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(ui): keyset-paginate request logs by session trace (#38794)
devin-ai-integration[bot]29c37141c30a
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex dcc798b81cb..295faaa980a 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -4,6 +4,7 @@ import jsonimport osfrom collections.abc import Mapping, Sequencefrom datetime import datetime, timedelta, timezone+from types import MappingProxyTypefrom typing import (TYPE_CHECKING,Annotated,@@ -57,9 +58,21 @@ router: Final = APIRouter()SPEND_LOGS_PAGINATION_COUNT_CAP: Final = 10000-_SESSION_GROUP_KEY_SQL: Final = "COALESCE(NULLIF(session_id, ''), request_id), api_key"+_SESSION_KEY_EXPR: Final = "COALESCE(NULLIF(session_id, ''), request_id)"+_SESSION_GROUP_KEY_SQL: Final = f"{_SESSION_KEY_EXPR}, api_key"_MCP_CALL_TYPES_SQL: Final = "('call_mcp_tool', 'list_mcp_tools')"_AGENT_CALL_TYPE_SQL: Final = "'asend_message'"+_SPEND_LOG_LIST_COLUMNS: Final = """+ request_id, call_type, api_key, spend, total_tokens,+ prompt_tokens, completion_tokens, "startTime", "endTime",+ "completionStartTime", model, model_id, model_group,+ custom_llm_provider, api_base, "user", metadata,+ 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+"""_INTERNAL_HEALTH_CHECK_API_KEYS: Final = (LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,@@ -2303,6 +2316,13 @@ async def ui_view_spend_logs(default=False,description="Paginate over sessions instead of raw logs: one representative row per session, total counts sessions",),+ session_cursor: str | None = fastapi.Query(+ default=None,+ description=(+ "Keyset cursor '<last_activity>|<api_key>|<session_key>' from a previous group_by_session page. "+ "UI route only, honored when sorting by startTime"+ ),+ ),):"""View spend logs with pagination support.@@ -2636,6 +2656,18 @@ async def ui_view_spend_logs(sql_params.append(f"%{error_message}%")p += 1+ if group_by_session is True and not is_v2 and not is_request_id_lookup and sort_by == "startTime":+ return await _ui_session_grouped_spend_logs(+ prisma_client=prisma_client,+ sql_conditions=sql_conditions,+ sql_params=sql_params,+ next_param_index=p,+ page=page,+ page_size=page_size,+ sort_desc=order_direction != "asc",+ session_cursor=session_cursor,+ )+# Build the ORDER BY expression. ttft_ms is computed from# completionStartTime - startTime; non-streaming rows (where# completionStartTime is null or equals endTime) yield NULL, so we@@ -2677,19 +2709,11 @@ async def ui_view_spend_logs(total_is_capped: Final = raw_total > SPEND_LOGS_PAGINATION_COUNT_CAPtotal_records: Final = SPEND_LOGS_PAGINATION_COUNT_CAP if total_is_capped else raw_total- select_columns: Final = """request_id, call_type, api_key, spend, total_tokens,- prompt_tokens, completion_tokens, "startTime", "endTime",- "completionStartTime", model, model_id, model_group,- custom_llm_provider, api_base, "user", metadata,- 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"""sql_query: Final = (f"""SELECT * FROM (SELECT DISTINCT ON ({_SESSION_GROUP_KEY_SQL})- {select_columns}+ {_SPEND_LOG_LIST_COLUMNS}FROM "LiteLLM_SpendLogs"WHERE {joined_conditions}ORDER BY {_SESSION_GROUP_KEY_SQL}, call_type IN {_MCP_CALL_TYPES_SQL}, "startTime" DESC@@ -2700,7 +2724,7 @@ async def ui_view_spend_logs(if session_groupingelse f"""SELECT- {select_columns}+ {_SPEND_LOG_LIST_COLUMNS}FROM "LiteLLM_SpendLogs"WHERE {joined_conditions}ORDER BY {_order_expr} {_sql_dir}{_nulls_clause}@@ -2733,6 +2757,162 @@ async def ui_view_spend_logs(raise handle_exception_on_proxy(e)+class _SessionPageRow(TypedDict):+ session_key: ReadOnly[str]+ api_key: ReadOnly[str]+ last_activity: ReadOnly[str]+++def _parse_session_cursor(session_cursor: str | None) -> tuple[str, str, str] | None:+ if session_cursor is None or session_cursor.count("|") < 2:+ return None+ last_activity, _, rest = session_cursor.partition("|")+ api_key, _, session_key = rest.partition("|")+ if not last_activity or not session_key:+ return None+ return (last_activity, session_key, api_key)+++async def _fetch_session_representatives(+ prisma_client: "PrismaClient",+ where_clause: str,+ sql_params: Sequence[object],+ next_param_index: int,+ session_keys: Sequence[tuple[str, str]],+) -> list[dict[str, object]]: # mutable-ok: _build_ui_spend_logs_response writes session counts onto each row+ """Fetch the newest non-MCP row of each ``(session_key, api_key)`` session, in ``session_keys`` order."""+ rep_query: Final = f"""+ SELECT * FROM (+ SELECT DISTINCT ON ({_SESSION_GROUP_KEY_SQL})+ {_SPEND_LOG_LIST_COLUMNS}+ FROM "LiteLLM_SpendLogs"+ WHERE {where_clause}+ AND ({_SESSION_GROUP_KEY_SQL}) IN (+ SELECT * FROM unnest(${next_param_index}::text[], ${next_param_index + 1}::text[])+ )+ ORDER BY {_SESSION_GROUP_KEY_SQL}, call_type IN {_MCP_CALL_TYPES_SQL}, "startTime" DESC+ ) AS session_representatives+ """+ rep_rows: Final[Sequence[dict[str, object]]] = await _query_raw( # mutable-ok: rows are enriched in place+ prisma_client,+ rep_query,+ *sql_params,+ [session_key for session_key, _ in session_keys], # mutable-ok: prisma serializes array params from a list+ [api_key for _, api_key in session_keys], # mutable-ok: prisma serializes array params from a list+ )+ rep_by_key: Final[Mapping[tuple[str, str], dict[str, object]]] = MappingProxyType( # mutable-ok: same rows+ {(str(row["session_id"] or row["request_id"]), str(row["api_key"])): row for row in rep_rows}+ )+ return [rep_by_key[key] for key in session_keys if key in rep_by_key] # mutable-ok: rows are enriched in place+++async def _ui_session_grouped_spend_logs(+ prisma_client: "PrismaClient",+ sql_conditions: Sequence[str],+ sql_params: Sequence[object],+ next_param_index: int,+ page: int,+ page_size: int,+ sort_desc: bool,+ session_cursor: str | None,+) -> Mapping[str, object]:+ """+ One row per session, keyset-paginated by session last activity.++ Sessions are derived on the fly from ``LiteLLM_SpendLogs`` (no extra+ table): rows sharing a ``session_id`` and ``api_key`` form a session, rows+ without a session id are singletons keyed by ``request_id``. A page is the+ next ``page_size`` sessions ordered by ``(MAX(startTime), session_key,+ api_key)``, resumed from the ``session_cursor`` keyset+ ``'<last_activity>|<api_key>|<session_key>'`` instead of an OFFSET, so+ page depth does not degrade the query plan. Each session is represented+ by its newest non-MCP row, enriched by ``_build_ui_spend_logs_response``+ exactly like the flat listing, and the response carries+ ``next_session_cursor`` / ``has_more`` while ``total`` counts sessions+ (capped like the flat total).+ """+ where_clause: Final = " AND ".join(sql_conditions) if sql_conditions else "TRUE"+ cmp_op: Final = "<" if sort_desc else ">"+ direction: Final = "DESC" if sort_desc else "ASC"++ cursor: Final = _parse_session_cursor(session_cursor)+ having_clause: Final = (+ f'HAVING (MAX("startTime"), {_SESSION_GROUP_KEY_SQL}) {cmp_op} '+ f"(${next_param_index}::timestamp, ${next_param_index + 1}, ${next_param_index + 2})"+ if cursor+ else ""+ )+ cursor_params: Final[tuple[object, ...]] = cursor if cursor else ()+ limit_index: Final = next_param_index + len(cursor_params)++ page_query: Final = f"""+ SELECT {_SESSION_KEY_EXPR} AS session_key,+ api_key,+ MAX("startTime")::text AS last_activity+ FROM "LiteLLM_SpendLogs"+ WHERE {where_clause}+ GROUP BY {_SESSION_GROUP_KEY_SQL}+ {having_clause}+ ORDER BY MAX("startTime") {direction}, {_SESSION_KEY_EXPR} {direction}, api_key {direction}+ LIMIT ${limit_index}+ """+ page_rows: Final[Sequence[_SessionPageRow]] = await _query_raw(+ prisma_client, page_query, *sql_params, *cursor_params, page_size + 1+ )++ has_more: Final = len(page_rows) > page_size+ visible_rows: Final = page_rows[:page_size]+ next_cursor: Final = (+ f"{visible_rows[-1]['last_activity']}|{visible_rows[-1]['api_key']}|{visible_rows[-1]['session_key']}"+ if has_more and visible_rows+ else None+ )++ count_query: Final = f"""+ SELECT COUNT(*) AS total_count+ FROM (+ SELECT 1+ FROM "LiteLLM_SpendLogs"+ WHERE {where_clause}+ GROUP BY {_SESSION_GROUP_KEY_SQL}+ LIMIT ${next_param_index}+ ) AS bounded_sessions+ """+ count_rows: Final[Sequence[_SpendLogsCountRow]] = await _query_raw(+ prisma_client, count_query, *sql_params, SPEND_LOGS_PAGINATION_COUNT_CAP + 1+ )+ raw_total: Final = int(count_rows[0]["total_count"]) if count_rows else 0+ total_is_capped: Final = raw_total > SPEND_LOGS_PAGINATION_COUNT_CAP+ total_records: Final = SPEND_LOGS_PAGINATION_COUNT_CAP if total_is_capped else raw_total++ session_keys: Final = tuple((row["session_key"], row["api_key"]) for row in visible_rows)+ data: Final[list[dict[str, object]]] = ( # mutable-ok: _build_ui_spend_logs_response writes onto each row+ await _fetch_session_representatives(+ prisma_client=prisma_client,+ where_clause=where_clause,+ sql_params=sql_params,+ next_param_index=next_param_index,+ session_keys=session_keys,+ )+ if session_keys+ else [] # mutable-ok: downstream enrichment mutates rows in place+ )+ _hydrate_spend_log_metadata(data)++ total_pages: Final = (total_records + page_size - 1) // page_size+ response: Final[Mapping[str, object]] = await _build_ui_spend_logs_response(+ prisma_client,+ data,+ total_records,+ page,+ page_size,+ total_pages,+ enrich_session_counts=True,+ total_is_capped=total_is_capped,+ )+ return {**response, "next_session_cursor": next_cursor, "has_more": has_more} # mutable-ok: FastAPI response body++class RequestResponsePayload(NamedTuple):messages: str | list | dict | Noneresponse: str | list | dict | None@@ -4102,7 +4282,7 @@ async def _build_ui_spend_logs_response(total_pages: int,enrich_session_counts: bool = True,total_is_capped: bool = False,-) -> dict:+) -> dict[str, object]:"""Build the paginated response for the UI spend-logs endpoint.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 c8b35e8a841..60a32102946 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@@ -6031,3 +6031,238 @@ def test_scoped_spend_report_range_at_max_allowed(client, monkeypatch):mock_prisma.db.query_raw.assert_awaited_once()finally:app.dependency_overrides.pop(ps.user_api_key_auth, None)+++def test_parse_session_cursor():+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _parse_session_cursor,+ )++ assert _parse_session_cursor(None) is None+ assert _parse_session_cursor("no-delimiter") is None+ assert _parse_session_cursor("2026-08-29 10:00:00|sess-1") is None+ assert _parse_session_cursor("|hashed-key|sess-1") is None+ assert _parse_session_cursor("2026-08-29 10:00:00|hashed-key|") is None+ assert _parse_session_cursor("2026-08-29 10:00:00|hashed-key|sess-1") == (+ "2026-08-29 10:00:00",+ "sess-1",+ "hashed-key",+ )+ assert _parse_session_cursor("2026-08-29 10:00:00.123|hashed-key|sess|with|pipes") == (+ "2026-08-29 10:00:00.123",+ "sess|with|pipes",+ "hashed-key",+ )+++SESSION_GROUP_KEY_SQL = "COALESCE(NULLIF(session_id, ''), request_id), api_key"+++def _session_grouped_mock_prisma(session_page_rows, session_total, representative_rows):+ """Mock prisma dispatching the raw queries the keyset grouped path emits."""++ async def mock_query_raw(sql_query, *params):+ if "COUNT(*) AS total_count" in sql_query:+ return [{"total_count": session_total}]+ if "DISTINCT ON" in sql_query:+ return representative_rows+ if "COALESCE(SUM(spend)" in sql_query:+ return [+ {+ "session_id": "sess-1",+ "api_key": "hashed-key",+ "session_total_count": 3,+ "session_total_spend": 0.03,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 0,+ "session_llm_count": 3,+ "session_agent_count": 0,+ "session_models": ["gpt-4o"],+ }+ ]+ return session_page_rows++ mock_prisma = MagicMock()+ mock_prisma.db = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)+ return mock_prisma+++def _session_representative_row(request_id, session_id):+ return {+ "request_id": request_id,+ "call_type": "acompletion",+ "api_key": "hashed-key",+ "spend": 0.01,+ "total_tokens": 10,+ "prompt_tokens": 5,+ "completion_tokens": 5,+ "startTime": "2026-08-29T10:00:00Z",+ "endTime": "2026-08-29T10:00:01Z",+ "model": "gpt-4o",+ "metadata": {},+ "session_id": session_id,+ }+++def _session_page_row(session_key, last_activity):+ return {"session_key": session_key, "api_key": "hashed-key", "last_activity": last_activity}+++async def test_ui_view_spend_logs_group_by_session_first_page(client, monkeypatch):+ """One row per (session, api_key), session-count total, and a keyset cursor for the next page."""+ page_rows = [+ _session_page_row("sess-1", "2026-08-29 10:00:00"),+ _session_page_row("req-solo", "2026-08-29 09:00:00"),+ _session_page_row("sess-extra", "2026-08-29 08:00:00"),+ ]+ reps = [+ _session_representative_row("req-solo", None),+ _session_representative_row("req-1", "sess-1"),+ ]+ mock_prisma = _session_grouped_mock_prisma(page_rows, 3, reps)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)+ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",+ lambda user_api_key_dict: True,+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )+ try:+ start_date, end_date = _default_date_range()+ response = client.get(+ "/spend/logs/ui",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "group_by_session": "true",+ "page_size": 2,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["total"] == 3+ assert data["has_more"] is True+ assert data["next_session_cursor"] == "2026-08-29 09:00:00|hashed-key|req-solo"+ request_ids = [row["request_id"] for row in data["data"]]+ assert request_ids == ["req-1", "req-solo"], "representatives must follow the page order"+ assert data["data"][0]["session_total_count"] == 3+ assert data["data"][1]["session_total_count"] == 1++ emitted = [call.args for call in mock_prisma.db.query_raw.await_args_list]+ page_query_sql = emitted[0][0]+ assert f"GROUP BY {SESSION_GROUP_KEY_SQL}" in page_query_sql+ assert "OFFSET" not in page_query_sql+ assert "HAVING" not in page_query_sql+ assert emitted[0][-1] == 3, "page query fetches page_size + 1 sessions to detect has_more"++ count_sql = emitted[1][0]+ assert f"GROUP BY {SESSION_GROUP_KEY_SQL}" in count_sql+ assert "LIMIT" in count_sql and "FROM (" in count_sql, "the grouped count must stay bounded"++ rep_call = emitted[2]+ assert f"DISTINCT ON ({SESSION_GROUP_KEY_SQL})" in rep_call[0]+ assert (+ f"ORDER BY {SESSION_GROUP_KEY_SQL}, call_type IN ('call_mcp_tool', 'list_mcp_tools'), \"startTime\" DESC"+ in rep_call[0]+ ), "the session representative must prefer the newest non-MCP call"+ assert rep_call[-2] == ["sess-1", "req-solo"]+ assert rep_call[-1] == ["hashed-key", "hashed-key"]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++async def test_ui_view_spend_logs_group_by_session_cursor_page(client, monkeypatch):+ """A session_cursor becomes a HAVING keyset predicate instead of an OFFSET."""+ page_rows = [_session_page_row("sess-2", "2026-08-29 07:00:00")]+ reps = [_session_representative_row("req-2", "sess-2")]+ mock_prisma = _session_grouped_mock_prisma(page_rows, 3, reps)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)+ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",+ lambda user_api_key_dict: True,+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )+ try:+ start_date, end_date = _default_date_range()+ response = client.get(+ "/spend/logs/ui",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "group_by_session": "true",+ "session_cursor": "2026-08-29 09:00:00|hashed-key|req-solo",+ "page_size": 2,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["has_more"] is False+ assert data["next_session_cursor"] is None+ assert [row["request_id"] for row in data["data"]] == ["req-2"]++ page_query_call = mock_prisma.db.query_raw.await_args_list[0]+ page_query_sql = page_query_call.args[0]+ assert f'HAVING (MAX("startTime"), {SESSION_GROUP_KEY_SQL}) <' in page_query_sql+ assert "OFFSET" not in page_query_sql+ cursor_index = page_query_call.args.index("2026-08-29 09:00:00")+ assert page_query_call.args[cursor_index : cursor_index + 3] == (+ "2026-08-29 09:00:00",+ "req-solo",+ "hashed-key",+ ), "cursor params must line up with (MAX(startTime), session key, api_key)"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++async def test_ui_view_spend_logs_group_by_session_offset_for_non_starttime_sort(+ client, monkeypatch+):+ """Sorting by another column keeps session grouping but pages with OFFSET, without a keyset cursor."""+ mock_prisma = _session_grouped_mock_prisma([], 0, [])++ async def mock_query_raw(sql_query, *params):+ if "COUNT(*)" in sql_query:+ return [{"total_count": 0}]+ return []++ mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)+ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",+ lambda user_api_key_dict: True,+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )+ try:+ start_date, end_date = _default_date_range()+ response = client.get(+ "/spend/logs/ui",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "group_by_session": "true",+ "session_cursor": "2026-08-29 09:00:00|hashed-key|req-solo",+ "sort_by": "spend",+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert "next_session_cursor" not in data+ emitted_sql = [call.args[0] for call in mock_prisma.db.query_raw.await_args_list]+ assert "HAVING" not in " ".join(emitted_sql)+ assert f"DISTINCT ON ({SESSION_GROUP_KEY_SQL})" in emitted_sql[1]+ assert "OFFSET" in emitted_sql[1]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)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 27e633099f0..9ae932ff01f 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@@ -508,11 +508,12 @@ async def test_global_spend_report_team_group_forwards_team_id(monkeypatch):async def test_spend_logs_ui_group_by_session_paginates_sessions(monkeypatch):"""With group_by_session=true, /spend/logs/ui must page and count SESSIONS,- not raw calls: the page query returns one representative row per session- (DISTINCT ON the session group key, preferring non-MCP calls, newest- first) and the bounded count counts groups. Otherwise the UI collapses a- server page of N calls into fewer visible rows while the footer still- claims N (issue #38060).+ not raw calls: the page is one representative row per session (DISTINCT+ ON the session group key, preferring non-MCP calls, newest first), the+ bounded count counts groups, and on the default startTime sort the page is+ selected by keyset (no OFFSET) so deep pages do not degrade. Otherwise the+ UI collapses a server page of N calls into fewer visible rows while the+ footer still claims N (issue #38060)."""from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.spend_tracking.spend_management_endpoints import (@@ -520,11 +521,26 @@ async def test_spend_logs_ui_group_by_session_paginates_sessions(monkeypatch):ui_view_spend_logs,)- page_rows = [- {"request_id": "req-1", "metadata": "{}", "session_id": None},- {"request_id": "req-2", "metadata": "{}", "session_id": None},+ group_key = "COALESCE(NULLIF(session_id, ''), request_id), api_key"+ session_rows = [+ {"session_key": "req-1", "api_key": "k", "last_activity": "2026-02-16 10:00:00"},+ {"session_key": "req-2", "api_key": "k", "last_activity": "2026-02-16 09:00:00"},]- mock_prisma = _make_ui_spend_logs_mock(count_total=12, page_rows=page_rows)+ representative_rows = [+ {"request_id": "req-1", "api_key": "k", "metadata": "{}", "session_id": None},+ {"request_id": "req-2", "api_key": "k", "metadata": "{}", "session_id": None},+ ]++ async def mock_query_raw(sql_query, *params):+ if "COUNT(*) AS total_count" in sql_query:+ return [{"total_count": 12}]+ if "DISTINCT ON" in sql_query:+ return representative_rows+ return session_rows++ mock_prisma = MagicMock()+ mock_prisma.db = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)auth = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")@@ -544,27 +560,85 @@ async def test_spend_logs_ui_group_by_session_paginates_sessions(monkeypatch):sort_order="desc",user_api_key_dict=auth,group_by_session=True,+ session_cursor=None,)- group_key = "COALESCE(NULLIF(session_id, ''), request_id), api_key"+ emitted = [call[0] for call in mock_prisma.db.query_raw.call_args_list]+ page_sql = emitted[0][0]+ assert f"GROUP BY {group_key}" in page_sql, f"page must select sessions, not calls. SQL was:\n{page_sql}"+ assert "OFFSET" not in page_sql, "the startTime page must be keyset-selected, not offset-selected"+ assert emitted[0][-1] == 51, "the page query fetches page_size + 1 sessions to detect has_more"- count_call = mock_prisma.db.query_raw.call_args_list[0]- count_sql = count_call[0][0]+ count_call = emitted[1]+ count_sql = count_call[0]assert f"GROUP BY {group_key}" in count_sql, f"grouped total must count sessions. SQL was:\n{count_sql}"assert "COUNT(*) OVER ()" not in count_sqlassert "LIMIT" in count_sql and "FROM (" in count_sql, "the grouped count must stay bounded"- assert count_call[0][-1] == SPEND_LOGS_PAGINATION_COUNT_CAP + 1+ assert count_call[-1] == SPEND_LOGS_PAGINATION_COUNT_CAP + 1- page_sql = mock_prisma.db.query_raw.call_args_list[1][0][0]- assert f"DISTINCT ON ({group_key})" in page_sql, f"page must return one row per session. SQL was:\n{page_sql}"- assert f"ORDER BY {group_key}, call_type IN ('call_mcp_tool', 'list_mcp_tools'), \"startTime\" DESC" in page_sql, (+ rep_sql = emitted[2][0]+ assert f"DISTINCT ON ({group_key})" in rep_sql, f"page must return one row per session. SQL was:\n{rep_sql}"+ assert f"ORDER BY {group_key}, call_type IN ('call_mcp_tool', 'list_mcp_tools'), \"startTime\" DESC" in rep_sql, ("the session representative must prefer the newest non-MCP call")- assert "COUNT(*) OVER ()" not in page_sql+ assert "COUNT(*) OVER ()" not in rep_sql+ assert [row["request_id"] for row in response["data"]] == ["req-1", "req-2"]assert response["total"] == 12assert response["total_is_capped"] is Falseassert response["total_pages"] == 1+ assert response["has_more"] is False+ assert response["next_session_cursor"] is None+++async def test_spend_logs_ui_group_by_session_offset_pages_for_other_sorts(monkeypatch):+ """+ Sorting a grouped listing by a column other than startTime has no keyset+ to resume from, so it pages the DISTINCT ON representatives with OFFSET.+ """+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.spend_tracking.spend_management_endpoints import ui_view_spend_logs++ page_rows = [+ {"request_id": "req-1", "metadata": "{}", "session_id": None},+ {"request_id": "req-2", "metadata": "{}", "session_id": None},+ ]+ mock_prisma = _make_ui_spend_logs_mock(count_total=12, 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=2,+ page_size=50,+ sort_by="spend",+ sort_order="desc",+ user_api_key_dict=auth,+ group_by_session=True,+ )++ group_key = "COALESCE(NULLIF(session_id, ''), request_id), api_key"+ count_sql = mock_prisma.db.query_raw.call_args_list[0][0][0]+ assert f"GROUP BY {group_key}" in count_sql++ page_call = mock_prisma.db.query_raw.call_args_list[1][0]+ page_sql = page_call[0]+ assert f"DISTINCT ON ({group_key})" in page_sql+ assert "ORDER BY spend DESC" in page_sql+ assert "OFFSET" in page_sql+ assert page_call[-2:] == (50, 50), "page 2 of 50 skips the first 50 sessions"++ assert response["total"] == 12+ assert "next_session_cursor" not in response@pytest.mark.asynciodiff --git a/ui/litellm-dashboard/eslint-budgets.json b/ui/litellm-dashboard/eslint-budgets.jsonindex e8207d179bd..3f9163d9028 100644--- a/ui/litellm-dashboard/eslint-budgets.json+++ b/ui/litellm-dashboard/eslint-budgets.json@@ -3,7 +3,7 @@"no-console": { "max": 12, "target": 0 },"complexity": { "max": 140, "target": 80 },"max-depth": { "max": 70, "target": 30 },- "local/no-large-inline-object-arg": { "max": 559, "target": 300 },+ "local/no-large-inline-object-arg": { "max": 555, "target": 300 },"local/no-long-condition-chain": { "max": 265, "target": 120 },"testing-library/no-container": { "max": 133, "target": 50 },"testing-library/no-node-access": { "max": 716, "target": 500 },diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex a01d52fc865..7e0f6c7e4f5 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -2053,6 +2053,7 @@ interface UiSpendLogsParams {max_spend?: number;exclude_internal_health_checks?: boolean;group_by_session?: boolean;+ session_cursor?: string;}interface UiSpendLogsCallOptions {diff --git a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsxindex cb7836d603f..60657872ccc 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx@@ -92,7 +92,10 @@ export function LogsTableToolbar({<Buttonvariant="ghost"className="w-full justify-start font-normal"- onClick={() => onIsCustomDateChange(!isCustomDate)}+ onClick={() => {+ onIsCustomDateChange(!isCustomDate);+ onResetToFirstPage();+ }}>Custom Range</Button>diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsxindex c368a43dd1e..93066c106ee 100644--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx@@ -139,19 +139,20 @@ describe("RequestLogsPanel", () => {});describe("server-grouped session pagination (#38060)", () => {- it("requests session-grouped pages of 10 rows by default", async () => {+ it("requests session-grouped pages of 10 rows by default without a cursor", async () => {renderPanel();await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());expect(lastCall()?.params?.group_by_session).toBe(true);+ expect(lastCall()?.params?.session_cursor).toBeUndefined();expect(lastCall()?.page_size).toBe(10);});it("renders every row the server returns without client-side collapsing", async () => {respondWith([- logEntry({ request_id: "req-a", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),- logEntry({ request_id: "req-b", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),- logEntry({ request_id: "req-c", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-a", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-b", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-c", session_id: "sess-1", session_total_count: 3 }),]);renderPanel();@@ -177,6 +178,138 @@ describe("RequestLogsPanel", () => {expect(within(row("req-llm") as HTMLElement).getByText("3")).toBeInTheDocument();});+ it("passes the server keyset cursor when navigating to the next page", async () => {+ const firstPage = Array.from({ length: 50 }, (_, index) => logEntry({ request_id: `req-${index}` }));+ vi.mocked(uiSpendLogsCall).mockResolvedValue({+ data: firstPage,+ total: 80,+ page: 1,+ page_size: 50,+ total_pages: 2,+ next_session_cursor: "2026-07-07 09:50:13|key-1|sess-1",+ has_more: true,+ });+ renderPanel();++ await waitFor(() => expect(row("req-0")).not.toBeNull());+ fireEvent.click(screen.getByTestId("pagination-next"));++ await waitFor(() => {+ const call = lastCall();+ expect(call?.params?.session_cursor).toBe("2026-07-07 09:50:13|key-1|sess-1");+ expect(call?.page).toBe(2);+ });+ });++ it("drops the cursor and returns to the first page when a filter changes", async () => {+ const firstPage = Array.from({ length: 50 }, (_, index) => logEntry({ request_id: `req-${index}` }));+ vi.mocked(uiSpendLogsCall).mockResolvedValue({+ data: firstPage,+ total: 80,+ page: 1,+ page_size: 50,+ total_pages: 2,+ next_session_cursor: "2026-07-07 09:50:13|key-1|sess-1",+ has_more: true,+ });+ renderPanel();++ await waitFor(() => expect(row("req-0")).not.toBeNull());+ fireEvent.click(screen.getByTestId("pagination-next"));+ await waitFor(() => expect(lastCall()?.page).toBe(2));++ fireEvent.change(screen.getByTestId("datatable-search"), { target: { value: "req-elsewhere" } });++ await waitFor(() => {+ const call = lastCall();+ expect(call?.page).toBe(1);+ expect(call?.params?.session_cursor).toBeUndefined();+ });+ });++ it("ignores another next click while the next page is still fetching", async () => {+ const firstPage = Array.from({ length: 50 }, (_, index) => logEntry({ request_id: `req-${index}` }));+ const firstResponse = {+ data: firstPage,+ total: 150,+ page: 1,+ page_size: 50,+ total_pages: 3,+ next_session_cursor: "2026-07-07 09:50:13|key-1|sess-1",+ has_more: true,+ };+ vi.mocked(uiSpendLogsCall)+ .mockResolvedValueOnce(firstResponse)+ .mockImplementation(() => new Promise(() => {}));+ renderPanel();++ await waitFor(() => expect(row("req-0")).not.toBeNull());+ fireEvent.click(screen.getByTestId("pagination-next"));+ await waitFor(() => expect(lastCall()?.page).toBe(2));++ fireEvent.click(screen.getByTestId("pagination-next"));++ expect(lastCall()?.page).toBe(2);+ expect(vi.mocked(uiSpendLogsCall).mock.calls.filter(([options]) => options.page === 3)).toHaveLength(0);+ });++ it("still moves to the next page while a live-tail refetch of the current page is in flight", async () => {+ const firstPage = Array.from({ length: 50 }, (_, index) => logEntry({ request_id: `req-${index}` }));+ const firstResponse = {+ data: firstPage,+ total: 150,+ page: 1,+ page_size: 50,+ total_pages: 3,+ next_session_cursor: "2026-07-07 09:50:13|key-1|sess-1",+ has_more: true,+ };+ vi.mocked(uiSpendLogsCall)+ .mockResolvedValueOnce(firstResponse)+ .mockImplementation(() => new Promise(() => {}));+ renderPanel();++ await waitFor(() => expect(row("req-0")).not.toBeNull());+ void testQueryClient.refetchQueries({ queryKey: ["logs", "table"] });+ await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalledTimes(2));++ fireEvent.click(screen.getByTestId("pagination-next"));++ await waitFor(() => {+ const call = lastCall();+ expect(call?.page).toBe(2);+ expect(call?.params?.session_cursor).toBe("2026-07-07 09:50:13|key-1|sess-1");+ });+ });++ it("drops the cursor and returns to the first page when Custom Range is toggled", async () => {+ const user = userEvent.setup();+ const firstPage = Array.from({ length: 50 }, (_, index) => logEntry({ request_id: `req-${index}` }));+ vi.mocked(uiSpendLogsCall).mockResolvedValue({+ data: firstPage,+ total: 80,+ page: 1,+ page_size: 50,+ total_pages: 2,+ next_session_cursor: "2026-07-07 09:50:13|key-1|sess-1",+ has_more: true,+ });+ renderPanel();++ await waitFor(() => expect(row("req-0")).not.toBeNull());+ fireEvent.click(screen.getByTestId("pagination-next"));+ await waitFor(() => expect(lastCall()?.page).toBe(2));++ await user.click(screen.getByRole("button", { name: /Last 24 Hours/i }));+ await user.click(await screen.findByRole("button", { name: "Custom Range" }));++ await waitFor(() => {+ const call = lastCall();+ expect(call?.page).toBe(1);+ expect(call?.params?.session_cursor).toBeUndefined();+ });+ });+it("leaves single-call rows untouched", async () => {respondWith([logEntry({ request_id: "req-solo-a", session_id: "sess-a", session_total_count: 1 }),@@ -395,9 +528,7 @@ describe("RequestLogsPanel", () => {});it("opens a deep-linked multi-call session log in session mode", async () => {- respondWith([- logEntry({ request_id: "req-llm", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),- ]);+ respondWith([logEntry({ request_id: "req-llm", session_id: "sess-1", session_total_count: 3 })]);renderPanel("?log_id=req-llm");await waitFor(() => {@@ -410,8 +541,8 @@ describe("RequestLogsPanel", () => {it("clicking a multi-call session's row writes ?session_id= alongside ?log_id=", async () => {const user = userEvent.setup();respondWith([- logEntry({ request_id: "req-llm", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),- logEntry({ request_id: "req-llm-2", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-llm", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-llm-2", session_id: "sess-1", session_total_count: 3 }),]);renderPanel();@@ -426,7 +557,7 @@ describe("RequestLogsPanel", () => {it("selecting another log while a session view is open keeps the session open", async () => {const user = userEvent.setup();respondWith([- logEntry({ request_id: "req-llm", call_type: "acompletion", session_id: "sess-1", session_total_count: 3 }),+ logEntry({ request_id: "req-llm", session_id: "sess-1", session_total_count: 3 }),logEntry({ request_id: "req-unenriched" }),]);renderPanel("?log_id=req-llm");diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsxindex 2ebabf64ab0..96cf2bd5dde 100644--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx@@ -39,6 +39,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: PAGE_SIZE });const [sorting, setSorting] = useState<SortingState>(DEFAULT_LOGS_SORTING);const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);+ const [sessionCursors, setSessionCursors] = useState<Record<number, string>>({});const [startTime, setStartTime] = useState<string>(moment().subtract(24, "hours").format("YYYY-MM-DDTHH:mm"));const [endTime, setEndTime] = useState<string>(moment().format("YYYY-MM-DDTHH:mm"));@@ -74,7 +75,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,sessionStorage.setItem("excludeInternalHealthChecks", JSON.stringify(excludeInternalHealthChecks));}, [excludeInternalHealthChecks]);- const { logsQuery, filteredLogs, allTeams } = useLogFilterLogic({+ const { logsQuery, filteredLogs, allTeams, usesSessionCursor } = useLogFilterLogic({accessToken,token,userRole,@@ -88,6 +89,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,pagination,isCustomDate,sorting,+ sessionCursors,});// Follow the table's own last fetch so a live-tail refresh carries the filter@@ -163,23 +165,52 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,const others = previous.filter((filter) => filter.id !== LOG_FILTER_IDS.REQUEST_ID);return value === "" ? others : [...others, { id: LOG_FILTER_IDS.REQUEST_ID, value }];});+ setSessionCursors({});setPagination((previous) => ({ ...previous, pageIndex: 0 }));}, []);const handleSortingChange = useCallback<OnChangeFn<SortingState>>((updaterOrValue) => {setSorting(updaterOrValue);+ setSessionCursors({});setPagination((previous) => ({ ...previous, pageIndex: 0 }));}, []);const handleColumnFiltersChange = useCallback<OnChangeFn<ColumnFiltersState>>((updaterOrValue) => {setColumnFilters(updaterOrValue);+ setSessionCursors({});setPagination((previous) => ({ ...previous, pageIndex: 0 }));}, []);const resetToFirstPage = useCallback(() => {+ setSessionCursors({});setPagination((previous) => ({ ...previous, pageIndex: 0 }));}, []);+ const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(+ (updaterOrValue) => {+ const requested = typeof updaterOrValue === "function" ? updaterOrValue(pagination) : updaterOrValue;+ if (!usesSessionCursor) {+ setPagination(requested);+ return;+ }+ if (requested.pageSize !== pagination.pageSize) {+ setSessionCursors({});+ setPagination({ ...requested, pageIndex: 0 });+ return;+ }+ if (requested.pageIndex <= pagination.pageIndex) {+ setPagination(requested);+ return;+ }+ const nextCursor = filteredLogs.next_session_cursor;+ if (!nextCursor || logsQuery.isPlaceholderData) return;+ const nextPageIndex = pagination.pageIndex + 1;+ setSessionCursors((previous) => ({ ...previous, [nextPageIndex]: nextCursor }));+ setPagination({ ...requested, pageIndex: nextPageIndex });+ },+ [usesSessionCursor, pagination, filteredLogs.next_session_cursor, logsQuery.isPlaceholderData],+ );+const handleExcludeInternalHealthChecksChange = useCallback((value: boolean) => {setExcludeInternalHealthChecks(value);@@ -256,7 +287,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,isLoading={logsQuery.isLoading}isRefreshing={logsQuery.isFetching}pagination={pagination}- onPaginationChange={setPagination}+ onPaginationChange={handlePaginationChange}sorting={sorting}onSortingChange={handleSortingChange}columnFilters={columnFilters}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 acd5be06593..90f0f0a60f1 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@@ -15,6 +15,8 @@ export interface PaginatedResponse {page_size: number;total_pages: number;total_is_capped?: boolean;+ next_session_cursor?: string | null;+ has_more?: boolean;}export const LOG_FILTER_IDS = {@@ -109,6 +111,7 @@ export function useLogFilterLogic({pagination,isCustomDate,sorting,+ sessionCursors = {},}: {accessToken: string | null;token: string | null;@@ -123,11 +126,14 @@ export function useLogFilterLogic({pagination: PaginationState;isCustomDate: boolean;sorting: SortingState;+ sessionCursors?: Record<number, string>;}) {const pageSize = pagination.pageSize || defaultPageSize;const activeSort = sorting[0] ?? DEFAULT_LOGS_SORTING[0];const sortBy: LogsSortField = isSortField(activeSort.id) ? activeSort.id : "startTime";const sortOrder: "asc" | "desc" = activeSort.desc ? "desc" : "asc";+ const usesSessionCursor = sortBy === "startTime";+ const sessionCursor = usesSessionCursor ? sessionCursors[pagination.pageIndex] : undefined;const logsQueryOptions: UseQueryOptions<PaginatedResponse> = {queryKey: [@@ -142,6 +148,7 @@ export function useLogFilterLogic({sortBy,sortOrder,excludeInternalHealthChecks,+ sessionCursor,],queryFn: async () => {if (!accessToken || !token || !userRole || !userID) {@@ -182,6 +189,7 @@ export function useLogFilterLogic({sort_order: sortOrder,exclude_internal_health_checks: excludeInternalHealthChecks,group_by_session: true,+ session_cursor: sessionCursor,},});},@@ -219,5 +227,6 @@ export function useLogFilterLogic({logsQuery,filteredLogs,allTeams,+ usesSessionCursor,};}diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 3a4e013b684..098b43f6433 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -56863,6 +56863,8 @@ export interface operations {exclude_internal_health_checks?: boolean;/** @description Paginate over sessions instead of raw logs: one representative row per session, total counts sessions */group_by_session?: boolean;+ /** @description Keyset cursor '<last_activity>|<api_key>|<session_key>' from a previous group_by_session page. UI route only, honored when sorting by startTime */+ session_cursor?: string | null;};header?: never;path?: never;@@ -56977,6 +56979,8 @@ export interface operations {exclude_internal_health_checks?: boolean;/** @description Paginate over sessions instead of raw logs: one representative row per session, total counts sessions */group_by_session?: boolean;+ /** @description Keyset cursor '<last_activity>|<api_key>|<session_key>' from a previous group_by_session page. UI route only, honored when sorting by startTime */+ session_cursor?: string | null;};header?: never;path?: never;