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
fix: bound row count on GET /spend/logs to stop unbounded LiteLLM_SpendLogs scans (#38420)
devin-ai-integration[bot]172e3aceafc2
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 06395a3c3cc..9deb52895f5 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -18,7 +18,7 @@ from typing import ()import fastapi-from fastapi import APIRouter, Depends, HTTPException, Request, status+from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom typing_extensions import ReadOnlyimport litellm@@ -208,9 +208,18 @@ async def _find_spend_logs(prisma_client: PrismaClient,where: Mapping[str, object],order: Mapping[str, str],+ take: int,+ http_response: Response,) -> Sequence[_SupportsModelDump]:- """Read spend log rows as Prisma model instances."""- return await _spend_logs_table(prisma_client).find_many(where=where, order=order)+ """Read spend log rows as Prisma model instances, capped at ``take`` rows."""+ rows: Final = await _spend_logs_table(prisma_client).find_many(where=where, order=order, take=take)+ if len(rows) == take:+ http_response.headers["x-litellm-spend-logs-truncated"] = "true"+ verbose_proxy_logger.warning(+ "/spend/logs result truncated to the %s most recent rows; use /spend/logs/v2 for paginated access",+ take,+ )+ return rowsasync def _find_spend_log_row(prisma_client: PrismaClient, request_id: str) -> _SpendLogOwnershipRow | None:@@ -2851,6 +2860,7 @@ async def ui_view_request_response_for_request_id(},)async def view_spend_logs(+ fastapi_response: Response,api_key: str | None = fastapi.Query(default=None,description="Get spend logs based on api key",@@ -2881,6 +2891,8 @@ async def view_spend_logs([DEPRECATED] This endpoint is not paginated and can cause performance issues.Please use `/spend/logs/v2` instead for paginated access to spend logs.+ Row results are capped at 10,000 most recent entries per response.+View all spend logs, if request_id is provided, only logs for that request_id will be returnedWhen start_date and end_date are provided:@@ -2931,7 +2943,6 @@ async def view_spend_logs(raise Exception("Database not connected. Connect a database to your proxy - https://docs.litellm.ai/docs/simple_proxy#managing-auth---virtual-keys")- spend_logs = []if (start_date is not Noneand isinstance(start_date, str)@@ -2970,6 +2981,8 @@ async def view_spend_logs(prisma_client,where=filter_query,order={"startTime": "desc"},+ take=SPEND_LOGS_PAGINATION_COUNT_CAP,+ http_response=fastapi_response,)return data@@ -3040,14 +3053,12 @@ async def view_spend_logs(if user_id is not None and isinstance(user_id, str):scoped_filter["user"] = user_id- if not scoped_filter:- spend_logs = await prisma_client.get_data(table_name="spend", query_type="find_all")- return spend_logs-data = await _find_spend_logs(prisma_client,where=scoped_filter,order={"startTime": "desc"},+ take=SPEND_LOGS_PAGINATION_COUNT_CAP,+ http_response=fastapi_response,)return datadiff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex 8c15ead8983..f60177a6455 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@ -3135,6 +3135,90 @@ async def test_view_spend_logs_summarize_parameter(client, monkeypatch):app.dependency_overrides.pop(ps.user_api_key_auth, None)+async def test_view_spend_logs_bounds_row_count(client, monkeypatch):+ """Every /spend/logs read path must send take=SPEND_LOGS_PAGINATION_COUNT_CAP to Prisma (LIT-6284)."""+ captured_find_many_kwargs = []++ class MockDB:+ def __init__(self):+ self.litellm_spendlogs = self+ self.available_rows = 0++ async def find_many(self, *args, **kwargs):+ captured_find_many_kwargs.append(kwargs)+ return [{}] * min(kwargs.get("take", 0), self.available_rows)++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ def hash_token(self, token):+ return f"hashed-{token}"++ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ start_date = (+ datetime.datetime.now(timezone.utc) - datetime.timedelta(days=2)+ ).strftime("%Y-%m-%d")+ end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d")+ try:+ response = client.get(+ "/spend/logs",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )+ assert "x-litellm-spend-logs-truncated" not in response.headers++ response = client.get(+ "/spend/logs",+ params={"user_id": "test-user"},+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert captured_find_many_kwargs[-1].get("where") == {"user": "test-user"}+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )++ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "summarize": "false",+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert "startTime" in captured_find_many_kwargs[-1].get("where", {})+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )++ mock_prisma_client.db.available_rows = (+ spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )+ response = client.get(+ "/spend/logs",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert len(response.json()) == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ assert response.headers["x-litellm-spend-logs-truncated"] == "true"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++@pytest.mark.asyncioasync def test_view_spend_tags(client, monkeypatch):"""Test the /spend/tags endpoint"""diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex e8a0db44c1f..5e5ff63e9ed 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -13176,6 +13176,8 @@ export interface paths {* @description [DEPRECATED] This endpoint is not paginated and can cause performance issues.* Please use `/spend/logs/v2` instead for paginated access to spend logs.*+ * Row results are capped at 10,000 most recent entries per response.+ ** View all spend logs, if request_id is provided, only logs for that request_id will be returned** When start_date and end_date are provided: