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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(sgr): make the gateway middleware the source of truth for successful requests (#35717)
Yassin Kortam09dd167b5a74
diff --git a/backend/routes/allowlist.py b/backend/routes/allowlist.pyindex 96e224a7dc6..8ccd439979b 100644--- a/backend/routes/allowlist.py+++ b/backend/routes/allowlist.py@@ -82,6 +82,9 @@ BACKEND_PATH_PREFIXES: tuple[str, ...] = ("/user_agent","/usage/","/daily/",+ # Deployment-wide gateway request counts. Scoped to the analytics read rather+ # than all of /gateway/, which stays free for data-plane routes.+ "/gateway/daily/",# CloudZero cost-export admin (init / settings / export / dry-run / delete)"/cloudzero/",# Caching admindiff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260803000000_add_daily_gateway_requests/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260803000000_add_daily_gateway_requests/migration.sqlnew file mode 100644index 00000000000..0885cebeaf5--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260803000000_add_daily_gateway_requests/migration.sql@@ -0,0 +1,15 @@+-- CreateTable+CREATE TABLE IF NOT EXISTS "LiteLLM_DailyGatewayRequests" (+ "date" TEXT NOT NULL,+ "category" TEXT NOT NULL,+ "route" TEXT NOT NULL,+ "successful_requests" BIGINT NOT NULL DEFAULT 0,+ "failed_requests" BIGINT NOT NULL DEFAULT 0,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "LiteLLM_DailyGatewayRequests_pkey" PRIMARY KEY ("date","category","route")+);++-- CreateIndex+CREATE INDEX IF NOT EXISTS "LiteLLM_DailyGatewayRequests_date_idx" ON "LiteLLM_DailyGatewayRequests"("date");diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 17339541fd9..3a7882b6d2b 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -1118,6 +1118,26 @@ model LiteLLM_DailyToolSpend {@@id([date, tool_name])}+// Gateway request counts recorded at the ASGI edge by+// BillableRequestMetricsMiddleware. This is the source of truth for SGR+// (successful gateway requests): it counts what the proxy actually answered,+// independent of whether the request reached litellm's logging callbacks.+// The key carries no deployment or caller dimension. Every part of it is+// chosen by the proxy and drawn from a closed set, so the table is bounded by+// (days x categories x routes) rather than by anything a caller can vary.+model LiteLLM_DailyGatewayRequests {+ date String+ category String+ route String+ successful_requests BigInt @default(0)+ failed_requests BigInt @default(0)+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([date, category, route])+ @@index([date])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 4e5782c862a..7a68fb24f43 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -622,6 +622,8 @@ class LiteLLMRoutes(enum.Enum):"/team/permissions_update","/team/permissions_bulk_update","/team/daily/activity",+ # gateway request counts (SGR); deployment-wide, admin-only+ "/gateway/daily/activity",# model"/model/new","/model/update",@@ -715,6 +717,7 @@ class LiteLLMRoutes(enum.Enum):"/global/spend/tags","/global/predict/spend/logs","/global/activity",+ "/gateway/daily/activity","/health/services",] + info_routesdiff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.pyindex acc8c71b84b..bb37989d129 100644--- a/litellm/proxy/db/db_spend_update_writer.py+++ b/litellm/proxy/db/db_spend_update_writer.py@@ -1860,6 +1860,12 @@ class DBSpendUpdateWriter:)return None+ # TODO: remove the successful_requests/failed_requests counters below once the+ # admin UI has fully migrated to LiteLLM_DailyGatewayRequests, which is now the+ # source of truth for SGR. This path derives the counts from spend-log metadata+ # rather than from what the gateway answered, so the two intentionally disagree+ # (see litellm/proxy/middleware/billable_request_metrics_middleware.py). The+ # spend, token and per-entity columns written here stay either way.request_status: Final = prisma_client.get_request_status(payload)verbose_proxy_logger.debug("Logged request status: %s", request_status)_metadata: Final[SpendLogsMetadata] = json.loads(payload["metadata"])diff --git a/litellm/proxy/db/gateway_request_tracking.py b/litellm/proxy/db/gateway_request_tracking.pynew file mode 100644index 00000000000..bebd74e877c--- /dev/null+++ b/litellm/proxy/db/gateway_request_tracking.py@@ -0,0 +1,133 @@+"""+Accumulates gateway request counts (SGR) recorded at the ASGI edge and commits+them to ``LiteLLM_DailyGatewayRequests``.++Unlike the spend queues this keeps no per-request item. A count is a pure+aggregate, so requests fold into an in-memory map as they finish. Every+dimension of the key is server-chosen and drawn from a fixed set: the date, the+category, and a route that the classifier maps to one of a closed list of+strings rather than passing the raw path through. Nothing a caller sends can+add a key, so the fold and the table it commits to are bounded by (days x+routes) however much traffic arrives, and the response path carries no+unbounded queue that would block once full.+"""++from dataclasses import asdict+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Final++from litellm._logging import verbose_proxy_logger+from litellm.proxy.middleware.billable_request_metrics_middleware import BillableCategory+from litellm.types.proxy.gateway_requests import (+ GatewayRequestCounts,+ GatewayRequestKey,+ GatewayRequestSnapshot,+)++if TYPE_CHECKING:+ from litellm.proxy.utils import PrismaClient++_EMPTY: Final = GatewayRequestCounts(successful_requests=0, failed_requests=0)+++def _utc_date() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")+++class GatewayRequestAccumulator:+ """Sink for the request-metrics middleware. ``record`` is sync and never awaits."""++ def __init__(self) -> None:+ self._counts: dict[GatewayRequestKey, GatewayRequestCounts] = {} # mutable-ok: bounded fold, drained per flush++ def record(self, *, category: BillableCategory, route: str, status_code: int) -> None:+ key: Final = GatewayRequestKey(date=_utc_date(), category=category.value, route=route)+ self._counts[key] = self._counts.get(key, _EMPTY).plus(succeeded=200 <= status_code < 300)++ def drain(self) -> GatewayRequestSnapshot:+ drained: Final = self._counts+ self._counts = {} # mutable-ok: the fold restarts empty; the drained map is handed off whole+ return drained++ def restore(self, snapshot: GatewayRequestSnapshot) -> None:+ """+ Merge un-committed counts back so the next flush retries them.++ A dropped flush would silently undercount the metric the dashboard now+ treats as the source of truth. Merging cannot grow without bound: keys+ collapse on collision, so the fold stays bounded by (date x category x+ route) however long the database is unreachable.++ This buys at-least-once, not exactly-once, and the cost is worth stating.+ The batch commits inside its context manager's ``__aexit__``, so a failure+ raised after the transaction committed (a connection dropped while reading+ the acknowledgement) restores counts that are already persisted, and the+ next flush increments them a second time. Exactly-once would need a dedup+ key the upserts could ignore on replay. For a traffic-volume metric a rare+ overcount on a dropped acknowledgement beats losing a whole interval to+ every database blip, so the trade is deliberate.+ """+ for key, counts in snapshot.items():+ existing = self._counts.get(key, _EMPTY)+ self._counts[key] = GatewayRequestCounts(+ successful_requests=existing.successful_requests + counts.successful_requests,+ failed_requests=existing.failed_requests + counts.failed_requests,+ )+++async def commit_gateway_requests_to_db(+ *,+ prisma_client: "PrismaClient",+ snapshot: GatewayRequestSnapshot,+) -> None:+ """Upsert one incrementing row per (date, category, route)."""+ if not snapshot:+ return++ ordered: Final = sorted(snapshot.items(), key=lambda item: (item[0].date, item[0].category, item[0].route))++ # pyright: ignore[reportAny] on both lines -- prisma's generated client is untyped,+ # so .db and every table action off it resolve to Any at this boundary. The dict+ # literals below are the shape prisma's generated inputs require.+ async with prisma_client.db.batch_() as batcher: # pyright: ignore[reportAny] # untyped prisma client+ for key, counts in ordered:+ columns = asdict(key)+ batcher.litellm_dailygatewayrequests.upsert( # pyright: ignore[reportAny] # untyped prisma client+ where={"date_category_route": columns}, # mutable-ok: prisma input is dict-shaped+ data={ # mutable-ok: prisma input is dict-shaped+ "create": { # mutable-ok: prisma input is dict-shaped+ **columns,+ "successful_requests": counts.successful_requests,+ "failed_requests": counts.failed_requests,+ },+ "update": { # mutable-ok: prisma input is dict-shaped+ "successful_requests": {"increment": counts.successful_requests}, # mutable-ok: as above+ "failed_requests": {"increment": counts.failed_requests}, # mutable-ok: as above+ },+ },+ )++ verbose_proxy_logger.debug("Gateway request tracking - committed %d aggregated rows", len(ordered))+++async def flush_gateway_requests(+ prisma_client: "PrismaClient",+ accumulator: GatewayRequestAccumulator,+) -> None:+ """+ Scheduler entrypoint. Never raises: a metering failure must not kill the job.++ ``CancelledError`` is deliberately not caught, so a flush cancelled during+ shutdown drops its snapshot rather than restoring counts onto an accumulator+ the process is about to discard.+ """+ snapshot: Final = accumulator.drain()+ try:+ await commit_gateway_requests_to_db(prisma_client=prisma_client, snapshot=snapshot)+ except Exception: # noqa: BLE001 -- a failed flush must not stop the scheduler+ accumulator.restore(snapshot)+ verbose_proxy_logger.warning(+ "Gateway request tracking - failed to commit %d rows, retrying on the next flush",+ len(snapshot),+ exc_info=True,+ )diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.pyindex 96f2465ebb9..9af65b50c7f 100644--- a/litellm/proxy/management_endpoints/common_daily_activity.py+++ b/litellm/proxy/management_endpoints/common_daily_activity.py@@ -571,6 +571,11 @@ def _build_aggregated_sql_query(# straight into their buckets without re-summing. The leaf grouping# is omitted on purpose: nothing in the response shape needs it once# all the rollups are present.+ #+ # TODO: drop the successful_requests/failed_requests aggregates (and the+ # total_successful_requests metadata they feed) once the admin UI reads SGR+ # only from LiteLLM_DailyGatewayRequests. The remaining spend, token and+ # api_requests rollups are still served from here.sql_query: Final = f"""SELECTdate,diff --git a/litellm/proxy/management_endpoints/gateway_request_endpoints.py b/litellm/proxy/management_endpoints/gateway_request_endpoints.pynew file mode 100644index 00000000000..33c078274fb--- /dev/null+++ b/litellm/proxy/management_endpoints/gateway_request_endpoints.py@@ -0,0 +1,139 @@+"""+GATEWAY REQUEST COUNTS (SGR)++GET /gateway/daily/activity - successful/failed gateway requests by date and route++Source of truth is LiteLLM_DailyGatewayRequests, written at the ASGI edge by+BillableRequestMetricsMiddleware. This counts what the proxy answered, so it is+independent of whether a request reached litellm's logging callbacks.++The table carries no key/user/team dimension, so these totals are deployment-wide+and the endpoint is restricted to proxy admin roles.+"""++from collections.abc import Sequence+from datetime import datetime, timedelta, timezone+from typing import Annotated, Final++from fastapi import APIRouter, Depends, HTTPException, Query+from pydantic import BaseModel, TypeAdapter++from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.types.proxy.gateway_requests import (+ GatewayRequestActivityResponse,+ GatewayRequestBreakdownEntry,+ GatewayRequestDailyEntry,+)++router: Final = APIRouter()++_DEFAULT_LOOKBACK_DAYS: Final = 30++_AGGREGATE_SQL: Final = """+ SELECT+ date,+ category,+ route,+ SUM(successful_requests)::bigint AS successful_requests,+ SUM(failed_requests)::bigint AS failed_requests+ FROM "LiteLLM_DailyGatewayRequests"+ WHERE date >= $1 AND date <= $2+ GROUP BY date, category, route+"""+++class _AggregateRow(BaseModel):+ """Validates one query_raw row so the handler works with typed values, not Any."""++ date: str+ category: str+ route: str+ successful_requests: int+ failed_requests: int+++_ROWS_ADAPTER: Final = TypeAdapter(tuple[_AggregateRow, ...])+++def _default_range() -> tuple[str, str]:+ end: Final = datetime.now(timezone.utc)+ start: Final = end - timedelta(days=_DEFAULT_LOOKBACK_DAYS)+ return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")+++def _fold_by_date(rows: Sequence[_AggregateRow]) -> tuple[GatewayRequestDailyEntry, ...]:+ dates: Final = sorted(frozenset(row.date for row in rows))+ return tuple(+ GatewayRequestDailyEntry(+ date=date,+ successful_requests=sum(row.successful_requests for row in rows if row.date == date),+ failed_requests=sum(row.failed_requests for row in rows if row.date == date),+ )+ for date in dates+ )+++def _fold_by_route(rows: Sequence[_AggregateRow]) -> tuple[GatewayRequestBreakdownEntry, ...]:+ pairs: Final = sorted(frozenset((row.category, row.route) for row in rows))+ entries: Final = tuple(+ GatewayRequestBreakdownEntry(+ category=category,+ route=route,+ successful_requests=sum(+ row.successful_requests for row in rows if row.category == category and row.route == route+ ),+ failed_requests=sum(row.failed_requests for row in rows if row.category == category and row.route == route),+ )+ for category, route in pairs+ )+ return tuple(sorted(entries, key=lambda entry: entry.successful_requests, reverse=True))+++ "/gateway/daily/activity",+ tags=["Budget & Spend Tracking"], # mutable-ok: fastapi's decorator signature types tags as a list+ response_model=GatewayRequestActivityResponse,+)+async def get_gateway_daily_activity(+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+ start_date: str | None = Query(default=None, description="Start date in YYYY-MM-DD format"),+ end_date: str | None = Query(default=None, description="End date in YYYY-MM-DD format"),+) -> GatewayRequestActivityResponse:+ """+ Successful and failed gateway requests, counted at the ASGI edge.++ Deployment-wide: the underlying table has no per-key or per-user dimension,+ so this is admin-only.+ """+ 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 gateway request counts across the deployment",+ )++ if prisma_client is None:+ raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)++ default_start, default_end = _default_range()+ raw_rows: Final = await prisma_client.db.query_raw( # pyright: ignore[reportAny] # untyped prisma client+ _AGGREGATE_SQL,+ start_date or default_start,+ end_date or default_end,+ )+ # Every downstream use is typed: the adapter returns _AggregateRow or raises.+ rows: Final = _ROWS_ADAPTER.validate_python(raw_rows or ())+ verbose_proxy_logger.debug("/gateway/daily/activity - aggregated %d rows", len(rows))++ return GatewayRequestActivityResponse(+ total_successful_requests=sum(row.successful_requests for row in rows),+ total_failed_requests=sum(row.failed_requests for row in rows),+ by_date=_fold_by_date(rows),+ by_route=_fold_by_route(rows),+ )diff --git a/litellm/proxy/middleware/billable_request_metrics_middleware.py b/litellm/proxy/middleware/billable_request_metrics_middleware.pyindex 2708698f71c..9824f33797c 100644--- a/litellm/proxy/middleware/billable_request_metrics_middleware.py+++ b/litellm/proxy/middleware/billable_request_metrics_middleware.py@@ -1,11 +1,18 @@"""-Counts billable HTTP requests on enterprise deployments.+Counts HTTP requests to LLM inference, MCP, and A2A endpoints.-A billable request is an inbound request to an LLM inference, MCP, or A2A-endpoint that returns a 2xx status. The actual export happens in an injected-recorder (see litellm.proxy.enterprise_billing.billing_metrics); when no-recorder is injected (non-enterprise, or metering misconfigured) this-middleware is a transparent pass-through.+Feeds two independent sinks off one classification:++- ``GatewayRequestSink`` receives every classified request with its status and+ is the source of truth for SGR (successful gateway requests) on the admin UI.+ Not license-gated (see litellm.proxy.db.gateway_request_tracking). It is not+ told which deployment served the request: it persists its counts, so every+ dimension it takes has to be one the proxy chooses.+- ``BillingRecorder`` receives 2xx requests only and exports them for+ enterprise metering (see litellm.proxy.enterprise_billing.billing_metrics).++Both are injected. When neither is present the middleware is a transparent+pass-through."""import re@@ -31,6 +38,21 @@ class BillingRecorder(Protocol):def record(self, *, category: BillableCategory, route: str, status_code: int, model_id: str | None) -> None: ...+@runtime_checkable+class GatewayRequestSink(Protocol):+ """+ Records every classified request, 2xx or not, for the SGR dashboard.++ Distinct from BillingRecorder on three counts: this is not license-gated,+ it is not restricted to 2xx, and it takes no model id. The deployment that+ served a request is deliberately not part of what it records, because the+ dashboard aggregates by route and a per-deployment dimension would only+ multiply the rows it has to sum back together.+ """++ def record(self, *, category: BillableCategory, route: str, status_code: int) -> None: ...++_MODEL_ID_HEADER: Final = b"x-litellm-model-id"# Ordered: a longer suffix that shares an ending with a shorter one must come@@ -165,10 +187,11 @@ def _extract_model_id(headers: Sequence[tuple[bytes, bytes]]) -> str | None:class BillableRequestMetricsMiddleware:"""- Pure ASGI middleware that records one billable request per 2xx response to a- billable endpoint. Modeled on InFlightRequestsMiddleware: it wraps `send`,- reads the final status and the x-litellm-model-id header off the- `http.response.start` message, and never blocks or fails the request path.+ Pure ASGI middleware that classifies each request once and fans the result+ out to the SGR sink (any status) and the billing recorder (2xx only).+ Modeled on InFlightRequestsMiddleware: it wraps `send`, reads the final+ status and the x-litellm-model-id header off the `http.response.start`+ message, and never blocks or fails the request path."""def __init__(@@ -176,6 +199,8 @@ class BillableRequestMetricsMiddleware:app: ASGIApp,recorder: BillingRecorder | None = None,recorder_factory: Callable[[], BillingRecorder | None] | None = None,+ sink: GatewayRequestSink | None = None,+ sink_factory: Callable[[], GatewayRequestSink | None] | None = None,) -> None:self.app = appself.recorder = recorder@@ -187,6 +212,12 @@ class BillableRequestMetricsMiddleware:self._recorder_factory = recorder_factoryself._resolved = recorder_factory is Noneself._resolve_lock = threading.Lock()+ # Resolved on the same schedule and for the same reason: the DB is not+ # connected at import time, so the sink cannot be built there either.+ self.sink = sink+ self._sink_factory = sink_factory+ self._sink_resolved = sink_factory is None+ self._sink_resolve_lock = threading.Lock()def _resolve_recorder(self) -> BillingRecorder | None:if self._resolved:@@ -200,13 +231,24 @@ class BillableRequestMetricsMiddleware:self._resolved = Truereturn self.recorder+ def _resolve_sink(self) -> GatewayRequestSink | None:+ if self._sink_resolved:+ return self.sink+ with self._sink_resolve_lock:+ if not self._sink_resolved:+ factory: Final = self._sink_factory+ self.sink = factory() if factory is not None else self.sink+ self._sink_resolved = True+ return self.sink+async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:if scope["type"] != "http":await self.app(scope, receive, send)returnrecorder: Final = self._resolve_recorder()- if recorder is None:+ sink: Final = self._resolve_sink()+ if recorder is None and sink is None:await self.app(scope, receive, send)return@@ -228,7 +270,13 @@ class BillableRequestMetricsMiddleware:await self.app(scope, receive, send_wrapper)- if 200 <= status_code < 300:+ if sink is not None:+ try:+ sink.record(category=category, route=route, status_code=status_code)+ except Exception: # noqa: BLE001 -- metering must never fail a request that was already served+ verbose_proxy_logger.warning("gateway request metering failed for %s", route, exc_info=True)++ if recorder is not None and 200 <= status_code < 300:try:recorder.record(category=category, route=route, status_code=status_code, model_id=model_id)except Exception: # noqa: BLE001 -- metering must never fail a request that was already serveddiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 43e37686f07..d4b3aae0d82 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -353,6 +353,10 @@ from litellm.proxy.db.exception_handler import (PrismaDBExceptionHandler,call_with_db_reconnect_retry,)+from litellm.proxy.db.gateway_request_tracking import (+ GatewayRequestAccumulator,+ flush_gateway_requests,+)from litellm.proxy.db.spend_counter_reseed import SpendCounterReseedfrom litellm.proxy.discovery_endpoints import ui_discovery_endpoints_routerfrom litellm.proxy.fine_tuning_endpoints.endpoints import router as fine_tuning_router@@ -411,6 +415,9 @@ from litellm.proxy.management_endpoints.customer_endpoints import (from litellm.proxy.management_endpoints.fallback_management_endpoints import (router as fallback_management_router,)+from litellm.proxy.management_endpoints.gateway_request_endpoints import (+ router as gateway_request_router,+)from litellm.proxy.management_endpoints.internal_user_endpoints import (router as internal_user_router,)@@ -820,6 +827,11 @@ async def proxy_shutdown_event():global prisma_client, master_key, user_custom_auth, user_custom_key_generate, user_custom_key_updateverbose_proxy_logger.info("Shutting down LiteLLM Proxy Server")if prisma_client:+ # Drain the SGR fold first: it lives in memory, so an un-drained interval+ # is lost, and a write attempted after disconnect raises+ # ClientNotConnectedError rather than persisting anything. Ordering this+ # inside the same guard is what keeps the two from drifting apart.+ await flush_gateway_requests(prisma_client, gateway_request_accumulator)verbose_proxy_logger.debug("Disconnecting from Prisma")await prisma_client.disconnect()@@ -1901,6 +1913,11 @@ app.add_middleware(if build_billing_metrics_recorder is not Noneelse None),+ # Unlike the billing recorder this is not license-gated: the admin UI must+ # report SGR on any deployment. Gated only on a database being configured,+ # since without one the fold would never be drained. Read at call time, so+ # it sees prisma_client as of the first request rather than import time.+ sink_factory=lambda: gateway_request_accumulator if prisma_client is not None else None,)app.add_middleware(InFlightRequestsMiddleware)app.add_middleware(SecurityHeadersMiddleware)@@ -2068,6 +2085,10 @@ jwt_handler: Final = JWTHandler()prompt_injection_detection_obj: _OPTIONAL_PromptInjectionDetection | None = Nonestore_model_in_db: bool = Falseopen_telemetry_logger: OpenTelemetry | None = None+### GATEWAY REQUEST COUNTS (SGR) ###+# Folded in memory by BillableRequestMetricsMiddleware, drained to+# LiteLLM_DailyGatewayRequests by the update_gateway_requests scheduler job.+gateway_request_accumulator: Final = GatewayRequestAccumulator()### INITIALIZE GLOBAL LOGGING OBJECT ###proxy_logging_obj: ProxyLogging = ProxyLogging(user_api_key_cache=user_api_key_cache, premium_user=premium_user)### REDIS QUEUE ###@@ -8198,6 +8219,17 @@ class ProxyStartupEvent:f"({tag_spend_update_interval / batch_writing_interval:.1f}x main job interval)")+ ### UPDATE GATEWAY REQUEST COUNTS (SGR) ###+ scheduler.add_job(+ flush_gateway_requests,+ "interval",+ seconds=batch_writing_interval,+ args=(prisma_client, gateway_request_accumulator),+ id="update_gateway_requests_job",+ replace_existing=True,+ misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,+ )+### MONITOR SPEND LOGS QUEUE (queue-size-based job) ###if general_settings.get("disable_spend_logs", False) is False:from litellm.proxy.utils import _monitor_spend_logs_queue@@ -16478,6 +16510,7 @@ app.include_router(fallback_management_router)app.include_router(cache_settings_router)app.include_router(coordination_redis_settings_router)app.include_router(user_agent_analytics_router)+app.include_router(gateway_request_router)app.include_router(enterprise_router)app.include_router(ui_discovery_endpoints_router)# Eager: /models/{name}:method overlaps with the OpenAI /models endpoint.diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 17339541fd9..3a7882b6d2b 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -1118,6 +1118,26 @@ model LiteLLM_DailyToolSpend {@@id([date, tool_name])}+// Gateway request counts recorded at the ASGI edge by+// BillableRequestMetricsMiddleware. This is the source of truth for SGR+// (successful gateway requests): it counts what the proxy actually answered,+// independent of whether the request reached litellm's logging callbacks.+// The key carries no deployment or caller dimension. Every part of it is+// chosen by the proxy and drawn from a closed set, so the table is bounded by+// (days x categories x routes) rather than by anything a caller can vary.+model LiteLLM_DailyGatewayRequests {+ date String+ category String+ route String+ successful_requests BigInt @default(0)+ failed_requests BigInt @default(0)+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([date, category, route])+ @@index([date])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/litellm/types/proxy/gateway_requests.py b/litellm/types/proxy/gateway_requests.pynew file mode 100644index 00000000000..f0abeb3c950--- /dev/null+++ b/litellm/types/proxy/gateway_requests.py@@ -0,0 +1,51 @@+"""Types for gateway request counts (SGR), recorded at the ASGI edge."""++from collections.abc import Mapping+from dataclasses import dataclass+from typing import TypeAlias++from pydantic import BaseModel+++@dataclass(frozen=True, slots=True)+class GatewayRequestKey:+ date: str+ category: str+ route: str+++@dataclass(frozen=True, slots=True)+class GatewayRequestCounts:+ successful_requests: int+ failed_requests: int++ def plus(self, *, succeeded: bool) -> "GatewayRequestCounts":+ return GatewayRequestCounts(+ successful_requests=self.successful_requests + (1 if succeeded else 0),+ failed_requests=self.failed_requests + (0 if succeeded else 1),+ )+++GatewayRequestSnapshot: TypeAlias = Mapping[GatewayRequestKey, GatewayRequestCounts]+++class GatewayRequestBreakdownEntry(BaseModel):+ category: str+ route: str+ successful_requests: int = 0+ failed_requests: int = 0+++class GatewayRequestDailyEntry(BaseModel):+ date: str+ successful_requests: int = 0+ failed_requests: int = 0+++class GatewayRequestActivityResponse(BaseModel):+ """Response for GET /gateway/daily/activity."""++ total_successful_requests: int = 0+ total_failed_requests: int = 0+ by_date: tuple[GatewayRequestDailyEntry, ...] = ()+ by_route: tuple[GatewayRequestBreakdownEntry, ...] = ()diff --git a/schema.prisma b/schema.prismaindex 17339541fd9..3a7882b6d2b 100644--- a/schema.prisma+++ b/schema.prisma@@ -1118,6 +1118,26 @@ model LiteLLM_DailyToolSpend {@@id([date, tool_name])}+// Gateway request counts recorded at the ASGI edge by+// BillableRequestMetricsMiddleware. This is the source of truth for SGR+// (successful gateway requests): it counts what the proxy actually answered,+// independent of whether the request reached litellm's logging callbacks.+// The key carries no deployment or caller dimension. Every part of it is+// chosen by the proxy and drawn from a closed set, so the table is bounded by+// (days x categories x routes) rather than by anything a caller can vary.+model LiteLLM_DailyGatewayRequests {+ date String+ category String+ route String+ successful_requests BigInt @default(0)+ failed_requests BigInt @default(0)+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([date, category, route])+ @@index([date])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/tests/test_litellm/proxy/db/test_gateway_request_tracking.py b/tests/test_litellm/proxy/db/test_gateway_request_tracking.pynew file mode 100644index 00000000000..93a11a914cb--- /dev/null+++ b/tests/test_litellm/proxy/db/test_gateway_request_tracking.py@@ -0,0 +1,227 @@+"""+Tests for the gateway request (SGR) fold and its commit to+LiteLLM_DailyGatewayRequests.+"""++import asyncio+from datetime import datetime, timezone++import pytest++from litellm.proxy.db.gateway_request_tracking import (+ GatewayRequestAccumulator,+ commit_gateway_requests_to_db,+ flush_gateway_requests,+)+from litellm.proxy.middleware.billable_request_metrics_middleware import BillableCategory+from litellm.types.proxy.gateway_requests import GatewayRequestCounts, GatewayRequestKey+++def _today() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")+++def _record(accumulator: GatewayRequestAccumulator, status_code: int, **overrides) -> None:+ accumulator.record(+ category=overrides.get("category", BillableCategory.LLM),+ route=overrides.get("route", "/chat/completions"),+ status_code=status_code,+ )+++# ── fold ──────────────────────────────────────────────────────────────────────+++def test_folds_repeated_requests_into_one_key():+ acc = GatewayRequestAccumulator()+ for _ in range(3):+ _record(acc, 200)+ _record(acc, 500)++ snapshot = acc.drain()+ assert snapshot == {+ GatewayRequestKey(date=_today(), category="llm", route="/chat/completions"): (+ GatewayRequestCounts(successful_requests=3, failed_requests=1)+ )+ }+++ "status_code, expected_successful, expected_failed",+ [(200, 1, 0), (201, 1, 0), (204, 1, 0), (299, 1, 0), (300, 0, 1), (400, 0, 1), (500, 0, 1)],+)+def test_success_boundary_is_2xx(status_code: int, expected_successful: int, expected_failed: int):+ acc = GatewayRequestAccumulator()+ _record(acc, status_code)+ counts = next(iter(acc.drain().values()))+ assert (counts.successful_requests, counts.failed_requests) == (expected_successful, expected_failed)+++def test_distinct_dimensions_do_not_merge():+ acc = GatewayRequestAccumulator()+ _record(acc, 200, route="/chat/completions")+ _record(acc, 200, route="/embeddings")+ _record(acc, 200, category=BillableCategory.MCP, route="/mcp")+ assert len(acc.drain()) == 3+++def test_drain_empties_the_fold():+ acc = GatewayRequestAccumulator()+ _record(acc, 200)+ assert len(acc.drain()) == 1+ assert acc.drain() == {}+++def test_drain_snapshot_is_not_mutated_by_later_records():+ acc = GatewayRequestAccumulator()+ _record(acc, 200)+ snapshot = acc.drain()+ _record(acc, 200)+ assert next(iter(snapshot.values())).successful_requests == 1+++# ── commit ────────────────────────────────────────────────────────────────────+++class FakeTable:+ def __init__(self) -> None:+ self.upserts: list[dict] = []++ def upsert(self, *, where: dict, data: dict) -> None:+ self.upserts.append({"where": where, "data": data})+++class FakeBatcher:+ def __init__(self, table: FakeTable) -> None:+ self.litellm_dailygatewayrequests = table++ async def __aenter__(self) -> "FakeBatcher":+ return self++ async def __aexit__(self, *args: object) -> bool:+ return False+++class FakeDB:+ def __init__(self, table: FakeTable) -> None:+ self._table = table++ def batch_(self) -> FakeBatcher:+ return FakeBatcher(self._table)+++class FakePrismaClient:+ def __init__(self) -> None:+ self.table = FakeTable()+ self.db = FakeDB(self.table)+++def test_commit_upserts_one_incrementing_row_per_key():+ client = FakePrismaClient()+ snapshot = {+ GatewayRequestKey(date="2026-08-01", category="llm", route="/chat/completions"): (+ GatewayRequestCounts(successful_requests=7, failed_requests=2)+ )+ }++ asyncio.run(commit_gateway_requests_to_db(prisma_client=client, snapshot=snapshot))++ assert len(client.table.upserts) == 1+ written = client.table.upserts[0]+ assert written["where"] == {+ "date_category_route": {+ "date": "2026-08-01",+ "category": "llm",+ "route": "/chat/completions",+ }+ }+ assert written["data"]["update"] == {+ "successful_requests": {"increment": 7},+ "failed_requests": {"increment": 2},+ }+ assert written["data"]["create"]["successful_requests"] == 7+++def test_commit_is_deterministically_ordered():+ """Concurrent writers must touch rows in the same order or they deadlock."""+ client = FakePrismaClient()+ keys = [+ GatewayRequestKey(date="2026-08-02", category="llm", route="/embeddings"),+ GatewayRequestKey(date="2026-08-01", category="mcp", route="/mcp"),+ GatewayRequestKey(date="2026-08-01", category="llm", route="/chat/completions"),+ ]+ snapshot = {key: GatewayRequestCounts(successful_requests=1, failed_requests=0) for key in keys}++ asyncio.run(commit_gateway_requests_to_db(prisma_client=client, snapshot=snapshot))++ written_order = [+ (row["where"]["date_category_route"]["date"], row["where"]["date_category_route"]["category"])+ for row in client.table.upserts+ ]+ assert written_order == [("2026-08-01", "llm"), ("2026-08-01", "mcp"), ("2026-08-02", "llm")]+++def test_commit_skips_the_database_entirely_when_nothing_accumulated():+ client = FakePrismaClient()+ asyncio.run(commit_gateway_requests_to_db(prisma_client=client, snapshot={}))+ assert client.table.upserts == []+++# ── flush ─────────────────────────────────────────────────────────────────────+++def test_flush_drains_and_commits():+ client = FakePrismaClient()+ acc = GatewayRequestAccumulator()+ _record(acc, 200)++ asyncio.run(flush_gateway_requests(client, acc))++ assert len(client.table.upserts) == 1+ assert acc.drain() == {}+++class ExplodingDB:+ def batch_(self):+ raise RuntimeError("db gone")+++class ExplodingClient:+ db = ExplodingDB()+++def test_flush_swallows_commit_failure_so_the_scheduler_survives():+ acc = GatewayRequestAccumulator()+ _record(acc, 200)++ asyncio.run(flush_gateway_requests(ExplodingClient(), acc))+++def test_failed_flush_keeps_counts_for_the_next_attempt():+ """A dropped flush would silently undercount the SGR source of truth."""+ acc = GatewayRequestAccumulator()+ _record(acc, 200)+ _record(acc, 500)++ asyncio.run(flush_gateway_requests(ExplodingClient(), acc))++ client = FakePrismaClient()+ asyncio.run(flush_gateway_requests(client, acc))++ assert client.table.upserts[0]["data"]["update"] == {+ "successful_requests": {"increment": 1},+ "failed_requests": {"increment": 1},+ }+++def test_restored_counts_merge_with_requests_recorded_meanwhile():+ acc = GatewayRequestAccumulator()+ _record(acc, 200)+ asyncio.run(flush_gateway_requests(ExplodingClient(), acc))++ _record(acc, 200)+ client = FakePrismaClient()+ asyncio.run(flush_gateway_requests(client, acc))++ assert len(client.table.upserts) == 1+ assert client.table.upserts[0]["data"]["update"]["successful_requests"] == {"increment": 2}diff --git a/tests/test_litellm/proxy/management_endpoints/test_gateway_request_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_gateway_request_endpoints.pynew file mode 100644index 00000000000..4f4e378bae4--- /dev/null+++ b/tests/test_litellm/proxy/management_endpoints/test_gateway_request_endpoints.py@@ -0,0 +1,303 @@+import os+from datetime import datetime, timedelta, timezone+from unittest.mock import AsyncMock, MagicMock, patch++# Patching ``litellm.proxy.proxy_server.prisma_client`` imports that module, whose+# module-level setup reads DATABASE_URL and LITELLM_MASTER_KEY. Tier-zero runners+# set neither, so pin throwaways first, as test_component_allowlists.py does. The+# prior values are restored below so a non-postgres URL cannot leak into sibling+# tests sharing the xdist worker and make them treat a phantom database as live.+_THROWAWAY_ENV = {+ "DATABASE_URL": "sqlite:///:memory:",+ "LITELLM_MASTER_KEY": "sk-test-gateway-request-endpoints",+}+_PRE_EXISTING_ENV = {key: os.environ.get(key) for key in _THROWAWAY_ENV}+for _key, _value in _THROWAWAY_ENV.items():+ os.environ.setdefault(_key, _value)++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.management_endpoints.gateway_request_endpoints import (+ _AggregateRow,+ _default_range,+ _fold_by_date,+ _fold_by_route,+ get_gateway_daily_activity,+ router,+)++for _key, _previous in _PRE_EXISTING_ENV.items():+ if _previous is None:+ os.environ.pop(_key, None)+ else:+ os.environ[_key] = _previous++# The handler stamps "today" from the wall clock, so any assertion that names a+# date has to pin it. Recomputing the expected range in the assertion instead+# would disagree with the request's own range whenever a run crosses UTC+# midnight between the two evaluations.+# A date in the past on purpose. Pinning "today" would let these assertions pass+# on a day the fixture silently failed to patch, which is the same vacuous pass a+# mutation check exists to catch.+_FROZEN_NOW = datetime(2023, 3, 15, 12, 0, tzinfo=timezone.utc)+_FROZEN_RANGE = ("2023-02-13", "2023-03-15")+++def frozen_clock():+ with patch("litellm.proxy.management_endpoints.gateway_request_endpoints.datetime") as clock:+ clock.now.return_value = _FROZEN_NOW+ yield+++def _row(+ date: str = "2026-08-04",+ category: str = "llm",+ route: str = "/chat/completions",+ successful: int = 0,+ failed: int = 0,+) -> _AggregateRow:+ return _AggregateRow(+ date=date,+ category=category,+ route=route,+ successful_requests=successful,+ failed_requests=failed,+ )+++def _admin() -> UserAPIKeyAuth:+ return UserAPIKeyAuth(api_key="sk-test", user_role=LitellmUserRoles.PROXY_ADMIN)+++def _prisma_returning(rows: list) -> MagicMock:+ client = MagicMock()+ client.db = MagicMock()+ client.db.query_raw = AsyncMock(return_value=rows)+ return client+++class TestDefaultRange:+ def test_spans_the_documented_lookback(self):+ start, end = _default_range()+ span = datetime.strptime(end, "%Y-%m-%d") - datetime.strptime(start, "%Y-%m-%d")+ assert span == timedelta(days=30)++ def test_ends_today_in_utc(self, frozen_clock):+ assert _default_range() == _FROZEN_RANGE+++class TestFoldByDate:+ def test_sums_every_route_into_one_entry_per_date(self):+ folded = _fold_by_date(+ (+ _row(date="2026-08-03", route="/chat/completions", successful=5, failed=1),+ _row(date="2026-08-03", route="/embeddings", successful=2, failed=0),+ _row(date="2026-08-04", route="/chat/completions", successful=7, failed=3),+ )+ )+ assert [(entry.date, entry.successful_requests, entry.failed_requests) for entry in folded] == [+ ("2026-08-03", 7, 1),+ ("2026-08-04", 7, 3),+ ]++ def test_orders_oldest_first_regardless_of_row_order(self):+ rows = (_row(date="2026-08-09"), _row(date="2026-08-01"), _row(date="2026-08-05"))+ assert [entry.date for entry in _fold_by_date(rows)] == ["2026-08-01", "2026-08-05", "2026-08-09"]+ assert [entry.date for entry in _fold_by_date(tuple(reversed(rows)))] == [+ "2026-08-01",+ "2026-08-05",+ "2026-08-09",+ ]++ def test_no_rows_yields_no_entries(self):+ assert _fold_by_date(()) == ()+++class TestFoldByRoute:+ def test_sums_across_dates_for_one_route(self):+ folded = _fold_by_route(+ (+ _row(date="2026-08-03", route="/chat/completions", successful=5, failed=1),+ _row(date="2026-08-04", route="/chat/completions", successful=7, failed=3),+ )+ )+ assert len(folded) == 1+ assert (folded[0].route, folded[0].successful_requests, folded[0].failed_requests) == (+ "/chat/completions",+ 12,+ 4,+ )++ def test_keeps_same_route_under_different_categories_apart(self):+ folded = _fold_by_route(+ (+ _row(category="mcp", route="/tools/call", successful=2),+ _row(category="a2a", route="/tools/call", successful=1),+ )+ )+ assert {(entry.category, entry.successful_requests) for entry in folded} == {("mcp", 2), ("a2a", 1)}++ def test_orders_busiest_route_first_whatever_the_row_order(self):+ rows = (+ _row(route="/embeddings", successful=4),+ _row(route="/chat/completions", successful=11),+ _row(route="/rerank", successful=7),+ )+ expected = ["/chat/completions", "/rerank", "/embeddings"]+ assert [entry.route for entry in _fold_by_route(rows)] == expected+ assert [entry.route for entry in _fold_by_route(tuple(reversed(rows)))] == expected+++class TestGatewayDailyActivityEndpoint:+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "role",+ [+ LitellmUserRoles.INTERNAL_USER,+ LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,+ LitellmUserRoles.TEAM,+ LitellmUserRoles.ORG_ADMIN,+ ],+ )+ async def test_refuses_every_non_admin_role(self, role):+ with patch("litellm.proxy.proxy_server.prisma_client", _prisma_returning([])):+ with pytest.raises(HTTPException) as exc:+ await get_gateway_daily_activity(+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test", user_role=role),+ )+ assert exc.value.status_code == 403++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "role",+ [LitellmUserRoles.PROXY_ADMIN, LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY],+ )+ async def test_serves_both_admin_roles(self, role):+ with patch("litellm.proxy.proxy_server.prisma_client", _prisma_returning([])):+ response = await get_gateway_daily_activity(+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test", user_role=role),+ )+ assert response.total_successful_requests == 0++ @pytest.mark.asyncio+ async def test_reports_db_not_connected_rather_than_crashing(self):+ with patch("litellm.proxy.proxy_server.prisma_client", None):+ with pytest.raises(HTTPException) as exc:+ await get_gateway_daily_activity(user_api_key_dict=_admin())+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ async def test_totals_and_breakdowns_come_from_the_same_rows(self):+ rows = [+ {+ "date": "2026-08-03",+ "category": "llm",+ "route": "/chat/completions",+ "successful_requests": 5,+ "failed_requests": 1,+ },+ {+ "date": "2026-08-04",+ "category": "llm",+ "route": "/chat/completions",+ "successful_requests": 7,+ "failed_requests": 3,+ },+ {+ "date": "2026-08-04",+ "category": "llm",+ "route": "/embeddings",+ "successful_requests": 4,+ "failed_requests": 0,+ },+ ]+ with patch("litellm.proxy.proxy_server.prisma_client", _prisma_returning(rows)):+ response = await get_gateway_daily_activity(user_api_key_dict=_admin())++ assert response.total_successful_requests == 16+ assert response.total_failed_requests == 4+ assert sum(entry.successful_requests for entry in response.by_date) == 16+ assert sum(entry.successful_requests for entry in response.by_route) == 16+ assert [entry.date for entry in response.by_date] == ["2026-08-03", "2026-08-04"]+ assert [entry.route for entry in response.by_route] == ["/chat/completions", "/embeddings"]++ @pytest.mark.asyncio+ async def test_a_null_result_set_is_not_an_error(self):+ client = _prisma_returning(None)+ with patch("litellm.proxy.proxy_server.prisma_client", client):+ response = await get_gateway_daily_activity(user_api_key_dict=_admin())+ assert response.total_successful_requests == 0+ assert response.by_date == ()+ assert response.by_route == ()++class TestGatewayDailyActivityRoute:+ """+ Driven through the mounted route rather than by calling the handler.++ The date parameters carry FastAPI ``Query`` defaults, which only resolve to+ None when the framework builds the call; invoking the handler directly hands+ it the Query object instead, so a direct call cannot check what an omitted+ date does.+ """++ def test_caller_dates_are_passed_through_verbatim(self):+ prisma = _prisma_returning([])+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = _admin+ with patch("litellm.proxy.proxy_server.prisma_client", prisma):+ response = TestClient(app).get(+ "/gateway/daily/activity",+ params={"start_date": "2026-01-01", "end_date": "2026-01-31"},+ )+ assert response.status_code == 200+ _, start, end = prisma.db.query_raw.call_args.args+ assert (start, end) == ("2026-01-01", "2026-01-31")++ def test_omitted_dates_fall_back_to_the_default_window(self, frozen_clock):+ prisma = _prisma_returning([])+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = _admin+ with patch("litellm.proxy.proxy_server.prisma_client", prisma):+ response = TestClient(app).get("/gateway/daily/activity")+ assert response.status_code == 200+ _, start, end = prisma.db.query_raw.call_args.args+ assert (start, end) == _FROZEN_RANGE++ def test_serialized_response_carries_the_documented_shape(self):+ prisma = _prisma_returning(+ [+ {+ "date": "2026-08-04",+ "category": "llm",+ "route": "/chat/completions",+ "successful_requests": 7,+ "failed_requests": 3,+ }+ ]+ )+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = _admin+ with patch("litellm.proxy.proxy_server.prisma_client", prisma):+ body = TestClient(app).get("/gateway/daily/activity").json()++ assert body == {+ "total_successful_requests": 7,+ "total_failed_requests": 3,+ "by_date": [{"date": "2026-08-04", "successful_requests": 7, "failed_requests": 3}],+ "by_route": [+ {+ "category": "llm",+ "route": "/chat/completions",+ "successful_requests": 7,+ "failed_requests": 3,+ }+ ],+ }diff --git a/tests/test_litellm/proxy/middleware/test_billable_request_metrics_middleware.py b/tests/test_litellm/proxy/middleware/test_billable_request_metrics_middleware.pyindex 9363c50407d..ff7a24db832 100644--- a/tests/test_litellm/proxy/middleware/test_billable_request_metrics_middleware.py+++ b/tests/test_litellm/proxy/middleware/test_billable_request_metrics_middleware.py@@ -18,6 +18,7 @@ from starlette.responses import JSONResponse, Responsefrom starlette.routing import Routefrom starlette.testclient import TestClient+from litellm.proxy.db.gateway_request_tracking import GatewayRequestAccumulatorfrom litellm.proxy.middleware.billable_request_metrics_middleware import (BillableCategory,BillableRequestMetricsMiddleware,@@ -456,3 +457,128 @@ def test_billable_middleware_is_registered_inside_the_in_flight_tracker():classes = [middleware.cls for middleware in proxy_app.user_middleware]assert classes.index(InFlightRequestsMiddleware) < classes.index(BillableRequestMetricsMiddleware)+++# ── gateway request sink (SGR) ────────────────────────────────────────────────+++class FakeSink:+ def __init__(self) -> None:+ self.calls: List[dict] = []++ def record(self, *, category: BillableCategory, route: str, status_code: int) -> None:+ self.calls.append({"category": category, "route": route, "status_code": status_code})+++def _make_sink_app(+ recorder: Optional[FakeRecorder],+ sink: Optional[FakeSink],+ status_code: int = 200,+ model_id: Optional[str] = None,+) -> Starlette:+ app = _make_app(None, status_code=status_code, model_id=model_id)+ app.user_middleware.clear()+ app.add_middleware(BillableRequestMetricsMiddleware, recorder=recorder, sink=sink)+ return app+++def test_sink_records_on_2xx():+ sink = FakeSink()+ TestClient(_make_sink_app(None, sink, status_code=200, model_id="m-1")).post("/v1/chat/completions")+ assert sink.calls == [{"category": BillableCategory.LLM, "route": "/chat/completions", "status_code": 200}]+++def test_varying_model_ids_fold_into_a_single_persisted_key():+ """+ The deployment that served a request reaches the middleware as the+ x-litellm-model-id header, and a caller has some say in which deployment+ that is. The SGR key is persisted, so it must not carry that dimension: a+ caller who could vary it could mint an unbounded number of table rows.+ """+ accumulator = GatewayRequestAccumulator()+ for model_id in ("deploy-1", "deploy-2", "deploy-3"):+ client = TestClient(_make_sink_app(None, accumulator, status_code=200, model_id=model_id))+ client.post("/v1/chat/completions")++ snapshot = accumulator.drain()+ assert len(snapshot) == 1+ assert next(iter(snapshot.values())).successful_requests == 3++[email protected]("status_code", [400, 429, 500, 503])+def test_sink_records_failures_that_billing_ignores(status_code: int):+ """SGR needs failed_requests, so the sink sees non-2xx. Billing must not."""+ sink, recorder = FakeSink(), FakeRecorder()+ TestClient(_make_sink_app(recorder, sink, status_code=status_code)).post("/v1/chat/completions")+ assert [call["status_code"] for call in sink.calls] == [status_code]+ assert recorder.calls == []+++def test_sink_runs_when_billing_recorder_is_absent():+ """The OSS case. Billing is license-gated; the SGR dashboard is not, so an+ absent recorder must not switch off the sink."""+ sink = FakeSink()+ TestClient(_make_sink_app(None, sink, status_code=200)).post("/v1/chat/completions")+ assert len(sink.calls) == 1+++def test_billing_recorder_still_2xx_only_when_sink_present():+ sink, recorder = FakeSink(), FakeRecorder()+ client = TestClient(_make_sink_app(recorder, sink, status_code=200))+ client.post("/v1/chat/completions")+ assert len(recorder.calls) == 1+ assert len(sink.calls) == 1+++def test_sink_ignores_non_billable_paths():+ sink = FakeSink()+ TestClient(_make_sink_app(None, sink, status_code=200)).post("/health")+ assert sink.calls == []+++def test_sink_raising_does_not_fail_the_request_or_block_billing():+ class ExplodingSink:+ def record(self, *, category, route, status_code):+ raise RuntimeError("db gone")++ recorder = FakeRecorder()+ app = _make_app(None, status_code=200)+ app.user_middleware.clear()+ app.add_middleware(BillableRequestMetricsMiddleware, recorder=recorder, sink=ExplodingSink())+ response = TestClient(app).post("/v1/chat/completions")+ assert response.status_code == 200+ assert len(recorder.calls) == 1+++def test_passthrough_only_when_both_recorder_and_sink_are_none():+ response = TestClient(_make_sink_app(None, None, status_code=200)).post("/v1/chat/completions")+ assert response.status_code == 200+++def test_sink_factory_not_called_at_init():+ calls = []++ def factory():+ calls.append(1)+ return FakeSink()++ BillableRequestMetricsMiddleware(_make_app(None), sink_factory=factory)+ assert calls == []+++def test_sink_factory_resolved_once_across_requests():+ sink = FakeSink()+ calls = []++ def factory():+ calls.append(1)+ return sink++ app = _make_app(None, status_code=200)+ app.user_middleware.clear()+ app.add_middleware(BillableRequestMetricsMiddleware, sink_factory=factory)+ client = TestClient(app)+ client.post("/v1/chat/completions")+ client.post("/v1/chat/completions")+ assert calls == [1]+ assert len(sink.calls) == 2diff --git a/tests/test_litellm/proxy/proxy_server/test_lifecycle.py b/tests/test_litellm/proxy/proxy_server/test_lifecycle.pyindex a3f5049ef1d..cf83300ab3b 100644--- a/tests/test_litellm/proxy/proxy_server/test_lifecycle.py+++ b/tests/test_litellm/proxy/proxy_server/test_lifecycle.py@@ -123,6 +123,66 @@ async def test_proxy_shutdown_event_disconnects_prisma_and_resets(monkeypatch):}+async def test_proxy_shutdown_drains_gateway_requests_before_disconnecting(monkeypatch):+ """+ The gateway request fold lives in memory, so shutdown drains it to the database.++ That drain has to happen while prisma is still connected: a write attempted+ after ``disconnect()`` raises ClientNotConnectedError, the flush swallows it+ and merges the counts back onto an accumulator the process is about to+ discard, and the final interval is lost silently on every restart. Ordering is+ the whole behavior here, so assert the order rather than that both ran.+ """+ calls: list = [] # mutable-ok: records call order, which is the assertion++ fake_prisma = MagicMock()+ fake_prisma.disconnect = AsyncMock(side_effect=lambda: calls.append("disconnect"))+ monkeypatch.setattr(ps, "prisma_client", fake_prisma, raising=False)++ async def _record_flush(client, accumulator):+ calls.append("flush")+ assert client is fake_prisma++ monkeypatch.setattr(ps, "flush_gateway_requests", _record_flush, raising=False)++ fake_jwt = MagicMock()+ fake_jwt.close = AsyncMock()+ monkeypatch.setattr(ps, "jwt_handler", fake_jwt, raising=False)+ monkeypatch.setattr(ps, "db_writer_client", None, raising=False)++ import litellm++ monkeypatch.setattr(litellm, "cache", None, raising=False)+ monkeypatch.setattr(litellm, "success_callback", [], raising=False)++ await proxy_shutdown_event()++ assert calls == ["flush", "disconnect"]+++async def test_proxy_shutdown_skips_gateway_flush_without_a_database(monkeypatch):+ """No prisma client means nothing to drain to, and no attempt is made."""+ flush = AsyncMock()+ monkeypatch.setattr(ps, "flush_gateway_requests", flush, raising=False)+ monkeypatch.setattr(ps, "prisma_client", None, raising=False)++ fake_jwt = MagicMock()+ fake_jwt.close = AsyncMock()+ monkeypatch.setattr(ps, "jwt_handler", fake_jwt, raising=False)+ monkeypatch.setattr(ps, "db_writer_client", None, raising=False)++ import litellm++ monkeypatch.setattr(litellm, "cache", None, raising=False)+ monkeypatch.setattr(litellm, "success_callback", [], raising=False)++ await proxy_shutdown_event()++ assert flush.await_count == 0++@pytest.mark.asyncioasync def test_proxy_shutdown_event_prisma_disconnect_raises_error(monkeypatch):fake_prisma = MagicMock()diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsxindex 98dae51fa37..0ded7d195d0 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx@@ -25,6 +25,7 @@ beforeAll(() => {vi.mock("@/components/networking", () => ({userDailyActivityCall: vi.fn(),userDailyActivityAggregatedCall: vi.fn(),+ gatewayDailyActivityCall: vi.fn(),tagListCall: vi.fn(),}));@@ -84,9 +85,23 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => {vi.mock("@/components/shared/advanced_date_picker", async () => {const React = await import("react");- const AdvancedDatePicker = () => {- return React.createElement("div", { "data-testid": "advanced-date-picker" }, "Date Picker");- };+ // The button is how a test drives a range change; the real picker's own UI is+ // not what any test here is asserting on.+ const AdvancedDatePicker = ({ onValueChange }: { onValueChange?: (value: unknown) => void }) =>+ React.createElement(+ "div",+ { "data-testid": "advanced-date-picker" },+ "Date Picker",+ React.createElement(+ "button",+ {+ "data-testid": "pick-a-different-range",+ onClick: () =>+ onValueChange?.({ from: new Date("2024-01-01T00:00:00Z"), to: new Date("2024-01-08T00:00:00Z") }),+ },+ "pick",+ ),+ );AdvancedDatePicker.displayName = "AdvancedDatePicker";return { default: AdvancedDatePicker };});@@ -333,6 +348,7 @@ describe("UsagePage", () => {const mockUserDailyActivityAggregatedCall = vi.mocked(networking.userDailyActivityAggregatedCall);const mockUserDailyActivityCall = vi.mocked(networking.userDailyActivityCall);const mockTagListCall = vi.mocked(networking.tagListCall);+ const mockGatewayDailyActivityCall = vi.mocked(networking.gatewayDailyActivityCall);const mockUseCustomers = vi.mocked(useCustomers);const mockUseAgents = vi.mocked(useAgents);const mockUseAuthorized = vi.mocked(useAuthorized);@@ -476,6 +492,30 @@ describe("UsagePage", () => {},];+ // The same session the suite runs as, minus the admin role. Named rather than+ // inlined so the test reads as "this session, but not an admin".+ const nonAdminSession = {+ isLoading: false,+ isAuthorized: true,+ token: "mock-token",+ accessToken: "test-token",+ userId: "user-123",+ userEmail: "[email protected]",+ userRole: "Internal User",+ premiumUser: true,+ disabledPersonalKeyCreation: false,+ showSSOBanner: false,+ };++ // Counts deliberately unlike anything in mockSpendData: the gateway tile must be+ // readable as coming from /gateway/daily/activity and from nothing else.+ const mockGatewayActivity = {+ total_successful_requests: 424242,+ total_failed_requests: 909,+ by_date: [{ date: "2025-01-01", successful_requests: 424242, failed_requests: 909 }],+ by_route: [{ category: "llm", route: "/chat/completions", successful_requests: 424242, failed_requests: 909 }],+ };+const defaultProps = {teams: [{@@ -522,7 +562,9 @@ describe("UsagePage", () => {mockUserDailyActivityAggregatedCall.mockClear();mockUserDailyActivityCall.mockClear();mockTagListCall.mockClear();+ mockGatewayDailyActivityCall.mockClear();mockUserDailyActivityAggregatedCall.mockResolvedValue(mockSpendData);+ mockGatewayDailyActivityCall.mockResolvedValue(mockGatewayActivity);mockUseInfiniteUsers.mockReturnValue({data: {pages: [@@ -571,9 +613,80 @@ describe("UsagePage", () => {expect(screen.getByText("1,500")).toBeInTheDocument();const successfulRequestLabelElements = screen.getAllByText("Successful Requests");expect(successfulRequestLabelElements.length).toBeGreaterThan(0);- // Use getAllByText since this value appears in multiple places (metrics card + table)- const successfulRequestElements = screen.getAllByText("1,450");- expect(successfulRequestElements.length).toBeGreaterThan(0);+ // Successful and Failed Requests both read the gateway counter, not the+ // spend-derived 1,450 / 50 that the same payload carries for the per-key and+ // per-model breakdowns. They must share a source, or the tiles contradict the+ // endpoint breakdown chart below them.+ await waitFor(() => {+ expect(screen.getAllByText("424,242").length).toBeGreaterThan(0);+ });+ expect(screen.getAllByText("909").length).toBeGreaterThan(0);+ expect(screen.queryByText("1,450")).not.toBeInTheDocument();+ });++ it("should stop showing the previous range's totals while a new range is in flight", async () => {+ // The request tiles read the gateway counts and fall through to the+ // spend-derived ones. Withholding a superseded gateway result is only worth+ // something if the fallback is withheld too, otherwise the tile keeps+ // showing the previous range's number by the other route.+ let releaseSecondFetch: () => void = () => {};+ mockUserDailyActivityAggregatedCall.mockReset();+ mockUserDailyActivityAggregatedCall.mockResolvedValueOnce(mockSpendData).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseSecondFetch = () => resolve(mockSpendData);+ }),+ );++ renderWithProviders(<UsagePage {...defaultProps} />);+ await waitFor(() => {+ expect(screen.getAllByText("1,500").length).toBeGreaterThan(0);+ });++ await act(async () => {+ fireEvent.click(screen.getByTestId("pick-a-different-range"));+ });++ await waitFor(() => {+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalledTimes(2);+ });+ expect(screen.queryByText("1,500")).not.toBeInTheDocument();++ await act(async () => {+ releaseSecondFetch();+ });+ await waitFor(() => {+ expect(screen.getAllByText("1,500").length).toBeGreaterThan(0);+ });+ });++ it("should fall back to the spend-derived count when the gateway endpoint is unavailable", async () => {+ mockGatewayDailyActivityCall.mockRejectedValue(new Error("gateway activity unavailable"));++ renderWithProviders(<UsagePage {...defaultProps} />);++ await waitFor(() => {+ expect(mockGatewayDailyActivityCall).toHaveBeenCalled();+ });+ await waitFor(() => {+ expect(screen.getAllByText("1,450").length).toBeGreaterThan(0);+ });+ expect(screen.queryByText("424,242")).not.toBeInTheDocument();+ expect(screen.queryByText("909")).not.toBeInTheDocument();+ expect(screen.queryByTestId("gateway-requests-by-endpoint")).not.toBeInTheDocument();+ });++ it("should not request deployment-wide gateway counts for a non-admin", async () => {+ mockUseAuthorized.mockReturnValue(nonAdminSession);++ renderWithProviders(<UsagePage {...defaultProps} />);++ await waitFor(() => {+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();+ });+ expect(mockGatewayDailyActivityCall).not.toHaveBeenCalled();+ expect(screen.queryByText("424,242")).not.toBeInTheDocument();+ expect(screen.queryByTestId("gateway-requests-by-endpoint")).not.toBeInTheDocument();});it("should display usage metrics and charts", async () => {@@ -605,13 +718,20 @@ describe("UsagePage", () => {expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();});+ // The gateway endpoint breakdown is a separate chart with its own palette,+ // so it is excluded rather than allowed to widen the expected fill set.+ const spendBars = () => {+ const gatewayCard = container.querySelector('[data-testid="gateway-requests-by-endpoint"]');+ return Array.from(container.querySelectorAll("path.recharts-rectangle")).filter(+ (rect) => !gatewayCard?.contains(rect),+ );+ };+await waitFor(() => {- expect(container.querySelectorAll("path.recharts-rectangle")).toHaveLength(2);+ expect(spendBars()).toHaveLength(2);});- const fills = new Set(- Array.from(container.querySelectorAll("path.recharts-rectangle")).map((rect) => rect.getAttribute("fill")),- );+ const fills = new Set(spendBars().map((rect) => rect.getAttribute("fill")));expect(fills).toEqual(new Set(["var(--color-cyan-500, #06b6d4)"]));expect(screen.getAllByText("2025-01-01").length).toBeGreaterThan(0);@@ -916,6 +1036,47 @@ describe("UsagePage", () => {expect(screen.getByText("1,500")).toBeInTheDocument();});+ it("should stop showing the previous range's paginated pages while a new range is in flight", async () => {+ // Same rule as the aggregate, one fallback further down. The flag that+ // decides whether these pages are read belongs to the range the failure+ // happened on, or the previous range's pages reach the tile through it.+ let releaseSecondAggregated: () => void = () => {};+ mockUserDailyActivityAggregatedCall.mockReset();+ mockUserDailyActivityAggregatedCall+ .mockRejectedValueOnce(new Error("Aggregated endpoint not available"))+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ releaseSecondAggregated = () => reject(new Error("Aggregated endpoint not available"));+ }),+ );+ mockUserDailyActivityCall.mockResolvedValue({+ ...mockSpendData,+ metadata: { ...mockSpendData.metadata, total_pages: 1, page: 1 },+ });++ renderWithProviders(<UsagePage {...defaultProps} />);+ await waitFor(() => {+ expect(screen.getAllByText("1,500").length).toBeGreaterThan(0);+ });++ await act(async () => {+ fireEvent.click(screen.getByTestId("pick-a-different-range"));+ });++ await waitFor(() => {+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalledTimes(2);+ });+ expect(screen.queryByText("1,500")).not.toBeInTheDocument();++ await act(async () => {+ releaseSecondAggregated();+ });+ await waitFor(() => {+ expect(screen.getAllByText("1,500").length).toBeGreaterThan(0);+ });+ });+it("should aggregate multiple pages when paginated endpoint has more than 1 page", async () => {mockUserDailyActivityAggregatedCall.mockRejectedValue(new Error("Not available"));diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsxindex 46a17017d39..e73dddd9788 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx@@ -40,6 +40,7 @@ import CloudZeroExportModal from "@/components/cloudzero_export_modal";import EntityUsageExportModal from "@/components/EntityUsageExport";import { Team } from "@/components/key_team_helpers/key_list";import {+ gatewayDailyActivityCall,Organization,tagListCall,userDailyActivityAggregatedCall,@@ -53,6 +54,15 @@ import ViewUserSpend from "@/components/view_user_spend";import { usePaginatedDailyActivity } from "../hooks/usePaginatedDailyActivity";import { DailyData, KeyMetricWithMetadata, MetricWithMetadata } from "@/components/UsagePage/types";import { valueFormatterSpend } from "@/components/UsagePage/utils/value_formatters";+import {+ fetchedRangeKey,+ selectForRange,+ selectGatewayActivity,+ topGatewayRoutes,+ type FetchedForRange,+ type FetchedGatewayActivity,+ type GatewayActivity,+} from "./gatewayActivity";import EndpointUsage from "./EndpointUsage/EndpointUsage";import EntityUsage, { EntityList } from "./EntityUsage/EntityUsage";import ModelViewToggle, { ModelViewType } from "./ModelViewToggle";@@ -69,9 +79,16 @@ interface UsagePageProps {const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {const { accessToken, userRole, userId: userID, premiumUser } = useAuthorized();// Aggregated endpoint: try first, fall back to paginated if unavailable- const [aggregatedData, setAggregatedData] = useState<{ results: DailyData[]; metadata: any } | null>(null);- const [aggregatedFailed, setAggregatedFailed] = useState(false);+ const [aggregatedData, setAggregatedData] = useState<FetchedForRange<{+ results: DailyData[];+ metadata: any;+ }> | null>(null);+ // Stamped like the data itself: the flag decides whether the paginated+ // fallback is read, and a flag left over from the previous range would let+ // that fallback's own leftover rows through.+ const [aggregatedFailure, setAggregatedFailure] = useState<FetchedForRange<true> | null>(null);const [aggregatedLoading, setAggregatedLoading] = useState(false);+ const [gatewayActivityData, setGatewayActivityData] = useState<FetchedGatewayActivity | null>(null);// Separate loading states for better UXconst [isDateChanging, setIsDateChanging] = useState(false);@@ -190,28 +207,65 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {};}, [accessToken, startTime, endTime]);+ // Everything the request tiles read is stamped with the range it answers and+ // selected during render, rather than cleared in an effect. An effect runs+ // after the render that follows a date change, so state cleared there is one+ // render too late: that render still holds the previous range's numbers and+ // can paint them. One source is not enough, since the tiles read the gateway+ // counts, fall through to the aggregate, and fall through again to the+ // paginated pages, so a stamp on any one of them is escaped by the next.+ const currentAggregatedRangeKey = fetchedRangeKey(startTime, endTime, effectiveUserId);+ const currentGatewayRangeKey = fetchedRangeKey(startTime, endTime);+// Try aggregated endpoint first, fall back to paginated on failureconst aggregatedFetchIdRef = useRef(0);useEffect(() => {if (!accessToken || !startTime || !endTime) return;const fetchId = ++aggregatedFetchIdRef.current;+ const rangeKey = currentAggregatedRangeKey;setAggregatedLoading(true);- setAggregatedFailed(false);- setAggregatedData(null);userDailyActivityAggregatedCall(accessToken, startTime, endTime, effectiveUserId).then((data) => {if (aggregatedFetchIdRef.current !== fetchId) return;- setAggregatedData(data);+ setAggregatedData({ rangeKey, value: data });setAggregatedLoading(false);setIsDateChanging(false);}).catch(() => {if (aggregatedFetchIdRef.current !== fetchId) return;- setAggregatedFailed(true);+ setAggregatedFailure({ rangeKey, value: true });setAggregatedLoading(false);});- }, [accessToken, startTime, endTime, effectiveUserId]);+ }, [accessToken, startTime, endTime, effectiveUserId, currentAggregatedRangeKey]);++ // Gateway request counts (SGR). Admin-only: the source table is+ // deployment-wide, so a non-admin must not see it.+ const gatewayRequest = useMemo(+ () => (accessToken && startTime && endTime ? { accessToken, startTime, endTime } : null),+ [accessToken, startTime, endTime],+ );+ const gatewayFetchIdRef = useRef(0);+ useEffect(() => {+ if (!isAdmin || !gatewayRequest) return;+ const fetchId = ++gatewayFetchIdRef.current;+ gatewayDailyActivityCall(gatewayRequest.accessToken, gatewayRequest.startTime, gatewayRequest.endTime)+ .then((data) => {+ if (gatewayFetchIdRef.current !== fetchId) return;+ setGatewayActivityData({ rangeKey: currentGatewayRangeKey, value: data as GatewayActivity });+ })+ .catch(() => {+ if (gatewayFetchIdRef.current !== fetchId) return;+ setGatewayActivityData(null);+ });+ }, [isAdmin, gatewayRequest, currentGatewayRangeKey]);++ const gatewayActivity = selectGatewayActivity(isAdmin, gatewayActivityData, currentGatewayRangeKey);+ const activeAggregated = selectForRange(aggregatedData, currentAggregatedRangeKey);+ // A failure belongs to the range it happened on. Reading it through the same+ // rule keeps the paginated hook disabled while a new range is in flight, and+ // disabled is what empties it, so its previous rows never reach a tile.+ const aggregatedFailed = selectForRange(aggregatedFailure, currentAggregatedRangeKey) === true;// Paginated fallback — only enabled when aggregated endpoint failsconst paginatedResult = usePaginatedDailyActivity({@@ -222,10 +276,10 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {// Derive userSpendData from whichever source is activeconst userSpendData = useMemo(() => {- if (aggregatedData) return aggregatedData;+ if (activeAggregated) return activeAggregated;if (aggregatedFailed) return paginatedResult.data;return { results: [] as DailyData[], metadata: {} as any };- }, [aggregatedData, aggregatedFailed, paginatedResult.data]);+ }, [activeAggregated, aggregatedFailed, paginatedResult.data]);const loading = aggregatedLoading || paginatedResult.loading;@@ -439,6 +493,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {() => [...userSpendData.results].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()),[userSpendData.results],);+ const gatewayRequestsByRoute = useMemo(() => topGatewayRoutes(gatewayActivity), [gatewayActivity]);const modelMetrics = useMemo(() => processActivityData(userSpendData, modelViewType === "groups" ? "model_groups" : "models", teams),[userSpendData, modelViewType, teams],@@ -616,20 +671,47 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {</Text></Card><Card>- <Title>Successful Requests</Title>+ <div className="flex items-center gap-2">+ <Title>Successful Requests</Title>+ {gatewayActivity && (+ <Tooltip title="Counted by the gateway when it answers a request, independent of spend logging. Deployment-wide, so it will not match the per-key or per-model breakdowns below.">+ <InfoCircleOutlined className="text-gray-400 hover:text-gray-600" />+ </Tooltip>+ )}+ </div>+ {/*+ TODO: drop the userSpendData fallback once every deployment+ is writing LiteLLM_DailyGatewayRequests. It covers two cases+ today: a non-admin (who may not read deployment-wide counts)+ and an admin on a proxy whose table is still backfilling.+ */}<Text className="text-2xl font-bold mt-2 text-green-600">- {userSpendData.metadata?.total_successful_requests?.toLocaleString() || 0}+ {(+ gatewayActivity?.total_successful_requests ??+ userSpendData.metadata?.total_successful_requests+ )?.toLocaleString() || 0}</Text></Card><Card><div className="flex items-center gap-2"><Title>Failed Requests</Title>- <Tooltip title="Includes requests that failed to route to a provider, tool usage failures, and other request errors where the provider cannot be determined.">+ <Tooltip+ title={+ gatewayActivity+ ? "Counted by the gateway when it answers a request, independent of spend logging. Deployment-wide, so it will not match the per-key or per-model breakdowns below."+ : "Includes requests that failed to route to a provider, tool usage failures, and other request errors where the provider cannot be determined."+ }+ ><InfoCircleOutlined className="text-gray-400 hover:text-gray-600" /></Tooltip></div>+ {/* Same source as Successful Requests: the two must agree, or the+ tile disagrees with the endpoint breakdown chart below it. */}<Text className="text-2xl font-bold mt-2 text-red-600">- {userSpendData.metadata?.total_failed_requests?.toLocaleString() || 0}+ {(+ gatewayActivity?.total_failed_requests ??+ userSpendData.metadata?.total_failed_requests+ )?.toLocaleString() || 0}</Text></Card><Card>@@ -729,6 +811,32 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {</CardContent></ShadcnCard></Col>+ {/* Gateway Requests by Endpoint (SGR) */}+ {gatewayActivity && gatewayActivity.by_route.length > 0 && (+ <Col numColSpan={2}>+ <ShadcnCard data-testid="gateway-requests-by-endpoint">+ <CardHeader>+ <CardTitle className="text-base font-semibold">+ Gateway Requests by Endpoint+ <Tooltip title="Counted by the gateway middleware as each request is answered. Covers LLM, MCP and A2A endpoints across the whole deployment.">+ <InfoCircleOutlined className="ml-2 text-gray-400 hover:text-gray-600" />+ </Tooltip>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <BarChart+ data={gatewayRequestsByRoute}+ index="route"+ categories={["successful_requests", "failed_requests"]}+ colors={["green", "red"]}+ stack={true}+ yAxisWidth={100}+ valueFormatter={(value: number) => value.toLocaleString()}+ />+ </CardContent>+ </ShadcnCard>+ </Col>+ )}{/* Top API Keys */}<Col numColSpan={1}><Card className="h-full">diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.test.tsnew file mode 100644index 00000000000..75177b98a41--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest";+import {+ GATEWAY_TOP_ROUTES,+ fetchedRangeKey,+ selectForRange,+ selectGatewayActivity,+ topGatewayRoutes,+ type GatewayActivity,+} from "./gatewayActivity";++const activity = (total: number): GatewayActivity => ({+ total_successful_requests: total,+ total_failed_requests: 0,+ by_date: [{ date: "2025-01-01", successful_requests: total, failed_requests: 0 }],+ by_route: [{ category: "llm", route: "/chat/completions", successful_requests: total, failed_requests: 0 }],+});++const JANUARY = fetchedRangeKey(new Date("2025-01-01T00:00:00Z"), new Date("2025-01-31T00:00:00Z"));+const FEBRUARY = fetchedRangeKey(new Date("2025-02-01T00:00:00Z"), new Date("2025-02-28T00:00:00Z"));++describe("fetchedRangeKey", () => {+ it("distinguishes ranges that differ only in their end", () => {+ const start = new Date("2025-01-01T00:00:00Z");+ expect(fetchedRangeKey(start, new Date("2025-01-31T00:00:00Z"))).not.toEqual(+ fetchedRangeKey(start, new Date("2025-02-28T00:00:00Z")),+ );+ });++ it("distinguishes the same range fetched for two different users", () => {+ const start = new Date("2025-01-01T00:00:00Z");+ const end = new Date("2025-01-31T00:00:00Z");+ expect(fetchedRangeKey(start, end, "user-a")).not.toEqual(fetchedRangeKey(start, end, "user-b"));+ });++ it("is stable for equal instants held in different Date objects", () => {+ expect(fetchedRangeKey(new Date("2025-01-01T00:00:00Z"), new Date("2025-01-31T00:00:00Z"))).toEqual(JANUARY);+ });++ it("tolerates a range that has not been picked yet", () => {+ expect(fetchedRangeKey(null, null)).toEqual("||");+ });+});++describe("selectForRange", () => {+ it("returns the value when it was fetched for the selected range", () => {+ expect(selectForRange({ rangeKey: JANUARY, value: 7 }, JANUARY)).toEqual(7);+ });++ it("withholds the previous range's value while a new range is in flight", () => {+ expect(selectForRange({ rangeKey: JANUARY, value: 7 }, FEBRUARY)).toBeNull();+ });++ it("returns null before anything has been fetched", () => {+ expect(selectForRange(null, JANUARY)).toBeNull();+ });+});++describe("selectGatewayActivity", () => {+ it("returns the counts when an admin's result matches the selected range", () => {+ expect(selectGatewayActivity(true, { rangeKey: JANUARY, value: activity(7) }, JANUARY)).toEqual(activity(7));+ });++ it("withholds the previous range's counts while a new range is in flight", () => {+ expect(selectGatewayActivity(true, { rangeKey: JANUARY, value: activity(7) }, FEBRUARY)).toBeNull();+ });++ it("withholds deployment-wide counts from a non-admin", () => {+ expect(selectGatewayActivity(false, { rangeKey: JANUARY, value: activity(7) }, JANUARY)).toBeNull();+ });++ it("returns null before anything has been fetched", () => {+ expect(selectGatewayActivity(true, null, JANUARY)).toBeNull();+ });+});++describe("topGatewayRoutes", () => {+ it("leaves an llm route unprefixed and prefixes the others so they stay distinguishable", () => {+ const bars = topGatewayRoutes({+ ...activity(0),+ by_route: [+ { category: "llm", route: "/chat/completions", successful_requests: 3, failed_requests: 1 },+ { category: "mcp", route: "/tools/call", successful_requests: 2, failed_requests: 0 },+ { category: "a2a", route: "/tools/call", successful_requests: 1, failed_requests: 0 },+ ],+ });+ expect(bars.map((bar) => bar.route)).toEqual(["/chat/completions", "mcp/tools/call", "a2a/tools/call"]);+ expect(bars[0]).toEqual({ route: "/chat/completions", successful_requests: 3, failed_requests: 1 });+ });++ it("caps the bars at the top N so a wide deployment stays readable", () => {+ const many = Array.from({ length: GATEWAY_TOP_ROUTES + 5 }, (_, i) => ({+ category: "llm",+ route: `/route-${i}`,+ successful_requests: 100 - i,+ failed_requests: 0,+ }));+ const bars = topGatewayRoutes({ ...activity(0), by_route: many });+ expect(bars).toHaveLength(GATEWAY_TOP_ROUTES);+ // The cap keeps the busiest endpoints, which is only true because it slices+ // the server's descending order rather than re-sorting.+ expect(bars[0].route).toEqual("/route-0");+ expect(bars[GATEWAY_TOP_ROUTES - 1].route).toEqual(`/route-${GATEWAY_TOP_ROUTES - 1}`);+ });++ it("renders no bars when there is nothing to show", () => {+ expect(topGatewayRoutes(null)).toEqual([]);+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.ts b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.tsnew file mode 100644index 00000000000..d527e8717f0--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/gatewayActivity.ts@@ -0,0 +1,82 @@+/**+ * Gateway request counts (SGR) from `/gateway/daily/activity`.+ *+ * Recorded by the proxy's request-metrics middleware rather than derived from+ * spend logs, so it counts what the gateway actually answered. Deployment-wide+ * with no per-key or per-user dimension, which is why it is admin-only and why+ * the per-key and per-model breakdowns on the usage page still come from the+ * spend tables.+ */++export const GATEWAY_TOP_ROUTES = 15;++export interface GatewayActivity {+ total_successful_requests: number;+ total_failed_requests: number;+ by_date: { date: string; successful_requests: number; failed_requests: number }[];+ by_route: { category: string; route: string; successful_requests: number; failed_requests: number }[];+}++/** A fetched result carrying the range key it was fetched for. */+export interface FetchedForRange<T> {+ rangeKey: string;+ value: T;+}++export type FetchedGatewayActivity = FetchedForRange<GatewayActivity>;++/** Extends Record so it satisfies the chart component's row constraint. */+export interface GatewayRouteBar extends Record<string, unknown> {+ route: string;+ successful_requests: number;+ failed_requests: number;+}++/**+ * Identifies what a result was fetched for: the date range, plus any other+ * input that changes the answer. The usage aggregate is scoped to a user, so+ * two results covering the same dates still describe different numbers.+ */+export const fetchedRangeKey = (+ startTime: Date | null | undefined,+ endTime: Date | null | undefined,+ scope: string | null | undefined = null,+): string => `${startTime?.toISOString() ?? ""}|${endTime?.toISOString() ?? ""}|${scope ?? ""}`;++/**+ * The value safe to render right now, or null to fall back.+ *+ * Clearing the state inside the fetch effect is one render too late: the render+ * that follows a date change still holds the previous range's value and can+ * paint before effects run. Comparing the stamp during render is what makes a+ * superseded range unrepresentable rather than merely brief.+ */+export const selectForRange = <T>(fetched: FetchedForRange<T> | null, currentRangeKey: string): T | null =>+ fetched != null && fetched.rangeKey === currentRangeKey ? fetched.value : null;++/**+ * As `selectForRange`, and additionally withholds the counts from a non-admin:+ * they are deployment-wide, so they are not a non-admin's to read.+ */+export const selectGatewayActivity = (+ isAdmin: boolean,+ fetched: FetchedGatewayActivity | null,+ currentRangeKey: string,+): GatewayActivity | null => (isAdmin ? selectForRange(fetched, currentRangeKey) : null);++/**+ * Bars for the endpoint breakdown chart, capped so a deployment exercising many+ * endpoints does not render an unreadable axis. `by_route` arrives sorted by+ * successful_requests descending, so the cap keeps the busiest endpoints.+ */+export const topGatewayRoutes = (+ activity: GatewayActivity | null,+ limit: number = GATEWAY_TOP_ROUTES,+): GatewayRouteBar[] =>+ (activity?.by_route ?? []).slice(0, limit).map((entry) => ({+ // The llm routes are already fully qualified; mcp and a2a routes are not, so+ // their category prefix is what keeps "/mcp" apart from "/a2a".+ route: entry.category === "llm" ? entry.route : `${entry.category}${entry.route}`,+ successful_requests: entry.successful_requests,+ failed_requests: entry.failed_requests,+ }));diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 4a9a41d1cbe..65e347ede43 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -2471,6 +2471,31 @@ export const userDailyActivityAggregatedCall = async (}};+export const gatewayDailyActivityCall = async (accessToken: string, startTime: Date, endTime: Date) => {+ /**+ * Get gateway request counts (SGR) recorded by the proxy middleware.+ * Deployment-wide and admin-only; carries no per-key or per-user dimension.+ */+ try {+ const formatDate = (date: Date) => {+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ return `${year}-${month}-${day}`;+ };+ return await apiClient.get(`/gateway/daily/activity`, {+ accessToken,+ query: {+ start_date: formatDate(startTime),+ end_date: formatDate(endTime),+ },+ });+ } catch (error) {+ console.error("Failed to fetch gateway daily activity:", error);+ throw error;+ }+};+export const getPossibleUserRoles = async (accessToken: string) => {try {const data = (await apiClient.get(`/user/available_roles`, { accessToken })) as Record<diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 9408a32198a..4cdc14f9ee3 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -4180,6 +4180,29 @@ export interface paths {patch?: never;trace?: never;};+ "/gateway/daily/activity": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Get Gateway Daily Activity+ * @description Successful and failed gateway requests, counted at the ASGI edge.+ *+ * Deployment-wide: the underlying table has no per-key or per-user dimension,+ * so this is admin-only.+ */+ get: operations["get_gateway_daily_activity_gateway_daily_activity_get"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/gemini/{endpoint}": {parameters: {query?: never;@@ -24543,6 +24566,64 @@ export interface components {* @enum {string}*/GUARDRAIL_DEFINITION_LOCATION: "db" | "config";+ /**+ * GatewayRequestActivityResponse+ * @description Response for GET /gateway/daily/activity.+ */+ GatewayRequestActivityResponse: {+ /**+ * By Date+ * @default []+ */+ by_date: components["schemas"]["GatewayRequestDailyEntry"][];+ /**+ * By Route+ * @default []+ */+ by_route: components["schemas"]["GatewayRequestBreakdownEntry"][];+ /**+ * Total Failed Requests+ * @default 0+ */+ total_failed_requests: number;+ /**+ * Total Successful Requests+ * @default 0+ */+ total_successful_requests: number;+ };+ /** GatewayRequestBreakdownEntry */+ GatewayRequestBreakdownEntry: {+ /** Category */+ category: string;+ /**+ * Failed Requests+ * @default 0+ */+ failed_requests: number;+ /** Route */+ route: string;+ /**+ * Successful Requests+ * @default 0+ */+ successful_requests: number;+ };+ /** GatewayRequestDailyEntry */+ GatewayRequestDailyEntry: {+ /** Date */+ date: string;+ /**+ * Failed Requests+ * @default 0+ */+ failed_requests: number;+ /**+ * Successful Requests+ * @default 0+ */+ successful_requests: number;+ };/** GenerateKeyRequest */GenerateKeyRequest: {/** Access Group Ids */@@ -41384,6 +41465,40 @@ export interface operations {};};};+ get_gateway_daily_activity_gateway_daily_activity_get: {+ parameters: {+ query?: {+ /** @description Start date in YYYY-MM-DD format */+ start_date?: string | null;+ /** @description End date in YYYY-MM-DD format */+ 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"]["GatewayRequestActivityResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };gemini_proxy_route_gemini__endpoint__get: {parameters: {query?: never;