Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(spend): rebuild the auto-router benchmarks backend as a per-session rollup (#35910)

tin-berri32deaff01535
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260805000000_add_autorouter_session_rollup/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260805000000_add_autorouter_session_rollup/migration.sql
new file mode 100644
index 00000000000..1b4e0d3b4d6
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260805000000_add_autorouter_session_rollup/migration.sql
@@ -0,0 +1,31 @@
+CREATE TABLE IF NOT EXISTS "LiteLLM_AutoRouterSession" (
+ "api_key" TEXT NOT NULL,
+ "session_id" TEXT NOT NULL,
+ "router_name" TEXT NOT NULL,
+ "router_type" TEXT NOT NULL,
+ "first_turn_at" TIMESTAMP(3) NOT NULL,
+ "last_turn_at" TIMESTAMP(3) NOT NULL,
+ "last_model" TEXT NOT NULL,
+ "models" JSONB NOT NULL DEFAULT '{}',
+ "turns" INTEGER NOT NULL DEFAULT 0,
+ "unordered_turns" INTEGER NOT NULL DEFAULT 0,
+ "covered_turns" INTEGER NOT NULL DEFAULT 0,
+ "cache_hits" INTEGER NOT NULL DEFAULT 0,
+ "same_model_turns" INTEGER NOT NULL DEFAULT 0,
+ "same_model_hits" INTEGER NOT NULL DEFAULT 0,
+ "first_visit_turns" INTEGER NOT NULL DEFAULT 0,
+ "first_visit_hits" INTEGER NOT NULL DEFAULT 0,
+ "return_turns" INTEGER NOT NULL DEFAULT 0,
+ "return_hits" INTEGER NOT NULL DEFAULT 0,
+ "return_expired_misses" INTEGER NOT NULL DEFAULT 0,
+ "return_within_ttl_misses" INTEGER NOT NULL DEFAULT 0,
+ "ttl_5m_turns" INTEGER NOT NULL DEFAULT 0,
+ "ttl_1h_turns" INTEGER NOT NULL DEFAULT 0,
+ "total_tokens" BIGINT NOT NULL DEFAULT 0,
+ "spend" DOUBLE PRECISION NOT NULL DEFAULT 0,
+ "saved_spend" DOUBLE PRECISION NOT NULL DEFAULT 0,
+
+ CONSTRAINT "LiteLLM_AutoRouterSession_pkey" PRIMARY KEY ("api_key", "session_id", "router_name")
+);
+
+CREATE INDEX IF NOT EXISTS "idx_autorouter_session_last_turn" ON "LiteLLM_AutoRouterSession"("last_turn_at");
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
index 3a7882b6d2b..b6557e3006d 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
@@ -1413,6 +1413,37 @@ model LiteLLM_AdaptiveRouterSession {
@@index([last_activity_at], map: "idx_adaptive_router_session_activity")
}
+model LiteLLM_AutoRouterSession {
+ api_key String
+ session_id String
+ router_name String
+ router_type String
+ first_turn_at DateTime
+ last_turn_at DateTime
+ last_model String
+ models Json @default("{}")
+ turns Int @default(0)
+ unordered_turns Int @default(0)
+ covered_turns Int @default(0)
+ cache_hits Int @default(0)
+ same_model_turns Int @default(0)
+ same_model_hits Int @default(0)
+ first_visit_turns Int @default(0)
+ first_visit_hits Int @default(0)
+ return_turns Int @default(0)
+ return_hits Int @default(0)
+ return_expired_misses Int @default(0)
+ return_within_ttl_misses Int @default(0)
+ ttl_5m_turns Int @default(0)
+ ttl_1h_turns Int @default(0)
+ total_tokens BigInt @default(0)
+ spend Float @default(0)
+ saved_spend Float @default(0)
+
+ @@id([api_key, session_id, router_name])
+ @@index([last_turn_at], map: "idx_autorouter_session_last_turn")
+}
+
// ---------------------------------------------------------------------------
// Workflow Run Tracking
//
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 7a68fb24f43..7bc8ed59a6a 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -2432,6 +2432,10 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase):
None,
description="Maximum retention period for spend logs (e.g., '7d' for 7 days). Logs older than this will be deleted.",
)
+ maximum_autorouter_session_retention_period: str | None = Field(
+ None,
+ description="Maximum retention period for auto-router benchmark session rollup rows (e.g., '365d'). Rows whose last turn is older than this are deleted by the spend log cleanup job, on that job's schedule. Unset means rollup rows are never deleted.",
+ )
use_spend_logs_partitioning: bool | None = Field(
None,
description="If True and LiteLLM_SpendLogs has been converted to a range-partitioned table (db_scripts/partition_spend_logs.sql), retention cleanup drops expired partitions instead of deleting rows, and pre-creates upcoming partitions. Default is False.",
diff --git a/litellm/proxy/db/autorouter_session_rollup.py b/litellm/proxy/db/autorouter_session_rollup.py
new file mode 100644
index 00000000000..da1652cdb61
--- /dev/null
+++ b/litellm/proxy/db/autorouter_session_rollup.py
@@ -0,0 +1,322 @@
+"""
+Per-session auto-router benchmarks rollup.
+
+At request time the spend writer builds one AutoRouterTurnTransaction per successful
+auto-routed request (a request whose metadata carries a routing_decision) and queues it
+on the prisma client. The spend-log flush job drains the queue into
+LiteLLM_AutoRouterSession with one conditional upsert per turn: the statement classifies
+the turn (same model, first visit, return to a model the session already used, out of
+order) against the row's own columns, so nothing is read before the write and concurrent
+pods compose. The benchmarks endpoint aggregates these rows and never touches
+LiteLLM_SpendLogs.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import hashlib
+import random
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from itertools import groupby
+from typing import TYPE_CHECKING, Final, NamedTuple
+
+from litellm._logging import verbose_proxy_logger
+from litellm.proxy._types import DB_RETRY_SAFE_ERROR_TYPES
+
+if TYPE_CHECKING:
+ from litellm.proxy._types import SpendLogsPayload
+ from litellm.proxy.utils import PrismaClient
+
+CACHE_TTL_5M_SECONDS: Final = 300
+CACHE_TTL_1H_SECONDS: Final = 3600
+
+
+@dataclass(frozen=True, slots=True)
+class AutoRouterTurnTransaction:
+ api_key: str
+ session_id: str
+ router_name: str
+ router_type: str
+ model: str
+ turn_at: datetime
+ total_tokens: int
+ spend: float
+ saved_spend: float
+ covered: bool
+ cache_hit: bool
+ cache_ttl_seconds: int | None
+ cache_touched: bool
+
+
+class TurnCacheFacts(NamedTuple):
+ """One statement of a turn's cache interaction, derived from its usage record.
+
+ ``touched`` is False only when telemetry positively shows the provider neither
+ read from nor wrote to the cache; absent telemetry reads as touched, which is
+ the conservative input for the per-model idle clock.
+ """
+
+ covered: bool
+ read_tokens: int
+ write_ttl_seconds: int | None
+ touched: bool
+
+
+def turn_cache_facts(usage_object: Mapping[str, object] | None) -> TurnCacheFacts:
+ from litellm.proxy.spend_tracking.savings import extract_cache_read_tokens
+
+ covered: Final = bool(usage_object)
+ read_tokens: Final = extract_cache_read_tokens(usage_object)
+ write_ttl_seconds: Final = _write_ttl_seconds(usage_object)
+ return TurnCacheFacts(
+ covered=covered,
+ read_tokens=read_tokens,
+ write_ttl_seconds=write_ttl_seconds,
+ touched=not covered or read_tokens > 0 or write_ttl_seconds is not None,
+ )
+
+
+def _turn_time_utc(start_time_iso: str) -> datetime | None:
+ try:
+ parsed: Final = datetime.fromisoformat(start_time_iso.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ return parsed
+ return parsed.astimezone(timezone.utc).replace(tzinfo=None)
+
+
+def _write_ttl_seconds(usage_object: Mapping[str, object] | None) -> int | None:
+ """The TTL this turn's cache write used, or None when nothing was written.
+
+ Providers that report a TTL split do so under prompt_tokens_details; a write with no
+ split is the provider's default five-minute cache.
+ """
+ from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens
+
+ if not usage_object:
+ return None
+ details: Final = usage_object.get("prompt_tokens_details")
+ creation: Final = details.get("cache_creation_token_details") if isinstance(details, Mapping) else None
+ if isinstance(creation, Mapping):
+ if creation.get("ephemeral_1h_input_tokens"):
+ return CACHE_TTL_1H_SECONDS
+ if creation.get("ephemeral_5m_input_tokens"):
+ return CACHE_TTL_5M_SECONDS
+ if extract_cache_creation_tokens(usage_object) > 0:
+ return CACHE_TTL_5M_SECONDS
+ return None
+
+
+SESSION_ID_MAX_CHARS: Final = 256
+
+
+def _bounded_session_id(session_id: str) -> str:
+ """The session id as stored, bounded so a caller-chosen identifier cannot exceed
+ Postgres's B-tree index entry limit through the composite primary key. Oversized
+ ids map to a stable digest, so their turns still aggregate into one session."""
+ if len(session_id) <= SESSION_ID_MAX_CHARS:
+ return session_id
+ return "sha256:" + hashlib.sha256(session_id.encode("utf-8", errors="surrogatepass")).hexdigest()
+
+
+def build_autorouter_turn_transaction(
+ payload: SpendLogsPayload,
+ metadata: Mapping[str, object],
+ saved_spend: float,
+) -> AutoRouterTurnTransaction | None:
+ """One rollup transaction for a successful auto-routed turn, else None.
+
+ The routing_decision record is what says a request was auto-routed at all, so a
+ request without one (including the auto-router's own classifier sub-calls) never
+ reaches the rollup. Failed requests served nothing and are excluded. Cache facts
+ are derived from the payload's own usage record through the savings owner, never
+ handed in beside it.
+ """
+ if payload.get("status") != "success":
+ return None
+ routing_decision: Final = metadata.get("routing_decision")
+ if not isinstance(routing_decision, Mapping) or not routing_decision:
+ return None
+ router_name: Final = routing_decision.get("router_model_name") or payload.get("model_group")
+ api_key: Final = payload.get("api_key")
+ session_id: Final = payload.get("session_id")
+ model: Final = payload.get("model")
+ if not (isinstance(router_name, str) and router_name and api_key and session_id and model):
+ return None
+ turn_at: Final = _turn_time_utc(str(payload.get("startTime") or ""))
+ if turn_at is None:
+ return None
+ usage_object_raw: Final = metadata.get("usage_object")
+ cache: Final = turn_cache_facts(usage_object_raw if isinstance(usage_object_raw, Mapping) else None)
+ return AutoRouterTurnTransaction(
+ api_key=api_key,
+ session_id=_bounded_session_id(session_id),
+ router_name=router_name,
+ router_type=str(routing_decision.get("router_type") or "unknown"),
+ model=model,
+ turn_at=turn_at,
+ total_tokens=int(payload.get("prompt_tokens") or 0) + int(payload.get("completion_tokens") or 0),
+ spend=float(payload.get("spend") or 0.0),
+ saved_spend=saved_spend,
+ covered=cache.covered,
+ cache_hit=cache.read_tokens > 0,
+ cache_ttl_seconds=cache.write_ttl_seconds,
+ cache_touched=cache.touched,
+ )
+
+
+_UPSERT_PARAM_FIELDS: Final = tuple(field.name for field in dataclasses.fields(AutoRouterTurnTransaction))
+
+
+def _p(field_name: str) -> str:
+ """Positional placeholder for a transaction field, numbered by the dataclass's own
+ field order so the SQL and the argument tuple cannot disagree; typos fail at import."""
+ return f"${_UPSERT_PARAM_FIELDS.index(field_name) + 1}"
+
+
+_MODEL: Final = _p("model")
+_TURN_AT: Final = _p("turn_at")
+_COVERED: Final = _p("covered")
+_CACHE_HIT: Final = _p("cache_hit")
+_CACHE_TTL: Final = _p("cache_ttl_seconds")
+_TOUCHED: Final = _p("cache_touched")
+
+_IN_ORDER: Final = f"{_TURN_AT}::timestamp >= t.last_turn_at"
+_SAME: Final = f"{_IN_ORDER} AND t.last_model = {_MODEL}"
+_FIRST: Final = f"{_IN_ORDER} AND NOT t.models ? {_MODEL}"
+_RETURN: Final = f"{_IN_ORDER} AND t.models ? {_MODEL} AND t.last_model <> {_MODEL}"
+_RETURN_MISS: Final = (
+ f"{_RETURN} AND {_COVERED}::int = 1 AND {_CACHE_HIT}::int = 0 AND (t.models -> {_MODEL} ->> 'ttl') IS NOT NULL"
+)
+_IDLE_SECONDS: Final = f"EXTRACT(EPOCH FROM {_TURN_AT}::timestamp) - (t.models -> {_MODEL} ->> 'at')::float8"
+_CACHE_TOUCHED: Final = f"{_TOUCHED}::int = 1"
+
+UPSERT_AUTOROUTER_SESSION_SQL: Final = f"""
+INSERT INTO "LiteLLM_AutoRouterSession" AS t (
+ api_key, session_id, router_name, router_type, first_turn_at, last_turn_at,
+ last_model, models, turns, unordered_turns, covered_turns, cache_hits,
+ same_model_turns, same_model_hits, first_visit_turns, first_visit_hits,
+ return_turns, return_hits, return_expired_misses, return_within_ttl_misses,
+ ttl_5m_turns, ttl_1h_turns, total_tokens, spend, saved_spend
+)
+VALUES (
+ {_p("api_key")}, {_p("session_id")}, {_p("router_name")}, {_p("router_type")}, {_TURN_AT}::timestamp, {_TURN_AT}::timestamp,
+ {_MODEL}, jsonb_build_object({_MODEL}, jsonb_build_object('at', EXTRACT(EPOCH FROM {_TURN_AT}::timestamp), 'ttl', {_CACHE_TTL}::int)),
+ 1, 0, {_COVERED}::int, {_CACHE_HIT}::int,
+ 0, 0, 1, {_CACHE_HIT}::int,
+ 0, 0, 0, 0,
+ (CASE WHEN {_CACHE_TTL}::int = {CACHE_TTL_5M_SECONDS} THEN 1 ELSE 0 END),
+ (CASE WHEN {_CACHE_TTL}::int = {CACHE_TTL_1H_SECONDS} THEN 1 ELSE 0 END),
+ {_p("total_tokens")}::bigint, {_p("spend")}::float8, {_p("saved_spend")}::float8
+)
+ON CONFLICT (api_key, session_id, router_name) DO UPDATE SET
+ turns = t.turns + 1,
+ total_tokens = t.total_tokens + EXCLUDED.total_tokens,
+ spend = t.spend + EXCLUDED.spend,
+ saved_spend = t.saved_spend + EXCLUDED.saved_spend,
+ covered_turns = t.covered_turns + EXCLUDED.covered_turns,
+ cache_hits = t.cache_hits + EXCLUDED.cache_hits,
+ ttl_5m_turns = t.ttl_5m_turns + EXCLUDED.ttl_5m_turns,
+ ttl_1h_turns = t.ttl_1h_turns + EXCLUDED.ttl_1h_turns,
+ unordered_turns = t.unordered_turns + (CASE WHEN NOT ({_IN_ORDER}) THEN 1 ELSE 0 END),
+ same_model_turns = t.same_model_turns + (CASE WHEN {_SAME} THEN 1 ELSE 0 END),
+ same_model_hits = t.same_model_hits + (CASE WHEN {_SAME} AND {_CACHE_HIT}::int = 1 THEN 1 ELSE 0 END),
+ first_visit_turns = t.first_visit_turns + (CASE WHEN {_FIRST} THEN 1 ELSE 0 END),
+ first_visit_hits = t.first_visit_hits + (CASE WHEN {_FIRST} AND {_CACHE_HIT}::int = 1 THEN 1 ELSE 0 END),
+ return_turns = t.return_turns + (CASE WHEN {_RETURN} THEN 1 ELSE 0 END),
+ return_hits = t.return_hits + (CASE WHEN {_RETURN} AND {_CACHE_HIT}::int = 1 THEN 1 ELSE 0 END),
+ return_expired_misses = t.return_expired_misses
+ + (CASE WHEN {_RETURN_MISS} AND {_IDLE_SECONDS} > (t.models -> {_MODEL} ->> 'ttl')::float8 THEN 1 ELSE 0 END),
+ return_within_ttl_misses = t.return_within_ttl_misses
+ + (CASE WHEN {_RETURN_MISS} AND {_IDLE_SECONDS} <= (t.models -> {_MODEL} ->> 'ttl')::float8 THEN 1 ELSE 0 END),
+ models = t.models || jsonb_build_object({_MODEL}, jsonb_build_object(
+ 'at', (CASE WHEN {_CACHE_TOUCHED}
+ THEN GREATEST(COALESCE((t.models -> {_MODEL} ->> 'at')::float8, 0), EXTRACT(EPOCH FROM {_TURN_AT}::timestamp))
+ ELSE COALESCE((t.models -> {_MODEL} ->> 'at')::float8, EXTRACT(EPOCH FROM {_TURN_AT}::timestamp)) END),
+ 'ttl', (CASE WHEN {_IN_ORDER}
+ THEN COALESCE({_CACHE_TTL}::int, (t.models -> {_MODEL} ->> 'ttl')::int)
+ ELSE COALESCE((t.models -> {_MODEL} ->> 'ttl')::int, {_CACHE_TTL}::int) END)
+ )),
+ last_model = (CASE WHEN {_IN_ORDER} THEN {_MODEL} ELSE t.last_model END),
+ first_turn_at = LEAST(t.first_turn_at, EXCLUDED.first_turn_at),
+ last_turn_at = GREATEST(t.last_turn_at, EXCLUDED.last_turn_at)
+"""
+
+
+def _as_sql_param(value: str | float | bool | datetime | None) -> str | float | None:
+ if isinstance(value, bool):
+ return int(value)
+ if isinstance(value, datetime):
+ return value.isoformat()
+ return value
+
+
+def _upsert_params(transaction: AutoRouterTurnTransaction) -> tuple[str | float | None, ...]:
+ return tuple(_as_sql_param(getattr(transaction, name)) for name in _UPSERT_PARAM_FIELDS)
+
+
+async def _upsert_turn_with_retry(
+ prisma_client: PrismaClient,
+ transaction: AutoRouterTurnTransaction,
+ n_retry_times: int,
+) -> None:
+ for attempt in range(n_retry_times + 1):
+ try:
+ await prisma_client.db.execute_raw(UPSERT_AUTOROUTER_SESSION_SQL, *_upsert_params(transaction))
+ except DB_RETRY_SAFE_ERROR_TYPES:
+ if attempt >= n_retry_times:
+ raise
+ await asyncio.sleep(2**attempt + random.uniform(0, 1))
+ else:
+ return
+
+
+async def flush_autorouter_turn_transactions(
+ prisma_client: PrismaClient,
+ transactions: Sequence[AutoRouterTurnTransaction],
+ n_retry_times: int = 3,
+) -> None:
+ """Drain a queue batch into the rollup, one upsert per turn.
+
+ Statements run sequentially in per-session event order: a turn's classification
+ depends on the turns before it, and Postgres rejects one multi-row INSERT touching
+ the same key twice. Only ConnectError is retried, per statement, because it proves
+ that statement never reached the database. Any other failure drops the remaining
+ turns of THAT session only, with an error log, and the flush continues with the
+ next session: sessions are independent state machines, so one poisoned statement
+ must not discard unrelated sessions, and a repeated increment is worse than an
+ undercount. Callers must not add their own retry around this function.
+ """
+ if not transactions:
+ return
+ ordered: Final = sorted(
+ transactions,
+ key=lambda transaction: (
+ transaction.api_key,
+ transaction.session_id,
+ transaction.router_name,
+ transaction.turn_at,
+ ),
+ )
+ for session_key, session_group in groupby(
+ ordered,
+ key=lambda transaction: (transaction.api_key, transaction.session_id, transaction.router_name),
+ ):
+ session_turns = tuple(session_group)
+ for position, transaction in enumerate(session_turns):
+ try:
+ await _upsert_turn_with_retry(prisma_client, transaction, n_retry_times)
+ except Exception as flush_err: # noqa: BLE001 # a statement failure drops only its session's remainder by design
+ verbose_proxy_logger.error(
+ "Spend tracking - auto-router session rollup flush failed for router %s; "
+ "%s of %s turn transactions dropped for one session: %s",
+ session_key[2],
+ len(session_turns) - position,
+ len(session_turns),
+ flush_err,
+ )
+ break
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.py
index bb37989d129..385a21976b7 100644
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@ -54,7 +54,11 @@ from litellm.proxy.route_llm_request import ROUTE_ENDPOINT_MAPPING
from litellm.proxy.spend_tracking.compression_savings import (
extract_compression_saved_tokens,
)
-from litellm.proxy.spend_tracking.savings import compute_savings_spend
+from litellm.proxy.spend_tracking.savings import (
+ compute_savings_spend,
+ extract_cache_creation_tokens,
+ extract_cache_read_tokens,
+)
from litellm.proxy.spend_tracking.spend_log_error_logger import spend_log_error
if TYPE_CHECKING:
@@ -84,31 +88,6 @@ def _get_llm_router():
return None
-def _extract_cache_read_tokens(usage_obj: dict) -> int:
- """
- Anthropic: top-level cache_read_input_tokens field.
- OpenAI-compatible (moonshotai, openai, deepseek, etc.): prompt_tokens_details.cached_tokens.
- """
- explicit: Final = usage_obj.get("cache_read_input_tokens", 0) or 0
- if explicit:
- return int(explicit)
- details: Final = usage_obj.get("prompt_tokens_details") or {}
- return int(details.get("cached_tokens", 0) or 0)
-
-
-def _extract_cache_creation_tokens(usage_obj: dict) -> int:
- """
- Anthropic: top-level cache_creation_input_tokens field.
- OpenAI-compatible (kimi-k2 etc.): prompt_tokens_details.cache_write_tokens
- or prompt_tokens_details.cache_creation_tokens.
- """
- explicit: Final = usage_obj.get("cache_creation_input_tokens", 0) or 0
- if explicit:
- return int(explicit)
- details: Final = usage_obj.get("prompt_tokens_details") or {}
- return int(details.get("cache_write_tokens", 0) or details.get("cache_creation_tokens", 0) or 0)
-
-
class DBSpendUpdateWriter:
"""
Module responsible for
@@ -204,6 +183,10 @@ class DBSpendUpdateWriter:
prisma_client=prisma_client,
kwargs=kwargs,
)
+ await self._enqueue_autorouter_turn_transaction(
+ payload=payload,
+ prisma_client=prisma_client,
+ )
else:
verbose_proxy_logger.debug(
"disable_spend_logs=True. Skipping writing spend logs to db. Other spend updates - Key/User/Team table will still occur."
@@ -275,6 +258,47 @@ class DBSpendUpdateWriter:
except Exception as e:
verbose_proxy_logger.debug("_enqueue_tool_usage_transaction error (non-blocking): %s", e)
+ async def _enqueue_autorouter_turn_transaction(
+ self,
+ payload: SpendLogsPayload,
+ prisma_client: "PrismaClient | None",
+ ) -> None:
+ try:
+ if prisma_client is None:
+ return
+ metadata_raw: Final = payload.get("metadata")
+ if not metadata_raw:
+ return
+ metadata: Final = json.loads(metadata_raw)
+ if not isinstance(metadata, dict) or not metadata.get("routing_decision"):
+ return
+ from litellm.proxy.db.autorouter_session_rollup import (
+ build_autorouter_turn_transaction,
+ )
+
+ usage_object_raw: Final = metadata.get("usage_object")
+ savings_spend: Final = compute_savings_spend(
+ model=payload.get("model"),
+ custom_llm_provider=payload.get("custom_llm_provider"),
+ compression_saved_tokens=0,
+ routing_decision=metadata.get("routing_decision"),
+ usage_object=usage_object_raw if isinstance(usage_object_raw, dict) else None,
+ model_id=payload.get("model_id"),
+ llm_router=_get_llm_router,
+ cost_breakdown=metadata.get("cost_breakdown"),
+ )
+ transaction: Final = build_autorouter_turn_transaction(
+ payload=payload,
+ metadata=metadata,
+ saved_spend=savings_spend.autorouter,
+ )
+ if transaction is None:
+ return
+ async with prisma_client._autorouter_turn_transactions_lock:
+ prisma_client.autorouter_turn_transactions.append(transaction)
+ except Exception as e: # noqa: BLE001 # a metrics enqueue must never fail the spend write
+ verbose_proxy_logger.debug("_enqueue_autorouter_turn_transaction error (non-blocking): %s", e)
+
def _enqueue_tool_registry_upsert(
self,
kwargs: dict | None,
@@ -1887,13 +1911,12 @@ class DBSpendUpdateWriter:
if call_type:
endpoint = ROUTE_ENDPOINT_MAPPING.get(call_type, None)
- cache_read_input_tokens: Final = _extract_cache_read_tokens(usage_obj)
+ cache_read_input_tokens: Final = extract_cache_read_tokens(usage_obj)
compression_saved_tokens: Final = extract_compression_saved_tokens(_metadata)
savings_spend: Final = compute_savings_spend(
model=payload.get("model", None),
custom_llm_provider=payload.get("custom_llm_provider", None),
compression_saved_tokens=compression_saved_tokens,
- cache_read_input_tokens=cache_read_input_tokens,
routing_decision=_metadata.get("routing_decision"),
model_id=payload.get("model_id"),
llm_router=_get_llm_router,
@@ -1916,7 +1939,7 @@ class DBSpendUpdateWriter:
successful_requests=1 if request_status == "success" else 0,
failed_requests=1 if request_status != "success" else 0,
cache_read_input_tokens=cache_read_input_tokens,
- cache_creation_input_tokens=_extract_cache_creation_tokens(usage_obj),
+ cache_creation_input_tokens=extract_cache_creation_tokens(usage_obj),
compression_saved_tokens=compression_saved_tokens,
compression_savings_spend=savings_spend.compression,
prompt_caching_savings_spend=savings_spend.prompt_caching,
diff --git a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
index 9e2a3acc42b..9f01c719a5f 100644
--- a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
+++ b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
@@ -46,32 +46,37 @@ class SpendLogCleanup:
self.pod_lock_manager = pod_lock_manager
verbose_proxy_logger.info("SpendLogCleanup initialized with batch size: %s", self.batch_size)
- def _should_delete_spend_logs(self) -> bool:
+ def _retention_seconds_for(self, setting_name: str) -> int | None:
"""
- Determines if logs should be deleted based on the max retention period in settings.
+ Parse one retention setting into seconds, or None when unset or invalid.
"""
- retention_setting = self.general_settings.get("maximum_spend_logs_retention_period")
- verbose_proxy_logger.info("Checking retention setting: %s", retention_setting)
+ retention_setting = self.general_settings.get(setting_name)
+ verbose_proxy_logger.info("Checking %s: %s", setting_name, retention_setting)
if retention_setting is None:
- verbose_proxy_logger.info("No retention setting found")
- return False
+ return None
try:
if isinstance(retention_setting, int):
verbose_proxy_logger.warning(
- "maximum_spend_logs_retention_period is an integer (%s); treating as days. Use a string like '3d' to be explicit.",
+ "%s is an integer (%s); treating as days. Use a string like '3d' to be explicit.",
+ setting_name,
retention_setting,
)
retention_setting = f"{retention_setting}d"
- self.retention_seconds = duration_in_seconds(retention_setting)
- verbose_proxy_logger.info("Retention period set to %s seconds", self.retention_seconds)
- return True
+ retention_seconds: Final = duration_in_seconds(retention_setting)
except ValueError as e:
- verbose_proxy_logger.warning(
- "Invalid maximum_spend_logs_retention_period value: %s, error: %s", retention_setting, e
- )
- return False
+ verbose_proxy_logger.warning("Invalid %s value: %s, error: %s", setting_name, retention_setting, e)
+ return None
+ verbose_proxy_logger.info("%s set to %s seconds", setting_name, retention_seconds)
+ return retention_seconds
+
+ def _should_delete_spend_logs(self) -> bool:
+ """
+ Determines if logs should be deleted based on the max retention period in settings.
+ """
+ self.retention_seconds = self._retention_seconds_for("maximum_spend_logs_retention_period")
+ return self.retention_seconds is not None
async def _delete_old_rows_batched(
self,
@@ -186,6 +191,15 @@ class SpendLogCleanup:
time_column="start_time",
)
+ async def _delete_old_autorouter_session_rows(self, prisma_client: PrismaClient, cutoff_date: datetime) -> int:
+ return await self._delete_old_rows_batched(
+ prisma_client,
+ cutoff_date,
+ table_name="LiteLLM_AutoRouterSession",
+ key_columns=("api_key", "session_id", "router_name"),
+ time_column="last_turn_at",
+ )
+
async def cleanup_old_spend_logs(self, prisma_client: PrismaClient) -> None:
"""
Main cleanup function. Deletes old spend logs in batches.
@@ -196,10 +210,14 @@ class SpendLogCleanup:
try:
verbose_proxy_logger.info("Cleanup job triggered at %s", datetime.now())
- if not self._should_delete_spend_logs():
+ delete_spend_logs: Final = self._should_delete_spend_logs()
+ autorouter_retention_seconds: Final = self._retention_seconds_for(
+ "maximum_autorouter_session_retention_period"
+ )
+ if not delete_spend_logs and autorouter_retention_seconds is None:
return
- if self.retention_seconds is None:
+ if delete_spend_logs and self.retention_seconds is None:
verbose_proxy_logger.error("Retention seconds is None, cannot proceed with cleanup")
return
@@ -219,31 +237,41 @@ class SpendLogCleanup:
verbose_proxy_logger.info("Another pod is already running cleanup")
return
- cutoff_date: Final = datetime.now(timezone.utc) - timedelta(seconds=float(self.retention_seconds))
- verbose_proxy_logger.info("Removing logs older than %s", cutoff_date.isoformat())
+ if delete_spend_logs and self.retention_seconds is not None:
+ cutoff_date: Final = datetime.now(timezone.utc) - timedelta(seconds=float(self.retention_seconds))
+ verbose_proxy_logger.info("Removing logs older than %s", cutoff_date.isoformat())
- if self.general_settings.get(
- "use_spend_logs_partitioning", False
- ) and await self.partition_manager.is_partitioned(prisma_client):
- await self.partition_manager.ensure_partitions(prisma_client)
- dropped: Final = await self.partition_manager.drop_partitions_older_than(prisma_client, cutoff_date)
- verbose_proxy_logger.info(
- "Dropped %d expired spend-log partitions: %s",
- len(dropped),
- dropped,
- )
- # DROP only reclaims whole expired partitions. Expired rows can
- # still sit in the DEFAULT partition (backfill, coverage gaps)
- # or in a partition that spans the cutoff, so retention must
- # also delete those stragglers row-wise.
- total_deleted = await self._delete_old_logs(prisma_client, cutoff_date)
- verbose_proxy_logger.info("Deleted %s expired logs not covered by dropped partitions", total_deleted)
- else:
- total_deleted = await self._delete_old_logs(prisma_client, cutoff_date)
- verbose_proxy_logger.info("Deleted %s logs", total_deleted)
+ if self.general_settings.get(
+ "use_spend_logs_partitioning", False
+ ) and await self.partition_manager.is_partitioned(prisma_client):
+ await self.partition_manager.ensure_partitions(prisma_client)
+ dropped: Final = await self.partition_manager.drop_partitions_older_than(prisma_client, cutoff_date)
+ verbose_proxy_logger.info(
+ "Dropped %d expired spend-log partitions: %s",
+ len(dropped),
+ dropped,
+ )
+ # DROP only reclaims whole expired partitions. Expired rows can
+ # still sit in the DEFAULT partition (backfill, coverage gaps)
+ # or in a partition that spans the cutoff, so retention must
+ # also delete those stragglers row-wise.
+ total_deleted = await self._delete_old_logs(prisma_client, cutoff_date)
+ verbose_proxy_logger.info(
+ "Deleted %s expired logs not covered by dropped partitions", total_deleted
+ )
+ else:
+ total_deleted = await self._delete_old_logs(prisma_client, cutoff_date)
+ verbose_proxy_logger.info("Deleted %s logs", total_deleted)
- index_deleted: Final = await self._delete_old_tool_index_rows(prisma_client, cutoff_date)
- verbose_proxy_logger.info("Deleted %s expired tool index rows", index_deleted)
+ index_deleted: Final = await self._delete_old_tool_index_rows(prisma_client, cutoff_date)
+ verbose_proxy_logger.info("Deleted %s expired tool index rows", index_deleted)
+
+ if autorouter_retention_seconds is not None:
+ session_cutoff: Final = datetime.now(timezone.utc) - timedelta(
+ seconds=float(autorouter_retention_seconds)
+ )
+ sessions_deleted: Final = await self._delete_old_autorouter_session_rows(prisma_client, session_cutoff)
+ verbose_proxy_logger.info("Deleted %s expired auto-router session rollup rows", sessions_deleted)
except Exception as e:
# .exception() captures the traceback; str(e) alone on a Prisma/DB
diff --git a/litellm/proxy/management_endpoints/auto_router_endpoints.py b/litellm/proxy/management_endpoints/auto_router_endpoints.py
index e1ac5ff6038..141094f4d4c 100644
--- a/litellm/proxy/management_endpoints/auto_router_endpoints.py
+++ b/litellm/proxy/management_endpoints/auto_router_endpoints.py
@@ -4,8 +4,12 @@ AUTO ROUTER MANAGEMENT ENDPOINTS
POST /auto_router/test_routing - Route one prompt through an unsaved complexity-router config
"""
+from collections.abc import Sequence
+from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Annotated, Final
+from pydantic import BaseModel, TypeAdapter
+
from litellm._logging import verbose_proxy_logger
from litellm.exceptions import BudgetExceededError
from litellm.proxy._types import (
@@ -25,18 +29,23 @@ from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup
from litellm.repositories.team_repository import TeamRepository
from litellm.router_strategy.complexity_router import ComplexityRouter
from litellm.types.management_endpoints.auto_router_endpoints import (
+ AutoRouterBenchmarkGroup,
+ AutoRouterBenchmarksResponse,
+ AutoRouterBenchmarkTotals,
+ AutoRouterCacheBucket,
+ AutoRouterCacheStats,
AutoRouterRoutingTestRequest,
AutoRouterRoutingTestResponse,
RequestComplexityRouterConfig,
)
if TYPE_CHECKING:
- from fastapi import APIRouter, Depends, HTTPException, status
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
from litellm.router import Router
else:
try:
- from fastapi import APIRouter, Depends, HTTPException, status
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
except ImportError:
# fastapi is only required for proxy, not for SDK usage
pass
@@ -246,3 +255,202 @@ async def preview_auto_router_routing(
routed_model_configured=hook_response.model in frozenset(llm_router.get_model_names()),
routing_decision=hook_response.routing_decision,
)
+
+
+class _SessionAggRow(BaseModel):
+ router_name: str
+ router_type: str
+ sessions: int
+ turns: int
+ unordered_turns: int
+ covered_turns: int
+ cache_hits: int
+ same_model_turns: int
+ same_model_hits: int
+ first_visit_turns: int
+ first_visit_hits: int
+ return_turns: int
+ return_hits: int
+ return_expired_misses: int
+ return_within_ttl_misses: int
+ ttl_5m_turns: int
+ ttl_1h_turns: int
+ total_tokens: int
+ spend: float
+ saved_spend: float
+ session_seconds: float
+
+
+_SESSION_AGG_ROWS: Final = TypeAdapter(list[_SessionAggRow])
+
+_BENCHMARKS_SQL: Final = """
+SELECT
+ router_name,
+ router_type,
+ COUNT(*)::int AS sessions,
+ COALESCE(SUM(turns), 0)::int AS turns,
+ COALESCE(SUM(unordered_turns), 0)::int AS unordered_turns,
+ COALESCE(SUM(covered_turns), 0)::int AS covered_turns,
+ COALESCE(SUM(cache_hits), 0)::int AS cache_hits,
+ COALESCE(SUM(same_model_turns), 0)::int AS same_model_turns,
+ COALESCE(SUM(same_model_hits), 0)::int AS same_model_hits,
+ COALESCE(SUM(first_visit_turns), 0)::int AS first_visit_turns,
+ COALESCE(SUM(first_visit_hits), 0)::int AS first_visit_hits,
+ COALESCE(SUM(return_turns), 0)::int AS return_turns,
+ COALESCE(SUM(return_hits), 0)::int AS return_hits,
+ COALESCE(SUM(return_expired_misses), 0)::int AS return_expired_misses,
+ COALESCE(SUM(return_within_ttl_misses), 0)::int AS return_within_ttl_misses,
+ COALESCE(SUM(ttl_5m_turns), 0)::int AS ttl_5m_turns,
+ COALESCE(SUM(ttl_1h_turns), 0)::int AS ttl_1h_turns,
+ COALESCE(SUM(total_tokens), 0)::bigint AS total_tokens,
+ COALESCE(SUM(spend), 0)::float8 AS spend,
+ COALESCE(SUM(saved_spend), 0)::float8 AS saved_spend,
+ COALESCE(SUM(EXTRACT(EPOCH FROM (last_turn_at - first_turn_at))), 0)::float8 AS session_seconds
+FROM "LiteLLM_AutoRouterSession"
+WHERE last_turn_at >= $1::timestamp AND first_turn_at < $2::timestamp
+GROUP BY router_name, router_type
+ORDER BY SUM(spend) DESC
+"""
+
+
+def _parse_benchmark_day(value: str) -> datetime:
+ try:
+ parsed: Final = datetime.strptime(value, "%Y-%m-%d").replace(tzinfo=timezone.utc)
+ except ValueError:
+ raise HTTPException(status_code=400, detail=f"Invalid date format: {value}. Expected: 'YYYY-MM-DD'")
+ return parsed.replace(tzinfo=None)
+
+
+def _pct(numerator: float, denominator: float) -> float:
+ if denominator <= 0:
+ return 0.0
+ return round(100.0 * numerator / denominator, 1)
+
+
+def _cache_bucket(turns: int, hits: int) -> AutoRouterCacheBucket:
+ return AutoRouterCacheBucket(turns=turns, hits=hits, hit_rate_pct=_pct(hits, turns))
+
+
+def _benchmark_totals(row: _SessionAggRow) -> AutoRouterBenchmarkTotals:
+ return_misses: Final = row.return_turns - row.return_hits
+ baseline_spend: Final = row.spend + row.saved_spend
+ sessions: Final = row.sessions
+ return AutoRouterBenchmarkTotals(
+ sessions=sessions,
+ turns=row.turns,
+ avg_turns_per_session=row.turns / sessions if sessions else 0.0,
+ avg_session_seconds=row.session_seconds / sessions if sessions else 0.0,
+ avg_tokens_per_session=row.total_tokens / sessions if sessions else 0.0,
+ spend=row.spend,
+ saved_spend=row.saved_spend,
+ baseline_spend=baseline_spend,
+ saved_pct=_pct(row.saved_spend, baseline_spend),
+ saved_per_session=row.saved_spend / sessions if sessions else 0.0,
+ cache=AutoRouterCacheStats(
+ coverage_pct=_pct(row.covered_turns, row.turns),
+ hit_rate_pct=_pct(row.cache_hits, row.covered_turns),
+ same_model=_cache_bucket(row.same_model_turns, row.same_model_hits),
+ first_visit=_cache_bucket(row.first_visit_turns, row.first_visit_hits),
+ return_to_tier=_cache_bucket(row.return_turns, row.return_hits),
+ unordered_turns=row.unordered_turns,
+ return_misses_expired=row.return_expired_misses,
+ return_misses_within_ttl=row.return_within_ttl_misses,
+ return_misses_unknown=max(return_misses - row.return_expired_misses - row.return_within_ttl_misses, 0),
+ ttl_5m_turns=row.ttl_5m_turns,
+ ttl_1h_turns=row.ttl_1h_turns,
+ ),
+ )
+
+
+def _summed_agg_row(rows: Sequence[_SessionAggRow]) -> _SessionAggRow:
+ return _SessionAggRow(
+ router_name="",
+ router_type="",
+ sessions=sum(row.sessions for row in rows),
+ turns=sum(row.turns for row in rows),
+ unordered_turns=sum(row.unordered_turns for row in rows),
+ covered_turns=sum(row.covered_turns for row in rows),
+ cache_hits=sum(row.cache_hits for row in rows),
+ same_model_turns=sum(row.same_model_turns for row in rows),
+ same_model_hits=sum(row.same_model_hits for row in rows),
+ first_visit_turns=sum(row.first_visit_turns for row in rows),
+ first_visit_hits=sum(row.first_visit_hits for row in rows),
+ return_turns=sum(row.return_turns for row in rows),
+ return_hits=sum(row.return_hits for row in rows),
+ return_expired_misses=sum(row.return_expired_misses for row in rows),
+ return_within_ttl_misses=sum(row.return_within_ttl_misses for row in rows),
+ ttl_5m_turns=sum(row.ttl_5m_turns for row in rows),
+ ttl_1h_turns=sum(row.ttl_1h_turns for row in rows),
+ total_tokens=sum(row.total_tokens for row in rows),
+ spend=sum(row.spend for row in rows),
+ saved_spend=sum(row.saved_spend for row in rows),
+ session_seconds=sum(row.session_seconds for row in rows),
+ )
+
+
+ "/auto_router/benchmarks",
+ tags=("auto router",),
+ dependencies=(Depends(user_api_key_auth),),
+ response_model=AutoRouterBenchmarksResponse,
+)
+async def get_auto_router_benchmarks(
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
+ start_date: Annotated[
+ str | None, Query(description="YYYY-MM-DD UTC, inclusive (defaults to 30 days before end_date)")
+ ] = None,
+ end_date: Annotated[str | None, Query(description="YYYY-MM-DD UTC, inclusive (defaults to today)")] = None,
+) -> AutoRouterBenchmarksResponse:
+ """
+ Benchmarks for the auto-router dashboard: session shape, savings against the configured
+ baseline, and prompt-caching behaviour bucketed by what the router did.
+
+ Reads the LiteLLM_AutoRouterSession rollup, folded once per request at spend-write time,
+ so this endpoint never scans LiteLLM_SpendLogs. A session is in the window when it
+ overlaps it: its last turn is on or after start_date and its first turn is on or before
+ end_date. Overall hit rate is over telemetry-bearing turns; each bucket's hit rate is
+ over that bucket's turns.
+ """
+ from litellm.proxy.proxy_server import prisma_client
+
+ if user_api_key_dict.user_role not in (
+ LitellmUserRoles.PROXY_ADMIN,
+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
+ ):
+ raise HTTPException(
+ status_code=403,
+ detail="Only proxy admin roles can view auto-router benchmarks across the deployment",
+ )
+ if prisma_client is None:
+ raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)
+
+ end_day: Final = (
+ _parse_benchmark_day(end_date)
+ if end_date
+ else datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
+ )
+ start_day: Final = _parse_benchmark_day(start_date) if start_date else end_day - timedelta(days=30)
+ if end_day < start_day:
+ raise HTTPException(status_code=400, detail="end_date must not be earlier than start_date")
+
+ raw_rows: Final = await prisma_client.db.query_raw(
+ _BENCHMARKS_SQL,
+ start_day.isoformat(),
+ (end_day + timedelta(days=1)).isoformat(),
+ )
+ rows: Final = _SESSION_AGG_ROWS.validate_python(raw_rows or ())
+ groups: Final = tuple(
+ AutoRouterBenchmarkGroup(
+ router_name=row.router_name,
+ router_type=row.router_type,
+ **_benchmark_totals(row).model_dump(),
+ )
+ for row in rows
+ )
+ return AutoRouterBenchmarksResponse(
+ start_date=start_day.strftime("%Y-%m-%d"),
+ end_date=end_day.strftime("%Y-%m-%d"),
+ routers_in_scope=len(rows),
+ totals=_benchmark_totals(_summed_agg_row(rows)),
+ groups=groups,
+ )
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 26112b4cc55..539b68c1aee 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -5969,7 +5969,8 @@ class ProxyConfig:
# Schedule new job if retention period is set (not None)
retention_period: Final = general_settings.get("maximum_spend_logs_retention_period")
- if retention_period is not None:
+ autorouter_retention: Final = general_settings.get("maximum_autorouter_session_retention_period")
+ if retention_period is not None or autorouter_retention is not None:
from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import (
SpendLogCleanup,
)
@@ -6090,6 +6091,13 @@ class ProxyConfig:
if old_value != new_value:
await self._reschedule_spend_log_cleanup_job()
+ if "maximum_autorouter_session_retention_period" in _general_settings:
+ old_session_value: Final = general_settings.get("maximum_autorouter_session_retention_period")
+ new_session_value: Final = _general_settings["maximum_autorouter_session_retention_period"]
+ general_settings["maximum_autorouter_session_retention_period"] = new_session_value
+ if old_session_value != new_session_value:
+ await self._reschedule_spend_log_cleanup_job()
+
for key in (
"user_url_allowed_hosts",
"user_url_validation",
@@ -8353,7 +8361,10 @@ class ProxyStartupEvent:
await cls._initialize_spend_tracking_background_jobs(scheduler=scheduler)
### SPEND LOG CLEANUP ###
- if general_settings.get("maximum_spend_logs_retention_period") is not None:
+ if (
+ general_settings.get("maximum_spend_logs_retention_period") is not None
+ or general_settings.get("maximum_autorouter_session_retention_period") is not None
+ ):
spend_log_cleanup: Final = SpendLogCleanup()
cleanup_cron: Final = general_settings.get("maximum_spend_logs_cleanup_cron")
diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma
index 3a7882b6d2b..b6557e3006d 100644
--- a/litellm/proxy/schema.prisma
+++ b/litellm/proxy/schema.prisma
@@ -1413,6 +1413,37 @@ model LiteLLM_AdaptiveRouterSession {
@@index([last_activity_at], map: "idx_adaptive_router_session_activity")
}
+model LiteLLM_AutoRouterSession {
+ api_key String
+ session_id String
+ router_name String
+ router_type String
+ first_turn_at DateTime
+ last_turn_at DateTime
+ last_model String
+ models Json @default("{}")
+ turns Int @default(0)
+ unordered_turns Int @default(0)
+ covered_turns Int @default(0)
+ cache_hits Int @default(0)
+ same_model_turns Int @default(0)
+ same_model_hits Int @default(0)
+ first_visit_turns Int @default(0)
+ first_visit_hits Int @default(0)
+ return_turns Int @default(0)
+ return_hits Int @default(0)
+ return_expired_misses Int @default(0)
+ return_within_ttl_misses Int @default(0)
+ ttl_5m_turns Int @default(0)
+ ttl_1h_turns Int @default(0)
+ total_tokens BigInt @default(0)
+ spend Float @default(0)
+ saved_spend Float @default(0)
+
+ @@id([api_key, session_id, router_name])
+ @@index([last_turn_at], map: "idx_autorouter_session_last_turn")
+}
+
// ---------------------------------------------------------------------------
// Workflow Run Tracking
//
diff --git a/litellm/proxy/spend_tracking/savings.py b/litellm/proxy/spend_tracking/savings.py
index a8fe023c802..3332afc0a4b 100644
--- a/litellm/proxy/spend_tracking/savings.py
+++ b/litellm/proxy/spend_tracking/savings.py
@@ -373,11 +373,57 @@ def _usage_from_spend_log(usage_object: Mapping[str, object] | None) -> Usage |
return None
+def extract_cache_read_tokens(usage_object: Mapping[str, object] | None) -> int:
+ """Cache-read tokens from a logged usage object, whatever shape recorded them.
+
+ Anthropic writes a top-level ``cache_read_input_tokens``; OpenAI-compatible
+ providers (moonshotai, openai, deepseek, etc.) write
+ ``prompt_tokens_details.cached_tokens``. This is the one owner of that
+ normalization: callers hand over the usage object rather than threading a
+ count that could disagree with it.
+ """
+ if not usage_object:
+ return 0
+ explicit: Final = usage_object.get("cache_read_input_tokens")
+ if isinstance(explicit, (int, float)) and explicit:
+ return int(explicit)
+ details: Final = usage_object.get("prompt_tokens_details")
+ if not isinstance(details, Mapping):
+ return 0
+ cached: Final = details.get("cached_tokens")
+ return int(cached) if isinstance(cached, (int, float)) else 0
+
+
+def extract_cache_creation_tokens(usage_object: Mapping[str, object] | None) -> int:
+ """Cache-write tokens from a logged usage object, whatever shape recorded them.
+
+ Anthropic writes a top-level ``cache_creation_input_tokens``; OpenAI-compatible
+ providers (kimi-k2 etc.) write ``prompt_tokens_details.cache_write_tokens`` or
+ ``prompt_tokens_details.cache_creation_tokens``.
+ """
+ if not usage_object:
+ return 0
+ explicit: Final = usage_object.get("cache_creation_input_tokens")
+ if isinstance(explicit, (int, float)) and explicit:
+ return int(explicit)
+ details: Final = usage_object.get("prompt_tokens_details")
+ if not isinstance(details, Mapping):
+ return 0
+ written: Final = next(
+ (
+ value
+ for value in (details.get("cache_write_tokens"), details.get("cache_creation_tokens"))
+ if isinstance(value, (int, float)) and value
+ ),
+ 0,
+ )
+ return int(written)
+
+
def compute_savings_spend(
model: str | None,
custom_llm_provider: str | None,
compression_saved_tokens: int,
- cache_read_input_tokens: int,
routing_decision: Mapping[str, object] | None = None,
usage_object: Mapping[str, object] | None = None,
model_id: str | None = None,
@@ -389,11 +435,13 @@ def compute_savings_spend(
Compression savings price the tokens compression removed at the model's
input rate. Prompt-caching savings price the cache-read tokens at the
- difference between the input rate and the discounted cache-read rate.
- Auto-router savings compare the served ``model`` against the counterfactual
- baseline the router recorded on its ``routing_decision``, and are zero unless the
- two differ. That record also says whether the conversation was already underway,
- which is what tells a mid-conversation switch from a first turn.
+ difference between the input rate and the discounted cache-read rate; the
+ read count is derived here from ``usage_object`` so no caller can hand in a
+ count that disagrees with the usage record. Auto-router savings compare the
+ served ``model`` against the counterfactual baseline the router recorded on
+ its ``routing_decision``, and are zero unless the two differ. That record
+ also says whether the conversation was already underway, which is what tells
+ a mid-conversation switch from a first turn.
``llm_router`` is passed as a provider rather than a router because every spend write
calls this and only auto-routed ones need one, so looking it up eagerly at the call
@@ -408,6 +456,7 @@ def compute_savings_spend(
"""
input_cost, cache_read_cost = _input_and_cache_read_cost(model, custom_llm_provider)
compression: Final = max(compression_saved_tokens, 0) * input_cost
+ cache_read_input_tokens: Final = extract_cache_read_tokens(usage_object)
prompt_caching: Final = max(cache_read_input_tokens, 0) * max(input_cost - cache_read_cost, 0.0)
usage: Final = _usage_from_spend_log(usage_object)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index ff7566df90c..46bb6e14a40 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -165,6 +165,7 @@ if TYPE_CHECKING:
from prisma.client import TransactionManager
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.proxy.db.autorouter_session_rollup import AutoRouterTurnTransaction
from litellm.proxy.db.spend_log_tool_index import ToolUsageTransaction
Span = _Span | Any
@@ -2994,6 +2995,10 @@ class PrismaClient:
_spend_log_transactions_lock = asyncio.Lock()
tool_usage_transactions: list["ToolUsageTransaction"] = []
_tool_usage_transactions_lock = asyncio.Lock()
+ autorouter_turn_transactions: ClassVar[
+ list["AutoRouterTurnTransaction"]
+ ] = [] # mutable-ok: drained queue, mirrors tool_usage_transactions
+ _autorouter_turn_transactions_lock = asyncio.Lock()
def __init__(
self,
@@ -5513,19 +5518,15 @@ async def update_spend(
### UPDATE SPEND LOGS ###
# Check queue size with lock protection
- async with prisma_client._spend_log_transactions_lock:
- queue_size: Final = len(prisma_client.spend_log_transactions)
+ queue_size: Final = await _total_queued_spend_transactions(prisma_client)
verbose_proxy_logger.debug("Spend Logs transactions: %s", queue_size)
- async with prisma_client._tool_usage_transactions_lock:
- tool_usage_queue_size: Final = len(prisma_client.tool_usage_transactions)
-
# Process spend log transactions when called directly.
# This keeps backwards compatibility with the old behavior.
# See update_spend_logs_job and _monitor_spend_logs_queue for the new behavior.
# Safe to keep: under high concurrency this can take up to ~30s to run,
# so it's unlikely to overlap with monitor_spend_logs_queue.
- if queue_size > 0 or tool_usage_queue_size > 0:
+ if queue_size > 0:
await update_spend_logs_job(
prisma_client=prisma_client,
db_writer_client=db_writer_client,
@@ -5533,6 +5534,19 @@ async def update_spend(
)
+async def _total_queued_spend_transactions(prisma_client: PrismaClient) -> int:
+ """Pending entries across every request-time spend queue, sized under each queue's
+ lock. Every drain trigger reads this one owner, so a queue added later joins the
+ direct path, the batch job's emptiness check and the monitor at once."""
+ async with prisma_client._spend_log_transactions_lock:
+ spend_queue_size: Final = len(prisma_client.spend_log_transactions)
+ async with prisma_client._tool_usage_transactions_lock:
+ tool_queue_size: Final = len(prisma_client.tool_usage_transactions)
+ async with prisma_client._autorouter_turn_transactions_lock:
+ autorouter_queue_size: Final = len(prisma_client.autorouter_turn_transactions)
+ return spend_queue_size + tool_queue_size + autorouter_queue_size
+
+
async def update_daily_tag_spend(
prisma_client: PrismaClient,
proxy_logging_obj: ProxyLogging,
@@ -5595,11 +5609,7 @@ async def update_spend_logs_job(
# Atomically pop batch from queue. The tool usage queue counts toward the
# emptiness check: a spend-log write failure aborts a run before the tool
# drain below, and those entries must not strand once the spend queue drains.
- async with prisma_client._spend_log_transactions_lock:
- queue_size: Final = len(prisma_client.spend_log_transactions)
- async with prisma_client._tool_usage_transactions_lock:
- tool_queue_size: Final = len(prisma_client.tool_usage_transactions)
- if queue_size == 0 and tool_queue_size == 0:
+ if await _total_queued_spend_transactions(prisma_client) == 0:
return
async with prisma_client._spend_log_transactions_lock:
@@ -5650,6 +5660,26 @@ async def update_spend_logs_job(
tool_tracking_err,
)
+ async with prisma_client._autorouter_turn_transactions_lock:
+ autorouter_turns_to_process: Final = prisma_client.autorouter_turn_transactions[:MAX_LOGS_PER_INTERVAL]
+ remaining_autorouter_turns: Final = prisma_client.autorouter_turn_transactions[
+ len(autorouter_turns_to_process) :
+ ]
+ prisma_client.autorouter_turn_transactions = remaining_autorouter_turns # rebind-ok: drain under lock
+ try:
+ from litellm.proxy.db.autorouter_session_rollup import flush_autorouter_turn_transactions
+
+ await flush_autorouter_turn_transactions(
+ prisma_client=prisma_client,
+ transactions=autorouter_turns_to_process,
+ )
+ except Exception as autorouter_tracking_err: # noqa: BLE001 # a drain bug must not abort the spend job
+ verbose_proxy_logger.error(
+ "Spend tracking - auto-router session rollup drain failed; %s turn transactions dropped: %s",
+ len(autorouter_turns_to_process),
+ autorouter_tracking_err,
+ )
+
async def _monitor_spend_logs_queue(
prisma_client: PrismaClient,
@@ -5684,11 +5714,7 @@ async def _monitor_spend_logs_queue(
try:
# Check queue sizes with lock protection; the tool usage queue keeps
# the monitor firing when a prior failed run left it nonempty.
- async with prisma_client._spend_log_transactions_lock:
- spend_queue_size = len(prisma_client.spend_log_transactions)
- async with prisma_client._tool_usage_transactions_lock:
- tool_queue_size = len(prisma_client.tool_usage_transactions)
- queue_size = spend_queue_size + tool_queue_size
+ queue_size = await _total_queued_spend_transactions(prisma_client)
if queue_size > 0:
if queue_size >= threshold:
diff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.py
index 2190db4a739..6c8fb96a729 100644
--- a/litellm/types/management_endpoints/auto_router_endpoints.py
+++ b/litellm/types/management_endpoints/auto_router_endpoints.py
@@ -60,3 +60,73 @@ class AutoRouterRoutingTestResponse(BaseModel):
routing_decision: StandardLoggingRoutingDecision = Field(
description="The decision record this request would have written to its log row",
)
+
+
+class AutoRouterCacheBucket(BaseModel):
+ """One prompt-caching bucket of turns, with how often those turns hit the cache."""
+
+ turns: int = Field(description="Turns classified into this bucket")
+ hits: int = Field(description="Turns in this bucket whose response reported cache-read tokens")
+ hit_rate_pct: float = Field(description="hits over this bucket's turns, as a percentage")
+
+
+class AutoRouterCacheStats(BaseModel):
+ """Prompt-caching behaviour of auto-routed turns, bucketed by what the router did.
+
+ Every in-order turn falls in exactly one bucket: the session stayed on the same model,
+ visited a model for the first time (cold by design), or returned to a model it had
+ already used. Out-of-order turns (cross-pod flush races) are counted but not bucketed.
+ """
+
+ coverage_pct: float = Field(description="Share of turns that carried cache telemetry")
+ hit_rate_pct: float = Field(description="All cache hits over telemetry-bearing turns")
+ same_model: AutoRouterCacheBucket
+ first_visit: AutoRouterCacheBucket
+ return_to_tier: AutoRouterCacheBucket
+ unordered_turns: int = Field(description="Turns that arrived out of order and were not bucketed")
+ return_misses_expired: int = Field(
+ description="Return-to-tier misses where the model's recorded cache TTL had lapsed"
+ )
+ return_misses_within_ttl: int = Field(
+ description="Return-to-tier misses inside the recorded TTL: the prefix changed or the provider "
+ "evicted the entry early; billing telemetry cannot distinguish the two"
+ )
+ return_misses_unknown: int = Field(description="Return-to-tier misses with no recorded TTL to attribute against")
+ ttl_5m_turns: int = Field(description="Turns whose cache write used the five-minute TTL")
+ ttl_1h_turns: int = Field(description="Turns whose cache write used the one-hour TTL")
+
+
+class AutoRouterBenchmarkTotals(BaseModel):
+ """Session-shape and savings aggregates over auto-routed traffic in the window."""
+
+ sessions: int
+ turns: int
+ avg_turns_per_session: float
+ avg_session_seconds: float
+ avg_tokens_per_session: float
+ spend: float = Field(description="What the routed traffic actually cost")
+ saved_spend: float = Field(
+ description="Signed dollars saved versus each router's savings baseline (derived from its hardest "
+ "tier, or the configured override), from the same per-request savings record the usage tab reads"
+ )
+ baseline_spend: float = Field(description="spend plus saved_spend: the estimated single-model cost")
+ saved_pct: float = Field(description="saved_spend over baseline_spend, as a percentage")
+ saved_per_session: float
+ cache: AutoRouterCacheStats
+
+
+class AutoRouterBenchmarkGroup(AutoRouterBenchmarkTotals):
+ """One auto-router's slice of the benchmarks."""
+
+ router_name: str = Field(description="The auto-router alias requests were sent to")
+ router_type: str = Field(description="complexity, adaptive or quality")
+
+
+class AutoRouterBenchmarksResponse(BaseModel):
+ """Benchmarks for the auto-router dashboard, aggregated from the per-session rollup."""
+
+ start_date: str = Field(description="Window start day, YYYY-MM-DD UTC, inclusive")
+ end_date: str = Field(description="Window end day, YYYY-MM-DD UTC, inclusive")
+ routers_in_scope: int
+ totals: AutoRouterBenchmarkTotals
+ groups: tuple[AutoRouterBenchmarkGroup, ...]
diff --git a/schema.prisma b/schema.prisma
index 3a7882b6d2b..b6557e3006d 100644
--- a/schema.prisma
+++ b/schema.prisma
@@ -1413,6 +1413,37 @@ model LiteLLM_AdaptiveRouterSession {
@@index([last_activity_at], map: "idx_adaptive_router_session_activity")
}
+model LiteLLM_AutoRouterSession {
+ api_key String
+ session_id String
+ router_name String
+ router_type String
+ first_turn_at DateTime
+ last_turn_at DateTime
+ last_model String
+ models Json @default("{}")
+ turns Int @default(0)
+ unordered_turns Int @default(0)
+ covered_turns Int @default(0)
+ cache_hits Int @default(0)
+ same_model_turns Int @default(0)
+ same_model_hits Int @default(0)
+ first_visit_turns Int @default(0)
+ first_visit_hits Int @default(0)
+ return_turns Int @default(0)
+ return_hits Int @default(0)
+ return_expired_misses Int @default(0)
+ return_within_ttl_misses Int @default(0)
+ ttl_5m_turns Int @default(0)
+ ttl_1h_turns Int @default(0)
+ total_tokens BigInt @default(0)
+ spend Float @default(0)
+ saved_spend Float @default(0)
+
+ @@id([api_key, session_id, router_name])
+ @@index([last_turn_at], map: "idx_autorouter_session_last_turn")
+}
+
// ---------------------------------------------------------------------------
// Workflow Run Tracking
//
diff --git a/tests/proxy_behavior/spend/__init__.py b/tests/proxy_behavior/spend/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/proxy_behavior/spend/conftest.py b/tests/proxy_behavior/spend/conftest.py
new file mode 100644
index 00000000000..0b918401eac
--- /dev/null
+++ b/tests/proxy_behavior/spend/conftest.py
@@ -0,0 +1,12 @@
+"""Session-scoped Prisma client for spend-rollup behavior tests against a real Postgres."""
+
+import pytest_asyncio
+from prisma import Prisma
+
+
+@pytest_asyncio.fixture(scope="session", loop_scope="session")
+async def db():
+ client = Prisma()
+ await client.connect()
+ yield client
+ await client.disconnect()
diff --git a/tests/proxy_behavior/spend/test_autorouter_session_rollup.py b/tests/proxy_behavior/spend/test_autorouter_session_rollup.py
new file mode 100644
index 00000000000..aa734ee22cc
--- /dev/null
+++ b/tests/proxy_behavior/spend/test_autorouter_session_rollup.py
@@ -0,0 +1,219 @@
+"""
+Behavior tests for the LiteLLM_AutoRouterSession conditional upsert and the benchmarks
+aggregate, against a real Postgres. The classification lives in SQL, so these tests are
+the ones that exercise it; the builder and flush contracts are unit-tested in
+tests/test_litellm/proxy/db/test_autorouter_session_rollup.py.
+"""
+
+import asyncio
+import uuid
+from datetime import datetime, timedelta, timezone
+from typing import Final
+
+import pytest
+
+from litellm.proxy.db.autorouter_session_rollup import UPSERT_AUTOROUTER_SESSION_SQL
+from litellm.proxy.management_endpoints.auto_router_endpoints import _BENCHMARKS_SQL
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+T0 = datetime(2026, 8, 1, 12, 0, 0)
+
+
+def _utc_epoch(moment: datetime) -> float:
+ return moment.replace(tzinfo=timezone.utc).timestamp()
+
+
+async def _turn(
+ db,
+ key: str,
+ model: str,
+ at: datetime,
+ covered: int = 1,
+ hit: int = 0,
+ ttl: "int | None" = None,
+ session_id: str = "s1",
+ router: str = "auto-1",
+ router_type: str = "complexity",
+ tokens: int = 100,
+ spend: float = 0.01,
+ saved: float = 0.02,
+) -> None:
+ touched: Final = 1 if (hit or ttl is not None or not covered) else 0
+ await db.execute_raw(
+ UPSERT_AUTOROUTER_SESSION_SQL,
+ key, session_id, router, router_type, model, at.isoformat(), tokens, spend, saved, covered, hit, ttl, touched,
+ )
+
+
+async def _row(db, key: str, session_id: str = "s1", router: str = "auto-1") -> dict:
+ rows = await db.query_raw(
+ 'SELECT * FROM "LiteLLM_AutoRouterSession" WHERE api_key = $1 AND session_id = $2 AND router_name = $3',
+ key, session_id, router,
+ )
+ assert len(rows) == 1
+ return rows[0]
+
+
+async def test_every_turn_lands_in_exactly_one_bucket(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, ttl=300)
+ await _turn(db, key, "A", T0 + timedelta(seconds=10), hit=1)
+ await _turn(db, key, "B", T0 + timedelta(seconds=20), ttl=3600)
+ await _turn(db, key, "A", T0 + timedelta(seconds=30), hit=1)
+ await _turn(db, key, "B", T0 + timedelta(seconds=40))
+ await _turn(db, key, "A", T0 + timedelta(seconds=500))
+ await _turn(db, key, "A", T0 + timedelta(seconds=5))
+ await _turn(db, key, "B", T0 + timedelta(seconds=600), covered=0)
+
+ row = await _row(db, key)
+ assert row["turns"] == 8
+ assert row["same_model_turns"] == 1
+ assert row["same_model_hits"] == 1
+ assert row["first_visit_turns"] == 2
+ assert row["first_visit_hits"] == 0
+ assert row["return_turns"] == 4
+ assert row["return_hits"] == 1
+ assert row["unordered_turns"] == 1
+ assert (
+ row["same_model_turns"] + row["first_visit_turns"] + row["return_turns"] + row["unordered_turns"]
+ == row["turns"]
+ )
+ assert row["covered_turns"] == 7
+ assert row["cache_hits"] == 2
+ assert row["ttl_5m_turns"] == 1
+ assert row["ttl_1h_turns"] == 1
+
+
+async def test_return_misses_attribute_against_the_recorded_ttl(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, ttl=300)
+ await _turn(db, key, "B", T0 + timedelta(seconds=10), ttl=3600)
+ await _turn(db, key, "A", T0 + timedelta(seconds=400))
+ await _turn(db, key, "B", T0 + timedelta(seconds=410))
+
+ row = await _row(db, key)
+ assert row["return_expired_misses"] == 1
+ assert row["return_within_ttl_misses"] == 1
+
+
+async def test_a_return_miss_with_no_recorded_ttl_stays_unattributed(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0)
+ await _turn(db, key, "B", T0 + timedelta(seconds=10))
+ await _turn(db, key, "A", T0 + timedelta(seconds=20))
+
+ row = await _row(db, key)
+ assert row["return_turns"] == 1
+ assert row["return_expired_misses"] == 0
+ assert row["return_within_ttl_misses"] == 0
+
+
+async def test_a_hit_refreshes_the_models_cache_clock(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, ttl=300)
+ await _turn(db, key, "B", T0 + timedelta(seconds=250), ttl=3600)
+ await _turn(db, key, "A", T0 + timedelta(seconds=290), hit=1)
+ await _turn(db, key, "B", T0 + timedelta(seconds=300))
+ await _turn(db, key, "A", T0 + timedelta(seconds=560))
+
+ row = await _row(db, key)
+ assert row["return_within_ttl_misses"] == 2
+ assert row["return_expired_misses"] == 0
+ assert row["models"]["A"]["at"] == pytest.approx(_utc_epoch(T0 + timedelta(seconds=290)), abs=1)
+
+
+async def test_out_of_order_turns_do_not_rewind_the_session(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0 + timedelta(seconds=100), ttl=300)
+ await _turn(db, key, "B", T0 + timedelta(seconds=200))
+ await _turn(db, key, "A", T0)
+
+ row = await _row(db, key)
+ assert row["last_model"] == "B"
+ assert row["unordered_turns"] == 1
+ assert row["first_turn_at"].startswith("2026-08-01T12:00:00")
+ assert row["last_turn_at"].startswith("2026-08-01T12:03:20")
+ assert row["models"]["A"]["at"] == pytest.approx(_utc_epoch(T0 + timedelta(seconds=100)), abs=1)
+
+
+async def test_concurrent_writers_compose_without_losing_turns(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0)
+ await asyncio.gather(
+ *(_turn(db, key, "A", T0 + timedelta(seconds=1 + offset), hit=1) for offset in range(30))
+ )
+ row = await _row(db, key)
+ assert row["turns"] == 31
+ assert (
+ row["same_model_turns"] + row["first_visit_turns"] + row["return_turns"] + row["unordered_turns"]
+ == row["turns"]
+ )
+ assert row["spend"] == pytest.approx(0.31)
+
+
+async def test_the_benchmarks_aggregate_reads_only_overlapping_sessions(db):
+ key = f"k-{uuid.uuid4()}"
+ router = f"r-{uuid.uuid4()}"
+ in_window = f"s-{uuid.uuid4()}"
+ out_of_window = f"s-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, session_id=in_window, router=router, saved=0.5, spend=0.25)
+ await _turn(db, key, "B", T0 + timedelta(seconds=60), session_id=in_window, router=router, saved=0.5, spend=0.25)
+ await _turn(db, key, "A", T0 - timedelta(days=40), session_id=out_of_window, router=router)
+
+ rows = await db.query_raw(
+ _BENCHMARKS_SQL,
+ (T0 - timedelta(days=1)).isoformat(),
+ (T0 + timedelta(days=1)).isoformat(),
+ )
+ matching = [row for row in rows if row["router_name"] == router]
+ assert len(matching) == 1
+ grouped = matching[0]
+ assert grouped["router_type"] == "complexity"
+ assert grouped["sessions"] == 1
+ assert grouped["turns"] == 2
+ assert grouped["spend"] == pytest.approx(0.5)
+ assert grouped["saved_spend"] == pytest.approx(1.0)
+ assert grouped["session_seconds"] == pytest.approx(60.0)
+
+
+async def test_a_reconfigured_alias_reports_each_router_type_as_its_own_group(db):
+ key = f"k-{uuid.uuid4()}"
+ router = f"r-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, session_id=f"s-{uuid.uuid4()}", router=router, router_type="complexity")
+ await _turn(db, key, "A", T0 + timedelta(seconds=10), session_id=f"s-{uuid.uuid4()}", router=router, router_type="quality")
+
+ rows = await db.query_raw(
+ _BENCHMARKS_SQL,
+ (T0 - timedelta(days=1)).isoformat(),
+ (T0 + timedelta(days=1)).isoformat(),
+ )
+ matching = sorted(
+ (row for row in rows if row["router_name"] == router),
+ key=lambda row: row["router_type"],
+ )
+ assert [(row["router_type"], row["sessions"]) for row in matching] == [("complexity", 1), ("quality", 1)]
+
+
+async def test_a_miss_that_touched_no_cache_does_not_advance_the_ttl_clock(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0, ttl=300)
+ await _turn(db, key, "B", T0 + timedelta(seconds=10), ttl=3600)
+ await _turn(db, key, "A", T0 + timedelta(seconds=400))
+ await _turn(db, key, "B", T0 + timedelta(seconds=410))
+ await _turn(db, key, "A", T0 + timedelta(seconds=600))
+
+ row = await _row(db, key)
+ assert row["return_expired_misses"] == 2
+ assert row["models"]["A"]["at"] == pytest.approx(_utc_epoch(T0), abs=1)
+
+
+async def test_an_out_of_order_hit_still_counts_toward_the_overall_hit_rate(db):
+ key = f"k-{uuid.uuid4()}"
+ await _turn(db, key, "A", T0 + timedelta(seconds=100))
+ await _turn(db, key, "A", T0 + timedelta(seconds=50), hit=1)
+
+ row = await _row(db, key)
+ assert row["unordered_turns"] == 1
+ assert row["cache_hits"] == 1
+ assert row["same_model_hits"] + row["first_visit_hits"] + row["return_hits"] == 0
diff --git a/tests/proxy_unit_tests/test_update_spend.py b/tests/proxy_unit_tests/test_update_spend.py
index 131f46a3e21..96a57c427e7 100644
--- a/tests/proxy_unit_tests/test_update_spend.py
+++ b/tests/proxy_unit_tests/test_update_spend.py
@@ -29,12 +29,14 @@ class MockPrismaClient:
self.spend_log_transactions = []
self.daily_user_spend_transactions = {}
self.tool_usage_transactions = []
+ self.autorouter_turn_transactions = []
# Add locks for the transaction queues (matches real PrismaClient)
import asyncio
self._spend_log_transactions_lock = asyncio.Lock()
self._tool_usage_transactions_lock = asyncio.Lock()
+ self._autorouter_turn_transactions_lock = asyncio.Lock()
def jsonify_object(self, obj):
return obj
diff --git a/tests/test_litellm/proxy/db/test_autorouter_session_rollup.py b/tests/test_litellm/proxy/db/test_autorouter_session_rollup.py
new file mode 100644
index 00000000000..aa7d01bc880
--- /dev/null
+++ b/tests/test_litellm/proxy/db/test_autorouter_session_rollup.py
@@ -0,0 +1,263 @@
+"""
+Unit tests for the auto-router per-session benchmarks rollup writer.
+
+The classification SQL itself runs against a real Postgres in
+tests/proxy_behavior/spend/test_autorouter_session_rollup.py; these tests cover the
+request-time transaction builder and the flush contract with an injected fake client.
+"""
+
+import asyncio
+import json
+from datetime import datetime
+
+import httpx
+import pytest
+
+from litellm.proxy.db.autorouter_session_rollup import (
+ AutoRouterTurnTransaction,
+ UPSERT_AUTOROUTER_SESSION_SQL,
+ build_autorouter_turn_transaction,
+ flush_autorouter_turn_transactions,
+)
+
+ROUTING_DECISION = {"router_model_name": "live-auto", "router_type": "complexity", "routed_model": "haiku"}
+
+
+def _payload(**overrides: object) -> dict:
+ base: dict = {
+ "status": "success",
+ "api_key": "hashed-key",
+ "session_id": "session-1",
+ "model": "bedrock/haiku",
+ "model_group": "live-auto",
+ "startTime": "2026-08-01T12:00:00",
+ "spend": 0.01,
+ "prompt_tokens": 90,
+ "completion_tokens": 10,
+ }
+ base.update(overrides)
+ return base
+
+
+def _metadata(**overrides: object) -> dict:
+ base: dict = {"routing_decision": dict(ROUTING_DECISION), "usage_object": {"prompt_tokens": 90}}
+ base.update(overrides)
+ return base
+
+
+def _build(payload: dict | None = None, metadata: dict | None = None):
+ return build_autorouter_turn_transaction(
+ payload=payload if payload is not None else _payload(),
+ metadata=metadata if metadata is not None else _metadata(),
+ saved_spend=0.02,
+ )
+
+
+class TestBuildTransaction:
+ def test_successful_auto_routed_turn_builds_every_field(self):
+ transaction = _build(
+ metadata=_metadata(
+ usage_object={"prompt_tokens": 90, "cache_read_input_tokens": 5, "cache_creation_input_tokens": 7}
+ )
+ )
+ assert transaction == AutoRouterTurnTransaction(
+ api_key="hashed-key",
+ session_id="session-1",
+ router_name="live-auto",
+ router_type="complexity",
+ model="bedrock/haiku",
+ turn_at=datetime(2026, 8, 1, 12, 0, 0),
+ total_tokens=100,
+ spend=0.01,
+ saved_spend=0.02,
+ covered=True,
+ cache_hit=True,
+ cache_ttl_seconds=300,
+ cache_touched=True,
+ )
+
+ @pytest.mark.parametrize(
+ "payload_overrides",
+ [
+ {"status": "failure"},
+ {"api_key": ""},
+ {"session_id": None},
+ {"model": ""},
+ {"startTime": "not-a-time"},
+ ],
+ )
+ def test_incomplete_payloads_are_skipped(self, payload_overrides: dict):
+ assert _build(payload=_payload(**payload_overrides)) is None
+
+ @pytest.mark.parametrize("metadata", [{}, {"routing_decision": None}, {"routing_decision": {}}])
+ def test_requests_without_a_routing_decision_are_skipped(self, metadata: dict):
+ assert _build(metadata=metadata) is None
+
+ def test_router_name_falls_back_to_the_payload_model_group(self):
+ transaction = _build(metadata=_metadata(routing_decision={"router_type": "complexity"}))
+ assert transaction is not None and transaction.router_name == "live-auto"
+
+ def test_one_hour_ttl_detail_beats_the_five_minute_default(self):
+ metadata = _metadata(
+ usage_object={
+ "prompt_tokens": 90,
+ "cache_creation_input_tokens": 4,
+ "prompt_tokens_details": {"cache_creation_token_details": {"ephemeral_1h_input_tokens": 4}},
+ }
+ )
+ transaction = _build(metadata=metadata)
+ assert transaction is not None and transaction.cache_ttl_seconds == 3600
+
+ def test_a_cache_write_without_ttl_detail_is_the_provider_default_five_minutes(self):
+ transaction = _build(metadata=_metadata(usage_object={"prompt_tokens": 90, "cache_creation_input_tokens": 12}))
+ assert transaction is not None and transaction.cache_ttl_seconds == 300
+
+ def test_a_turn_that_wrote_nothing_records_no_ttl(self):
+ transaction = _build()
+ assert transaction is not None and transaction.cache_ttl_seconds is None
+
+ def test_a_turn_without_usage_telemetry_is_uncovered(self):
+ transaction = _build(metadata=_metadata(usage_object={}))
+ assert transaction is not None
+ assert transaction.covered is False
+ assert transaction.cache_ttl_seconds is None
+ assert transaction.cache_touched is True
+
+ def test_a_covered_turn_that_neither_read_nor_wrote_did_not_touch_the_cache(self):
+ transaction = _build()
+ assert transaction is not None
+ assert transaction.covered is True
+ assert transaction.cache_touched is False
+
+ def test_an_oversized_session_id_is_bounded_to_a_stable_digest(self):
+ long_id = "x" * 3000
+ first = _build(payload=_payload(session_id=long_id))
+ second = _build(payload=_payload(session_id=long_id))
+ assert first is not None and second is not None
+ assert first.session_id == second.session_id
+ assert first.session_id.startswith("sha256:")
+ assert len(first.session_id) < 100
+
+ def test_a_normal_session_id_is_stored_verbatim(self):
+ transaction = _build(payload=_payload(session_id="sess-" + "a" * 200))
+ assert transaction is not None and transaction.session_id == "sess-" + "a" * 200
+
+ def test_timezone_aware_start_times_normalize_to_utc(self):
+ transaction = _build(payload=_payload(startTime="2026-08-01T14:00:00+02:00"))
+ assert transaction is not None and transaction.turn_at == datetime(2026, 8, 1, 12, 0, 0)
+
+
+class _FakeDB:
+ def __init__(self, failures: "list[Exception] | None" = None, poison_session: str | None = None):
+ self.calls: list[tuple] = []
+ self._failures = list(failures or [])
+ self._poison_session = poison_session
+
+ async def execute_raw(self, sql: str, *params: object) -> int:
+ if self._poison_session is not None and params[1] == self._poison_session:
+ raise RuntimeError("index row size exceeds btree maximum")
+ if self._failures:
+ raise self._failures.pop(0)
+ self.calls.append((sql, params))
+ return 1
+
+
+class _FakeClient:
+ def __init__(self, failures: "list[Exception] | None" = None, poison_session: str | None = None):
+ self.db = _FakeDB(failures, poison_session)
+
+
+def _transaction(session_id: str = "s1", at: datetime = datetime(2026, 8, 1, 12, 0, 0)) -> AutoRouterTurnTransaction:
+ return AutoRouterTurnTransaction(
+ api_key="k1",
+ session_id=session_id,
+ router_name="live-auto",
+ router_type="complexity",
+ model="bedrock/haiku",
+ turn_at=at,
+ total_tokens=100,
+ spend=0.01,
+ saved_spend=0.02,
+ covered=True,
+ cache_hit=False,
+ cache_ttl_seconds=None,
+ cache_touched=False,
+ )
+
+
+class TestFlush:
+ def test_turns_replay_in_per_session_event_order(self):
+ client = _FakeClient()
+ first = _transaction(at=datetime(2026, 8, 1, 12, 0, 0))
+ second = _transaction(at=datetime(2026, 8, 1, 12, 0, 10))
+ asyncio.run(flush_autorouter_turn_transactions(client, [second, first]))
+ sent_times = [params[5] for _, params in client.db.calls]
+ assert sent_times == ["2026-08-01T12:00:00", "2026-08-01T12:00:10"]
+
+ def test_params_marshal_in_statement_order(self):
+ client = _FakeClient()
+ asyncio.run(flush_autorouter_turn_transactions(client, [_transaction()]))
+ sql, params = client.db.calls[0]
+ assert sql == UPSERT_AUTOROUTER_SESSION_SQL
+ assert params == (
+ "k1", "s1", "live-auto", "complexity", "bedrock/haiku",
+ "2026-08-01T12:00:00", 100, 0.01, 0.02, 1, 0, None, 0,
+ )
+
+ def test_a_connect_error_retries_the_same_statement(self):
+ client = _FakeClient(failures=[httpx.ConnectError("boom")])
+ asyncio.run(flush_autorouter_turn_transactions(client, [_transaction()]))
+ assert len(client.db.calls) == 1
+
+ def test_an_ambiguous_failure_drops_only_that_sessions_remaining_turns(self):
+ client = _FakeClient(poison_session="s1")
+ transactions = [
+ _transaction(session_id="s1", at=datetime(2026, 8, 1, 12, 0, 0)),
+ _transaction(session_id="s1", at=datetime(2026, 8, 1, 12, 0, 10)),
+ _transaction(session_id="s2", at=datetime(2026, 8, 1, 12, 0, 5)),
+ ]
+ asyncio.run(flush_autorouter_turn_transactions(client, transactions))
+ assert [params[1] for _, params in client.db.calls] == ["s2"]
+
+ def test_an_empty_batch_writes_nothing(self):
+ client = _FakeClient()
+ asyncio.run(flush_autorouter_turn_transactions(client, []))
+ assert client.db.calls == []
+
+
+class TestEnqueueSeam:
+ @pytest.mark.asyncio
+ async def test_update_database_seam_enqueues_only_auto_routed_success(self, monkeypatch: pytest.MonkeyPatch):
+ import litellm
+ from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter
+ from litellm.proxy.utils import PrismaClient
+
+ monkeypatch.setattr(litellm, "autorouter_savings_baseline_model", None)
+ monkeypatch.setattr(PrismaClient, "autorouter_turn_transactions", [])
+ writer = DBSpendUpdateWriter()
+ fake_prisma = type("P", (), {})()
+ fake_prisma._autorouter_turn_transactions_lock = asyncio.Lock()
+ fake_prisma.autorouter_turn_transactions = []
+
+ routed = _payload()
+ routed["metadata"] = json.dumps(_metadata())
+ await writer._enqueue_autorouter_turn_transaction(payload=routed, prisma_client=fake_prisma)
+
+ plain = _payload()
+ plain["metadata"] = json.dumps({"usage_object": {"prompt_tokens": 9}})
+ await writer._enqueue_autorouter_turn_transaction(payload=plain, prisma_client=fake_prisma)
+
+ assert [t.router_name for t in fake_prisma.autorouter_turn_transactions] == ["live-auto"]
+ assert fake_prisma.autorouter_turn_transactions[0].saved_spend == 0.0
+
+
+def test_every_drain_trigger_reads_the_one_queue_census_owner():
+ import inspect
+
+ from litellm.proxy import utils as proxy_utils
+
+ owner_source = inspect.getsource(proxy_utils._total_queued_spend_transactions)
+ for queue in ("spend_log_transactions", "tool_usage_transactions", "autorouter_turn_transactions"):
+ assert queue in owner_source, queue
+ for site in (proxy_utils.update_spend, proxy_utils.update_spend_logs_job, proxy_utils._monitor_spend_logs_queue):
+ assert "_total_queued_spend_transactions" in inspect.getsource(site), site.__name__
diff --git a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
index 6aea2bcb19b..888db031515 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
@@ -284,3 +284,146 @@ def test_blank_prompt_is_rejected():
def test_semantic_matching_without_an_embedding_model_is_rejected():
with pytest.raises(ValidationError):
_request("what is 2+2", semantic_keyword_matching=True)
+
+
+class TestAutoRouterBenchmarks:
+ from litellm.proxy.management_endpoints.auto_router_endpoints import _SessionAggRow
+
+ ROW = _SessionAggRow(
+ router_name="live-auto",
+ router_type="complexity",
+ sessions=4,
+ turns=40,
+ unordered_turns=1,
+ covered_turns=38,
+ cache_hits=28,
+ same_model_turns=20,
+ same_model_hits=19,
+ first_visit_turns=8,
+ first_visit_hits=2,
+ return_turns=11,
+ return_hits=6,
+ return_expired_misses=2,
+ return_within_ttl_misses=1,
+ ttl_5m_turns=30,
+ ttl_1h_turns=5,
+ total_tokens=4000,
+ spend=10.0,
+ saved_spend=30.0,
+ session_seconds=400.0,
+ )
+
+ def test_overall_hit_rate_counts_hits_independently_of_bucketing(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import _benchmark_totals
+
+ totals = _benchmark_totals(self.ROW)
+ bucket_hits = (
+ totals.cache.same_model.hits + totals.cache.first_visit.hits + totals.cache.return_to_tier.hits
+ )
+ assert bucket_hits == 27
+ assert totals.cache.hit_rate_pct == pytest.approx(100.0 * 28 / 38, abs=0.1)
+
+ def test_fold_math_matches_hand_computed_truth(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import _benchmark_totals
+
+ totals = _benchmark_totals(self.ROW)
+ assert totals.sessions == 4
+ assert totals.turns == 40
+ assert totals.avg_turns_per_session == 10.0
+ assert totals.avg_session_seconds == 100.0
+ assert totals.avg_tokens_per_session == 1000.0
+ assert totals.baseline_spend == 40.0
+ assert totals.saved_pct == 75.0
+ assert totals.saved_per_session == 7.5
+ assert totals.cache.coverage_pct == 95.0
+ assert totals.cache.hit_rate_pct == pytest.approx(73.7)
+ assert totals.cache.same_model.hit_rate_pct == 95.0
+ assert totals.cache.first_visit.hit_rate_pct == 25.0
+ assert totals.cache.return_to_tier.hit_rate_pct == pytest.approx(54.5)
+ assert totals.cache.return_misses_unknown == 2
+ assert totals.cache.unordered_turns == 1
+
+ def test_a_losing_router_reports_negative_savings(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import _benchmark_totals
+
+ losing = self.ROW.model_copy(update={"saved_spend": -5.0})
+ totals = _benchmark_totals(losing)
+ assert totals.baseline_spend == 5.0
+ assert totals.saved_pct == -100.0
+
+ def test_an_empty_window_folds_to_zeros(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import (
+ _benchmark_totals,
+ _summed_agg_row,
+ )
+
+ totals = _benchmark_totals(_summed_agg_row([]))
+ assert totals.sessions == 0
+ assert totals.turns == 0
+ assert totals.saved_pct == 0.0
+ assert totals.cache.hit_rate_pct == 0.0
+
+ def test_totals_sum_counters_across_groups_before_deriving_ratios(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import (
+ _benchmark_totals,
+ _summed_agg_row,
+ )
+
+ other = self.ROW.model_copy(update={"router_name": "auto-2", "sessions": 1, "turns": 10, "spend": 0.0})
+ summed = _summed_agg_row([self.ROW, other])
+ totals = _benchmark_totals(summed)
+ assert summed.sessions == 5
+ assert summed.turns == 50
+ assert totals.avg_turns_per_session == 10.0
+ assert totals.spend == 10.0
+
+ @pytest.mark.asyncio
+ async def test_non_admin_roles_cannot_read_benchmarks(self):
+ from litellm.proxy.management_endpoints.auto_router_endpoints import get_auto_router_benchmarks
+
+ with pytest.raises(HTTPException) as err:
+ await get_auto_router_benchmarks(
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-x"),
+ start_date="2026-08-01",
+ end_date="2026-08-02",
+ )
+ assert err.value.status_code == 403
+
+ @pytest.mark.asyncio
+ async def test_a_reversed_window_is_rejected(self, monkeypatch: pytest.MonkeyPatch):
+ from litellm.proxy import proxy_server
+ from litellm.proxy.management_endpoints.auto_router_endpoints import get_auto_router_benchmarks
+
+ monkeypatch.setattr(proxy_server, "prisma_client", object())
+ with pytest.raises(HTTPException) as err:
+ await get_auto_router_benchmarks(
+ user_api_key_dict=ADMIN,
+ start_date="2026-08-05",
+ end_date="2026-08-01",
+ )
+ assert err.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_endpoint_returns_groups_and_totals_from_the_rollup(self, monkeypatch: pytest.MonkeyPatch):
+ from litellm.proxy import proxy_server
+ from litellm.proxy.management_endpoints.auto_router_endpoints import get_auto_router_benchmarks
+
+ captured: dict = {}
+
+ class _DB:
+ async def query_raw(self, sql: str, *params: object):
+ captured["sql"] = sql
+ captured["params"] = params
+ return [TestAutoRouterBenchmarks.ROW.model_dump()]
+
+ monkeypatch.setattr(proxy_server, "prisma_client", type("P", (), {"db": _DB()})())
+
+ response = await get_auto_router_benchmarks(
+ user_api_key_dict=ADMIN,
+ start_date="2026-07-01",
+ end_date="2026-08-01",
+ )
+ assert captured["params"] == ("2026-07-01T00:00:00", "2026-08-02T00:00:00")
+ assert response.routers_in_scope == 1
+ assert response.groups[0].router_name == "live-auto"
+ assert response.groups[0].saved_pct == response.totals.saved_pct == 75.0
diff --git a/tests/test_litellm/proxy/spend_tracking/test_savings.py b/tests/test_litellm/proxy/spend_tracking/test_savings.py
index bd5551c4d89..dc4f860ce00 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_savings.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_savings.py
@@ -62,7 +62,6 @@ def test_compression_savings_priced_at_input_rate():
model="claude-sonnet-5",
custom_llm_provider="anthropic",
compression_saved_tokens=4389,
- cache_read_input_tokens=0,
)
assert result.compression == pytest.approx(4389 * input_cost)
assert result.compression > 0
@@ -78,7 +77,7 @@ def test_prompt_caching_savings_priced_at_input_minus_cache_read():
model="claude-sonnet-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=8200,
+ usage_object={"cache_read_input_tokens": 8200},
)
assert result.prompt_caching == pytest.approx(8200 * (input_cost - cache_read_cost))
assert result.prompt_caching > 0
@@ -90,7 +89,7 @@ def test_unknown_model_fails_open_to_zero():
model="totally-made-up-model-xyz",
custom_llm_provider="anthropic",
compression_saved_tokens=1000,
- cache_read_input_tokens=1000,
+ usage_object={"cache_read_input_tokens": 1000},
)
assert result.compression == 0.0
assert result.prompt_caching == 0.0
@@ -101,7 +100,7 @@ def test_missing_model_fails_open_to_zero():
model=None,
custom_llm_provider=None,
compression_saved_tokens=1000,
- cache_read_input_tokens=1000,
+ usage_object={"cache_read_input_tokens": 1000},
)
assert result.compression == 0.0
assert result.prompt_caching == 0.0
@@ -112,7 +111,7 @@ def test_negative_token_counts_clamp_to_zero():
model="claude-sonnet-5",
custom_llm_provider="anthropic",
compression_saved_tokens=-500,
- cache_read_input_tokens=-500,
+ usage_object={"cache_read_input_tokens": -500},
)
assert result.compression == 0.0
assert result.prompt_caching == 0.0
@@ -290,7 +289,6 @@ def test_autorouter_savings_zero_without_baseline():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision=None,
usage_object=_cached_usage_object(),
)
@@ -305,7 +303,6 @@ def test_compute_savings_spend_carries_a_losing_switch_through(monkeypatch):
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True},
usage_object=_cached_usage_object(),
)
@@ -319,7 +316,6 @@ def test_the_driver_is_off_until_a_baseline_is_configured():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=1000,
- cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True},
usage_object=_cached_usage_object(),
)
@@ -334,7 +330,6 @@ def test_malformed_usage_object_does_not_fail_the_spend_write():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=1000,
- cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True},
usage_object={"prompt_tokens": ["not", "a", "number"]},
)
@@ -351,7 +346,7 @@ def test_model_without_cache_read_pricing_yields_no_caching_savings():
model=model,
custom_llm_provider="azure",
compression_saved_tokens=0,
- cache_read_input_tokens=5000,
+ usage_object={"cache_read_input_tokens": 5000},
)
assert result.prompt_caching == 0.0
@@ -622,7 +617,6 @@ def test_a_baseline_recorded_on_the_decision_turns_the_driver_on():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True, "savings_baseline_model": "anthropic/claude-opus-5"},
usage_object=_cached_usage_object(),
)
@@ -636,7 +630,6 @@ def test_the_configured_baseline_overrides_the_recorded_one(monkeypatch):
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision={
"conversation_continuing": True,
"savings_baseline_model": "anthropic/claude-opus-5",
@@ -665,7 +658,6 @@ def test_a_non_string_recorded_baseline_is_ignored():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True, "savings_baseline_model": ["anthropic/claude-opus-5"]},
usage_object=_cached_usage_object(),
)
@@ -697,7 +689,6 @@ def test_a_recorded_baseline_deployment_prices_at_its_configured_rate():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision=decision,
usage_object=_cached_usage_object(),
llm_router=lambda: router,
@@ -706,7 +697,6 @@ def test_a_recorded_baseline_deployment_prices_at_its_configured_rate():
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
- cache_read_input_tokens=0,
routing_decision={k: v for k, v in decision.items() if k != "savings_baseline_deployment_id"},
usage_object=_cached_usage_object(),
llm_router=lambda: router,
diff --git a/tests/test_litellm/proxy/test_spend_log_cleanup.py b/tests/test_litellm/proxy/test_spend_log_cleanup.py
index 2ba9257e1da..03eef14dacb 100644
--- a/tests/test_litellm/proxy/test_spend_log_cleanup.py
+++ b/tests/test_litellm/proxy/test_spend_log_cleanup.py
@@ -692,3 +692,64 @@ def test_cleanup_batch_size_env_var(monkeypatch):
monkeypatch.delenv("SPEND_LOG_CLEANUP_BATCH_SIZE", raising=False)
importlib.reload(constants_module)
importlib.reload(cleanup_module)
+
+
+def _mock_prisma_for_retention(side_effect: list) -> "MagicMock":
+ from unittest.mock import AsyncMock, MagicMock
+
+ client = MagicMock()
+ client.db.execute_raw = AsyncMock(side_effect=side_effect)
+ return client
+
+
+async def test_spend_logs_retention_alone_does_not_touch_the_session_rollup():
+ client = _mock_prisma_for_retention([0, 0])
+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})
+ cleaner.pod_lock_manager = None
+ await cleaner.cleanup_old_spend_logs(client)
+ tables = [call[0][0] for call in client.db.execute_raw.call_args_list]
+ assert any('"LiteLLM_SpendLogs"' in sql for sql in tables)
+ assert not any('"LiteLLM_AutoRouterSession"' in sql for sql in tables)
+
+
+async def test_session_retention_alone_cleans_only_the_session_rollup():
+ client = _mock_prisma_for_retention([0])
+ cleaner = SpendLogCleanup(general_settings={"maximum_autorouter_session_retention_period": "365d"})
+ cleaner.pod_lock_manager = None
+ await cleaner.cleanup_old_spend_logs(client)
+ tables = [call[0][0] for call in client.db.execute_raw.call_args_list]
+ assert len(tables) == 1
+ assert '"LiteLLM_AutoRouterSession"' in tables[0]
+
+
+async def test_each_retention_key_cuts_off_at_its_own_horizon():
+ from datetime import datetime, timezone
+
+ client = _mock_prisma_for_retention([0, 0, 0])
+ cleaner = SpendLogCleanup(
+ general_settings={
+ "maximum_spend_logs_retention_period": "7d",
+ "maximum_autorouter_session_retention_period": "365d",
+ }
+ )
+ cleaner.pod_lock_manager = None
+ await cleaner.cleanup_old_spend_logs(client)
+ cutoffs = {
+ ("LiteLLM_AutoRouterSession" if '"LiteLLM_AutoRouterSession"' in call[0][0] else "logs"): call[0][1]
+ for call in client.db.execute_raw.call_args_list
+ }
+ now = datetime.now(timezone.utc)
+ assert (now - cutoffs["logs"]).days == 7
+ assert (now - cutoffs["LiteLLM_AutoRouterSession"]).days == 365
+
+
+async def test_no_retention_keys_means_no_cleanup_at_all():
+ client = _mock_prisma_for_retention([])
+ cleaner = SpendLogCleanup(general_settings={})
+ cleaner.pod_lock_manager = None
+ await cleaner.cleanup_old_spend_logs(client)
+ assert client.db.execute_raw.await_count == 0
diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py
index b22e16d8c6e..3f024e2fd03 100644
--- a/tests/test_litellm/test_cost_calculator.py
+++ b/tests/test_litellm/test_cost_calculator.py
@@ -3131,7 +3131,7 @@ def test_custom_pricing_applies_cache_creation_input_cost_via_cache_write_tokens
def test_extract_cache_read_tokens_anthropic_top_level():
- from litellm.proxy.db.db_spend_update_writer import _extract_cache_read_tokens
+ from litellm.proxy.spend_tracking.savings import extract_cache_read_tokens as _extract_cache_read_tokens
usage_obj = {
"prompt_tokens": 100,
@@ -3143,7 +3143,7 @@ def test_extract_cache_read_tokens_anthropic_top_level():
def test_extract_cache_read_tokens_openai_compatible_fallback():
- from litellm.proxy.db.db_spend_update_writer import _extract_cache_read_tokens
+ from litellm.proxy.spend_tracking.savings import extract_cache_read_tokens as _extract_cache_read_tokens
# Anthropic field absent — fall back to prompt_tokens_details.cached_tokens.
usage_obj = {
@@ -3154,7 +3154,7 @@ def test_extract_cache_read_tokens_openai_compatible_fallback():
def test_extract_cache_read_tokens_zero_when_missing():
- from litellm.proxy.db.db_spend_update_writer import _extract_cache_read_tokens
+ from litellm.proxy.spend_tracking.savings import extract_cache_read_tokens as _extract_cache_read_tokens
assert _extract_cache_read_tokens({}) == 0
assert _extract_cache_read_tokens({"cache_read_input_tokens": None}) == 0
@@ -3165,9 +3165,7 @@ def test_extract_cache_read_tokens_zero_when_missing():
def test_extract_cache_creation_tokens_anthropic_top_level():
- from litellm.proxy.db.db_spend_update_writer import (
- _extract_cache_creation_tokens,
- )
+ from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens as _extract_cache_creation_tokens
usage_obj = {
"prompt_tokens": 100,
@@ -3179,9 +3177,7 @@ def test_extract_cache_creation_tokens_anthropic_top_level():
def test_extract_cache_creation_tokens_openai_cache_write_alias():
- from litellm.proxy.db.db_spend_update_writer import (
- _extract_cache_creation_tokens,
- )
+ from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens as _extract_cache_creation_tokens
# kimi-k2 emits cache_write_tokens.
usage_obj = {
@@ -3192,9 +3188,7 @@ def test_extract_cache_creation_tokens_openai_cache_write_alias():
def test_extract_cache_creation_tokens_openai_cache_creation_alias():
- from litellm.proxy.db.db_spend_update_writer import (
- _extract_cache_creation_tokens,
- )
+ from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens as _extract_cache_creation_tokens
# Other OpenAI-compatible providers emit cache_creation_tokens.
usage_obj = {
@@ -3205,9 +3199,7 @@ def test_extract_cache_creation_tokens_openai_cache_creation_alias():
def test_extract_cache_creation_tokens_zero_when_missing():
- from litellm.proxy.db.db_spend_update_writer import (
- _extract_cache_creation_tokens,
- )
+ from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens as _extract_cache_creation_tokens
assert _extract_cache_creation_tokens({}) == 0
assert _extract_cache_creation_tokens({"cache_creation_input_tokens": None}) == 0
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index f5010bf45fb..ded3f54e46b 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -760,6 +760,33 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/auto_router/benchmarks": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Auto Router Benchmarks
+ * @description Benchmarks for the auto-router dashboard: session shape, savings against the configured
+ * baseline, and prompt-caching behaviour bucketed by what the router did.
+ *
+ * Reads the LiteLLM_AutoRouterSession rollup, folded once per request at spend-write time,
+ * so this endpoint never scans LiteLLM_SpendLogs. A session is in the window when it
+ * overlaps it: its last turn is on or after start_date and its first turn is on or before
+ * end_date. Overall hit rate is over telemetry-bearing turns; each bucket's hit rate is
+ * over that bucket's turns.
+ */
+ get: operations["get_auto_router_benchmarks_auto_router_benchmarks_get"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/auto_router/classifier/default_prompt": {
parameters: {
query?: never;
@@ -21295,6 +21322,189 @@ export interface components {
[key: string]: unknown;
} | null;
};
+ /**
+ * AutoRouterBenchmarkGroup
+ * @description One auto-router's slice of the benchmarks.
+ */
+ AutoRouterBenchmarkGroup: {
+ /** Avg Session Seconds */
+ avg_session_seconds: number;
+ /** Avg Tokens Per Session */
+ avg_tokens_per_session: number;
+ /** Avg Turns Per Session */
+ avg_turns_per_session: number;
+ /**
+ * Baseline Spend
+ * @description spend plus saved_spend: the estimated single-model cost
+ */
+ baseline_spend: number;
+ cache: components["schemas"]["AutoRouterCacheStats"];
+ /**
+ * Router Name
+ * @description The auto-router alias requests were sent to
+ */
+ router_name: string;
+ /**
+ * Router Type
+ * @description complexity, adaptive or quality
+ */
+ router_type: string;
+ /**
+ * Saved Pct
+ * @description saved_spend over baseline_spend, as a percentage
+ */
+ saved_pct: number;
+ /** Saved Per Session */
+ saved_per_session: number;
+ /**
+ * Saved Spend
+ * @description Signed dollars saved versus each router's savings baseline (derived from its hardest tier, or the configured override), from the same per-request savings record the usage tab reads
+ */
+ saved_spend: number;
+ /** Sessions */
+ sessions: number;
+ /**
+ * Spend
+ * @description What the routed traffic actually cost
+ */
+ spend: number;
+ /** Turns */
+ turns: number;
+ };
+ /**
+ * AutoRouterBenchmarkTotals
+ * @description Session-shape and savings aggregates over auto-routed traffic in the window.
+ */
+ AutoRouterBenchmarkTotals: {
+ /** Avg Session Seconds */
+ avg_session_seconds: number;
+ /** Avg Tokens Per Session */
+ avg_tokens_per_session: number;
+ /** Avg Turns Per Session */
+ avg_turns_per_session: number;
+ /**
+ * Baseline Spend
+ * @description spend plus saved_spend: the estimated single-model cost
+ */
+ baseline_spend: number;
+ cache: components["schemas"]["AutoRouterCacheStats"];
+ /**
+ * Saved Pct
+ * @description saved_spend over baseline_spend, as a percentage
+ */
+ saved_pct: number;
+ /** Saved Per Session */
+ saved_per_session: number;
+ /**
+ * Saved Spend
+ * @description Signed dollars saved versus each router's savings baseline (derived from its hardest tier, or the configured override), from the same per-request savings record the usage tab reads
+ */
+ saved_spend: number;
+ /** Sessions */
+ sessions: number;
+ /**
+ * Spend
+ * @description What the routed traffic actually cost
+ */
+ spend: number;
+ /** Turns */
+ turns: number;
+ };
+ /**
+ * AutoRouterBenchmarksResponse
+ * @description Benchmarks for the auto-router dashboard, aggregated from the per-session rollup.
+ */
+ AutoRouterBenchmarksResponse: {
+ /**
+ * End Date
+ * @description Window end day, YYYY-MM-DD UTC, inclusive
+ */
+ end_date: string;
+ /** Groups */
+ groups: components["schemas"]["AutoRouterBenchmarkGroup"][];
+ /** Routers In Scope */
+ routers_in_scope: number;
+ /**
+ * Start Date
+ * @description Window start day, YYYY-MM-DD UTC, inclusive
+ */
+ start_date: string;
+ totals: components["schemas"]["AutoRouterBenchmarkTotals"];
+ };
+ /**
+ * AutoRouterCacheBucket
+ * @description One prompt-caching bucket of turns, with how often those turns hit the cache.
+ */
+ AutoRouterCacheBucket: {
+ /**
+ * Hit Rate Pct
+ * @description hits over this bucket's turns, as a percentage
+ */
+ hit_rate_pct: number;
+ /**
+ * Hits
+ * @description Turns in this bucket whose response reported cache-read tokens
+ */
+ hits: number;
+ /**
+ * Turns
+ * @description Turns classified into this bucket
+ */
+ turns: number;
+ };
+ /**
+ * AutoRouterCacheStats
+ * @description Prompt-caching behaviour of auto-routed turns, bucketed by what the router did.
+ *
+ * Every in-order turn falls in exactly one bucket: the session stayed on the same model,
+ * visited a model for the first time (cold by design), or returned to a model it had
+ * already used. Out-of-order turns (cross-pod flush races) are counted but not bucketed.
+ */
+ AutoRouterCacheStats: {
+ /**
+ * Coverage Pct
+ * @description Share of turns that carried cache telemetry
+ */
+ coverage_pct: number;
+ first_visit: components["schemas"]["AutoRouterCacheBucket"];
+ /**
+ * Hit Rate Pct
+ * @description All cache hits over telemetry-bearing turns
+ */
+ hit_rate_pct: number;
+ /**
+ * Return Misses Expired
+ * @description Return-to-tier misses where the model's recorded cache TTL had lapsed
+ */
+ return_misses_expired: number;
+ /**
+ * Return Misses Unknown
+ * @description Return-to-tier misses with no recorded TTL to attribute against
+ */
+ return_misses_unknown: number;
+ /**
+ * Return Misses Within Ttl
+ * @description Return-to-tier misses inside the recorded TTL: the prefix changed or the provider evicted the entry early; billing telemetry cannot distinguish the two
+ */
+ return_misses_within_ttl: number;
+ return_to_tier: components["schemas"]["AutoRouterCacheBucket"];
+ same_model: components["schemas"]["AutoRouterCacheBucket"];
+ /**
+ * Ttl 1H Turns
+ * @description Turns whose cache write used the one-hour TTL
+ */
+ ttl_1h_turns: number;
+ /**
+ * Ttl 5M Turns
+ * @description Turns whose cache write used the five-minute TTL
+ */
+ ttl_5m_turns: number;
+ /**
+ * Unordered Turns
+ * @description Turns that arrived out of order and were not bucketed
+ */
+ unordered_turns: number;
+ };
/**
* AutoRouterClassifierDefaultPromptResponse
* @description The built-in system prompt an auto-router's LLM classifier uses when none is configured.
@@ -23317,6 +23527,11 @@ export interface components {
* @description max response size in MB, if a response is larger than this size it will be rejected
*/
max_response_size_mb?: number | null;
+ /**
+ * Maximum Autorouter Session Retention Period
+ * @description Maximum retention period for auto-router benchmark session rollup rows (e.g., '365d'). Rows whose last turn is older than this are deleted by the spend log cleanup job, on that job's schedule. Unset means rollup rows are never deleted.
+ */
+ maximum_autorouter_session_retention_period?: string | null;
/**
* Maximum Spend Logs Retention Period
* @description Maximum retention period for spend logs (e.g., '7d' for 7 days). Logs older than this will be deleted.
@@ -36449,6 +36664,40 @@ export interface operations {
};
};
};
+ get_auto_router_benchmarks_auto_router_benchmarks_get: {
+ parameters: {
+ query?: {
+ /** @description YYYY-MM-DD UTC, inclusive (defaults to 30 days before end_date) */
+ start_date?: string | null;
+ /** @description YYYY-MM-DD UTC, inclusive (defaults to today) */
+ end_date?: string | null;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AutoRouterBenchmarksResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
get_auto_router_classifier_default_prompt_auto_router_classifier_default_prompt_get: {
parameters: {
query?: {