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(spend): bound the logs-tab pagination count to stop full-window scans (#31825)
Yassin Kortamdc48b2049138
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 29a970c3cfb..8f530e3b8ce 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -45,6 +45,8 @@ else:router = APIRouter()+SPEND_LOGS_PAGINATION_COUNT_CAP = 10000+@router.get("/spend/keys",@@ -1958,6 +1960,20 @@ async def ui_view_spend_logs(else:_order_expr = order_column+ count_query = f"""+ SELECT COUNT(*) AS total_count+ FROM (+ SELECT 1+ FROM "LiteLLM_SpendLogs"+ WHERE {" AND ".join(sql_conditions)}+ LIMIT ${p}+ ) AS bounded_matches+ """+ count_rows = await prisma_client.db.query_raw(count_query, *sql_params, SPEND_LOGS_PAGINATION_COUNT_CAP + 1)+ raw_total = int(count_rows[0]["total_count"]) if count_rows else 0+ total_is_capped = raw_total > SPEND_LOGS_PAGINATION_COUNT_CAP+ total_records = SPEND_LOGS_PAGINATION_COUNT_CAP if total_is_capped else raw_total+sql_query = f"""SELECTrequest_id, call_type, api_key, spend, total_tokens,@@ -1967,8 +1983,7 @@ async def ui_view_spend_logs(cache_hit, cache_key, request_tags, team_id,organization_id, end_user, requester_ip_address,session_id, status, mcp_namespaced_tool_name, agent_id,- COALESCE(request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER) AS request_duration_ms,- COUNT(*) OVER () AS total_count+ COALESCE(request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER) AS request_duration_msFROM "LiteLLM_SpendLogs"WHERE {" AND ".join(sql_conditions)}ORDER BY {_order_expr} {_sql_dir}{_nulls_clause}@@ -1978,34 +1993,13 @@ async def ui_view_spend_logs(data = await prisma_client.db.query_raw(sql_query, *sql_params)- # `COUNT(*) OVER ()` folds the total-match count into the same scan as the- # page data; a standalone `COUNT(*)` is a distributed RPC on sharded- # engines like YugabyteDB that contacts every tablet and times out- # regardless of row count (LIT-4027). The hot path (page 1 and in-range- # pages) always carries the count on its rows, so the count round trip is- # gone there. Only an out-of-range page overshoots the last row and comes- # back empty; fall back to a direct count there so total/total_pages stay- # accurate rather than collapsing to zero.- if data:- total_records = int(data[0]["total_count"])- elif page > 1:- total_records = int(- await SpendLogsRepository(prisma_client).table.count(- where=where_conditions,- )- )- else:- total_records = 0-# query_raw returns the JSONB `metadata` column as a string (the Prisma# serialiser bypasses the model-layer JSON hydration we get on the ORM# path). The UI reads `metadata.status` / `metadata.error_information`# as object fields, so failure rows looked like successes (#29674).- # Re-hydrate to dict here. Also drop the window-function `total_count`- # helper column so it does not leak into the serialised rows.+ # Re-hydrate to dict here.for row in data:if isinstance(row, dict):- row.pop("total_count", None)md = row.get("metadata")if isinstance(md, str):try:@@ -2026,6 +2020,7 @@ async def ui_view_spend_logs(page_size,total_pages,enrich_session_counts=not is_v2,+ total_is_capped=total_is_capped,)except Exception as e:verbose_proxy_logger.exception(f"Error in ui_view_spend_logs: {e}")@@ -3334,6 +3329,7 @@ async def _build_ui_spend_logs_response(page_size: int,total_pages: int,enrich_session_counts: bool = True,+ total_is_capped: bool = False,) -> dict:"""Build the paginated response for the UI spend-logs endpoint.@@ -3358,10 +3354,12 @@ async def _build_ui_spend_logs_response(total_pages: Total number of pages.enrich_session_counts: Whether to add ``session_total_count`` to eachrow. Defaults to ``True``.+ total_is_capped: Whether ``total_records`` was clamped to the+ pagination count cap (there are more matching rows than the cap).Returns:A dict with ``data`` (enriched rows), ``total``, ``page``,- ``page_size``, and ``total_pages``.+ ``page_size``, ``total_pages``, and ``total_is_capped``."""count_map: dict[str, int] = {}if enrich_session_counts:@@ -3451,6 +3449,7 @@ async def _build_ui_spend_logs_response("page": page,"page_size": page_size,"total_pages": total_pages,+ "total_is_capped": total_is_capped,}diff --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 4acc94c737a..1e9818534c9 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@@ -66,13 +66,14 @@ def _reconstruct_ui_where_from_sql(sql_query, params):Rebuild the Prisma-style ``where`` dict the filter_fns below expect from theraw SQL + params the endpoint emits.- ``ui_view_spend_logs`` folds the total into the page query via- ``COUNT(*) OVER ()`` and no longer issues a separate ``count(where=...)``- call, so the mock derives the active filter from the one query it sees- instead of from the (now absent) count call.+ ``ui_view_spend_logs`` computes the total with a bounded+ ``SELECT COUNT(*) FROM (SELECT 1 ... LIMIT $cap+1)`` query and fetches the+ page with a separate ``ORDER BY ... LIMIT/OFFSET`` query. Both carry the+ same WHERE clause, so the terminator can be ``ORDER BY`` (page query) or+ ``LIMIT`` (bounded count query)."""where: dict = {}- clause = re.search(r"WHERE (.*) ORDER BY", sql_query, re.DOTALL)+ clause = re.search(r"WHERE (.*?)\s+(?:ORDER BY|LIMIT)", sql_query, re.DOTALL)if clause is None:return where@@ -163,13 +164,13 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=Noasync def query_raw(self, sql_query, *params):filtered = filter_fn(_reconstruct_ui_where_from_sql(sql_query, params))+ total = len(filtered)+ if "COUNT(*)" in sql_query:+ cap_plus_one = params[-1]+ return [{"total_count": min(total, cap_plus_one)}]page_size = params[-2] if len(params) >= 2 else 50skip = params[-1] if len(params) >= 1 else 0- total = len(filtered)- return [- {**row, "total_count": total}- for row in filtered[skip : skip + page_size]- ]+ return [row for row in filtered[skip : skip + page_size]]class MockPrismaClient:def __init__(self):@@ -684,6 +685,8 @@ async def test_ui_view_spend_logs_sort_by_and_sort_order(return len(base_logs)async def mock_query_raw(sql_query, *params):+ if "COUNT(*)" in sql_query:+ return [{"total_count": len(base_logs)}]# Endpoint uses raw SQL with ORDER BY startTime DESC; mock returns sorted dataorder = ({"startTime": "desc"}@@ -693,10 +696,7 @@ async def test_ui_view_spend_logs_sort_by_and_sort_order(sorted_logs = _sort_logs(base_logs, order)page_size = params[-2] if len(params) >= 2 else 50skip = params[-1] if len(params) >= 1 else 0- return [- {**row, "total_count": len(base_logs)}- for row in sorted_logs[skip : skip + page_size]- ]+ return [row for row in sorted_logs[skip : skip + page_size]]class MockPrismaClient:def __init__(self):@@ -830,16 +830,15 @@ async def test_ui_view_spend_logs_sort_by_request_duration_ms(client, monkeypatcreturn len(base_logs)async def mock_query_raw(sql_query, *params):+ if "COUNT(*)" in sql_query:+ return [{"total_count": len(base_logs)}]reverse = "DESC" in sql_querysorted_logs = sorted(base_logs, key=lambda x: x.get("request_duration_ms", 0), reverse=reverse)page_size = params[-2] if len(params) >= 2 else 50skip = params[-1] if len(params) >= 1 else 0- return [- {**row, "total_count": len(base_logs)}- for row in sorted_logs[skip : skip + page_size]- ]+ return [row for row in sorted_logs[skip : skip + page_size]]class MockPrismaClient:def __init__(self):@@ -926,6 +925,8 @@ async def test_ui_view_spend_logs_sort_by_model(return len(base_logs)async def mock_query_raw(sql_query, *params):+ if "COUNT(*)" in sql_query:+ return [{"total_count": len(base_logs)}]assert "model" in sql_query# model is non-nullable in the schema, so NULLS LAST should NOT be# appended — only ttft_ms gets that clause. This guards against@@ -937,10 +938,7 @@ async def test_ui_view_spend_logs_sort_by_model()page_size = params[-2] if len(params) >= 2 else 50skip = params[-1] if len(params) >= 1 else 0- return [- {**row, "total_count": len(base_logs)}- for row in sorted_logs[skip : skip + page_size]- ]+ return [row for row in sorted_logs[skip : skip + page_size]]class MockPrismaClient:def __init__(self):@@ -1040,6 +1038,8 @@ async def test_ui_view_spend_logs_sort_by_ttft_ms(client, monkeypatch):return len(base_logs)async def mock_query_raw(sql_query, *params):+ if "COUNT(*)" in sql_query:+ return [{"total_count": len(base_logs)}]# Endpoint must compute TTFT inline and use NULLS LAST.assert "completionStartTime" in sql_queryassert "NULLS LAST" in sql_query@@ -1051,10 +1051,7 @@ async def test_ui_view_spend_logs_sort_by_ttft_ms(client, monkeypatch):page_size = params[-2] if len(params) >= 2 else 50skip = params[-1] if len(params) >= 1 else 0return [- {- **{k: v for k, v in row.items() if k != "_ttft_ms"},- "total_count": len(base_logs),- }+ {k: v for k, v in row.items() if k != "_ttft_ms"}for row in sorted_logs[skip : skip + page_size]]diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_query_optimization.py b/tests/test_litellm/proxy/spend_tracking/test_spend_query_optimization.pyindex e8950e84f55..19083486974 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_query_optimization.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_query_optimization.py@@ -203,31 +203,42 @@ async def test_spend_logs_ui_wraps_params_in_at_time_zone_utc(monkeypatch):)+def _make_ui_spend_logs_mock(count_total, page_rows):+ """+ Build a prisma mock whose first `query_raw` (the bounded count) returns+ `count_total` and whose second `query_raw` (the page data) returns+ `page_rows`.+ """+ mock_prisma = MagicMock()+ mock_prisma.db = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ side_effect=[[{"total_count": count_total}], page_rows]+ )+ mock_prisma.db.litellm_spendlogs = MagicMock()+ mock_prisma.db.litellm_spendlogs.count = AsyncMock(return_value=0)+ return mock_prisma++@pytest.mark.asyncio-async def test_spend_logs_ui_folds_count_into_window_function(monkeypatch):+async def test_spend_logs_ui_uses_bounded_count_not_full_scan(monkeypatch):"""- /spend/logs/ui must not issue a separate `COUNT(*)` round trip to compute- the total. On sharded engines like YugabyteDB a standalone `COUNT(*)` is a- distributed RPC that contacts every tablet and times out regardless of row- count, so the logs tab 500s (LIT-4027). The total is folded into the page- query via `COUNT(*) OVER ()` and read off the returned rows instead.+ /spend/logs/ui must compute its pagination total with a bounded+ `SELECT COUNT(*) FROM (SELECT 1 ... LIMIT $cap+1)` so it never scans the+ whole time window of a huge LiteLLM_SpendLogs table (Aurora ACU spike,+ LIT-4119). It must also avoid the unbounded prisma `.count()` /+ `COUNT(*) OVER ()` full-window count that reads every matching row."""from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.spend_tracking.spend_management_endpoints import (+ SPEND_LOGS_PAGINATION_COUNT_CAP,ui_view_spend_logs,)- rows = [- {"request_id": "req-1", "metadata": "{}", "session_id": None, "total_count": 137},- {"request_id": "req-2", "metadata": "{}", "session_id": None, "total_count": 137},+ page_rows = [+ {"request_id": "req-1", "metadata": "{}", "session_id": None},+ {"request_id": "req-2", "metadata": "{}", "session_id": None},]-- mock_prisma = MagicMock()- mock_prisma.db = MagicMock()- mock_prisma.db.query_raw = AsyncMock(return_value=rows)- mock_prisma.db.litellm_spendlogs = MagicMock()- mock_prisma.db.litellm_spendlogs.count = AsyncMock(return_value=0)-+ mock_prisma = _make_ui_spend_logs_mock(count_total=137, page_rows=page_rows)monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)auth = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")@@ -250,33 +261,90 @@ async def test_spend_logs_ui_folds_count_into_window_function(monkeypatch):mock_prisma.db.litellm_spendlogs.count.assert_not_called()- sql = mock_prisma.db.query_raw.call_args[0][0]- assert "COUNT(*) OVER ()" in sql, (- "the page query must carry a window-function count so a separate "- f"distributed COUNT(*) is avoided. SQL was:\n{sql}"+ count_call = mock_prisma.db.query_raw.call_args_list[0]+ count_sql = count_call[0][0]+ assert "COUNT(*) OVER ()" not in count_sql+ assert "LIMIT" in count_sql and "FROM (" in count_sql, (+ "the total must come from a bounded subquery count, not a full-window "+ f"scan. SQL was:\n{count_sql}"+ )+ assert count_call[0][-1] == SPEND_LOGS_PAGINATION_COUNT_CAP + 1, (+ "the bounded count must probe at most cap+1 rows"+ )++ page_sql = mock_prisma.db.query_raw.call_args_list[1][0][0]+ assert "COUNT(*) OVER ()" not in page_sql, (+ "the page query must not carry a window count that forces a full-window "+ f"scan. SQL was:\n{page_sql}")assert response["total"] == 137+ assert response["total_is_capped"] is Falseassert response["total_pages"] == (137 + 50 - 1) // 50for row in response["data"]:assert "total_count" not in row, "the window-function helper column must be stripped before serialising rows"+async def test_spend_logs_ui_caps_total_for_large_result_sets(monkeypatch):+ """+ When more than the cap match, /spend/logs/ui reports the cap and flags+ `total_is_capped` so the UI can render `<cap>+` instead of an exact total+ that would require scanning the whole window (LIT-4119).+ """+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ SPEND_LOGS_PAGINATION_COUNT_CAP,+ ui_view_spend_logs,+ )++ page_rows = [{"request_id": "req-1", "metadata": "{}", "session_id": None}]+ mock_prisma = _make_ui_spend_logs_mock(+ count_total=SPEND_LOGS_PAGINATION_COUNT_CAP + 1, page_rows=page_rows+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")+ mock_request = MagicMock()+ mock_request.url.path = "/spend/logs/ui"++ response = await ui_view_spend_logs(+ request=mock_request,+ api_key=None,+ user_id=None,+ request_id=None,+ start_date="2026-02-16 00:00:00",+ end_date="2026-02-16 23:59:59",+ page=1,+ page_size=50,+ sort_by="startTime",+ sort_order="desc",+ user_api_key_dict=auth,+ )++ assert response["total"] == SPEND_LOGS_PAGINATION_COUNT_CAP+ assert response["total_is_capped"] is True+ assert response["total_pages"] == (SPEND_LOGS_PAGINATION_COUNT_CAP + 50 - 1) // 50++@pytest.mark.asyncioasync def test_spend_logs_ui_empty_page_reports_zero_total(monkeypatch):"""- When a page matches no rows the window-function count row is absent, so the- total must fall back to zero without issuing a separate `COUNT(*)`.+ When nothing matches, the bounded count query returns a single row with a+ zero count (real `COUNT(*)` always returns one row) and the page query+ returns no rows, so the total is zero without an unbounded prisma `.count()`."""from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.spend_tracking.spend_management_endpoints import (ui_view_spend_logs,)+ # First query_raw call is the bounded count (0 matches), second is the empty+ # page.mock_prisma = MagicMock()mock_prisma.db = MagicMock()- mock_prisma.db.query_raw = AsyncMock(return_value=[])+ mock_prisma.db.query_raw = AsyncMock(side_effect=[[{"total_count": 0}], []])mock_prisma.db.litellm_spendlogs = MagicMock()mock_prisma.db.litellm_spendlogs.count = AsyncMock(return_value=0)@@ -307,24 +375,25 @@ async def test_spend_logs_ui_empty_page_reports_zero_total(monkeypatch):@pytest.mark.asyncio-async def test_spend_logs_ui_out_of_range_page_falls_back_to_count(monkeypatch):+async def test_spend_logs_ui_out_of_range_page_keeps_total(monkeypatch):"""- An out-of-range page (offset past the last matching row) returns no rows, so- the window-function count is unavailable. The total must not collapse to zero- there; it falls back to a direct count so total/total_pages stay accurate.- This fallback only fires off the hot path (page > 1 with an empty result), so- the YugabyteDB timeout the fix removes from page 1 stays removed.+ An out-of-range page (offset past the last matching row) returns no rows,+ but the bounded count query runs independently of the page query, so the+ total must not collapse to zero and no unbounded prisma `.count()` is+ needed. total/total_pages stay accurate off the hot path too."""from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.spend_tracking.spend_management_endpoints import (ui_view_spend_logs,)+ # First query_raw call is the bounded count (7 matches), second is the+ # out-of-range page (empty).mock_prisma = MagicMock()mock_prisma.db = MagicMock()- mock_prisma.db.query_raw = AsyncMock(return_value=[])+ mock_prisma.db.query_raw = AsyncMock(side_effect=[[{"total_count": 7}], []])mock_prisma.db.litellm_spendlogs = MagicMock()- mock_prisma.db.litellm_spendlogs.count = AsyncMock(return_value=7)+ mock_prisma.db.litellm_spendlogs.count = AsyncMock(return_value=0)monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)@@ -346,9 +415,10 @@ async def test_spend_logs_ui_out_of_range_page_falls_back_to_count(monkeypatch):user_api_key_dict=auth,)- mock_prisma.db.litellm_spendlogs.count.assert_called_once()+ mock_prisma.db.litellm_spendlogs.count.assert_not_called()assert response["total"] == 7assert response["total_pages"] == (7 + 2 - 1) // 2+ assert response["data"] == []@pytest.mark.asynciodiff --git a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsxindex b20281ed0da..f65ff2cc6ca 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx@@ -193,15 +193,24 @@ export function LogsTableToolbar({</div><div className="flex items-center space-x-4">- <span className="text-sm text-gray-700 whitespace-nowrap">+ <span+ className="text-sm text-gray-700 whitespace-nowrap"+ title={+ !isLoading && filteredLogs?.total_is_capped+ ? `Showing the first ${filteredLogs.total.toLocaleString()} results. Narrow the date range or add filters to see more.`+ : undefined+ }+ >Showing {isLoading ? "..." : filteredLogs ? (currentPage - 1) * pageSize + 1 : 0} -{" "}{isLoading ? "..." : filteredLogs ? Math.min(currentPage * pageSize, filteredLogs.total) : 0} of{" "}- {isLoading ? "..." : filteredLogs ? filteredLogs.total : 0} results+ {isLoading ? "..." : filteredLogs ? filteredLogs.total : 0}+ {!isLoading && filteredLogs?.total_is_capped ? "+" : ""} results</span><div className="flex items-center space-x-2"><span className="text-sm text-gray-700 min-w-[90px]">Page {isLoading ? "..." : currentPage} of{" "}{isLoading ? "..." : filteredLogs ? filteredLogs.total_pages : 1}+ {!isLoading && filteredLogs?.total_is_capped ? "+" : ""}</span><buttononClick={() => onCurrentPageChange((p: number) => Math.max(1, p - 1))}diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsxindex d9830a83f6e..c45e03905d0 100644--- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx@@ -13,6 +13,7 @@ export interface PaginatedResponse {page: number;page_size: number;total_pages: number;+ total_is_capped?: boolean;}function useDebouncedValue<T>(value: T, delayMs: number): [T, React.Dispatch<React.SetStateAction<T>>] {