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
Merge origin/litellm_internal_staging into litellm_spend_log_request_id_call_id
mateo-berri8608a03bd871
diff --cc litellm/constants.pyindex 6430cffe9b7,be5a4e4b076..816f0c24eab--- a/litellm/constants.py+++ b/litellm/constants.py@@@ -136,7 -143,7 +143,8 @@@ DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD", 0.3))MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH: Final = int(os.getenv("MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH", 150))+MAX_LITELLM_CALL_ID_LENGTH: Final = 256+ MAX_GUARDRAIL_SCAN_METADATA_HEADER_LENGTH: Final = 2048DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS: Final = 2000diff --cc litellm/proxy/spend_tracking/spend_management_endpoints.pyindex f7875cfb28d,8cfb6354dd0..0ec2788fbaa--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@@ -3,8 -3,9 +3,10 @@@ import collectionimport jsonimport osfrom collections.abc import Mapping, Sequence+from dataclasses import dataclass- from datetime import datetime, timedelta, timezone+ from datetime import date, datetime, timedelta, timezone+ from itertools import groupby+ from types import MappingProxyTypefrom typing import (TYPE_CHECKING,Annotated,@@@ -13,9 -14,9 +15,10 @@@Literal,NamedTuple,Protocol,+ TypeAlias,TypedDict,TypeVar,- cast, # noqa: TID251 # prisma group_by returns untyped aggregate mappings++ cast, # noqa: TID251 # custom-logger and cold-storage payloads are untyped JSON)import fastapi@@@ -56,9 -63,21 +65,22 @@@ 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,++ litellm_call_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,@@@ -2711,10 -2843,10 +2877,10 @@@ async def ui_view_spend_logsif session_groupingelse f"""SELECT- {select_columns}+ {_SPEND_LOG_LIST_COLUMNS}FROM "LiteLLM_SpendLogs"WHERE {joined_conditions}- ORDER BY {_order_expr} {_sql_dir}{_nulls_clause}+ ORDER BY {exact_request_id_first}{_order_expr} {_sql_dir}{_nulls_clause}LIMIT ${p} OFFSET ${p + 1}""")@@@ -3062,13 -3383,15 +3433,15 @@@ async def view_spend_logs}}+ summary_api_key: Final[str | None] = (+ prisma_client.hash_token(token=api_key)+ if api_key is not None and api_key.startswith("sk-")+ else api_key+ )if api_key is not None and isinstance(api_key, str):- if api_key.startswith("sk-"):- filter_query["api_key"] = prisma_client.hash_token(token=api_key)- else:- filter_query["api_key"] = api_key+ filter_query["api_key"] = summary_api_keyif request_id is not None and isinstance(request_id, str):- filter_query["request_id"] = request_id+ filter_query["OR"] = _request_id_or_call_id_clause(request_id)if user_id is not None and isinstance(user_id, str):filter_query["user"] = user_id@@@ -3085,61 -3408,38 +3458,38 @@@return data# Legacy behavior: return summarized data (when summarize=true)- # SQL query- response: Final = await SpendLogsRepository(prisma_client).table.group_by(- by=["api_key", "user", "model", "startTime"],- where=filter_query,- sum={- "spend": True,- },+ summary_sql_and_params: Final = _spend_logs_daily_summary_sql(+ start_date_iso=start_date_iso,+ end_date_iso=end_date_iso,+ api_key=summary_api_key,+ request_id=request_id,+ user_id=user_id,)-- if isinstance(response, list) and len(response) > 0 and isinstance(response[0], dict):- spend_rows: Final = cast(Sequence[_SpendGroupByRow], response) # cast-ok: by/sum fix the shape- result: Final[dict] = {}- for record in spend_rows:- dt_object = datetime.strptime(str(record["startTime"]), "%Y-%m-%dT%H:%M:%S.%fZ")- date = dt_object.date()- if date not in result:- result[date] = {"users": {}, "models": {}}- api_key = record["api_key"]- user_id = record["user"]- model = record["model"]- result[date]["spend"] = result[date].get("spend", 0) + record.get("_sum", {}).get("spend", 0)- result[date][api_key] = result[date].get(api_key, 0) + record.get("_sum", {}).get("spend", 0)- result[date]["users"][user_id] = result[date]["users"].get(user_id, 0) + record.get("_sum", {}).get(- "spend", 0- )- result[date]["models"][model] = result[date]["models"].get(model, 0) + record.get("_sum", {}).get(- "spend", 0- )- return_list: Final = []- final_date = None- for k, v in sorted(result.items()):- return_list.append({**v, "startTime": k})- final_date = k-- end_date_date: Final = end_date_obj.date()- if final_date is not None and final_date < end_date_date:- current_date = final_date + timedelta(days=1)- while current_date <= end_date_date:- # Represent current_date as string because original response has it this way- return_list.append(- {- "startTime": current_date,- "spend": 0,- "users": {},- "models": {},- }- ) # If no data, will stay as zero- current_date += timedelta(days=1) # Move on to the next day-- return return_list-- return response+ sql_query, params = summary_sql_and_params+ rows: Final[Sequence[_SpendDailySummaryRow]] = await _query_raw(prisma_client, sql_query, *params)+ summary_items: Final = tuple(+ _daily_summary_item(date.fromisoformat(day), tuple(day_rows))+ for day, day_rows in groupby(rows, key=lambda row: row["day"])+ )+ final_date: Final = date.fromisoformat(rows[-1]["day"]) if len(rows) > 0 else None+ end_date_date: Final = end_date_obj.date()+ padding: Final[tuple[Mapping[str, object], ...]] = (+ ()+ if final_date is None+ else tuple(+ {+ "startTime": final_date + timedelta(days=offset),+ "spend": 0,+ "users": {},+ "models": {},+ }+ for offset in range(1, (end_date_date - final_date).days + 1)+ )+ )+ return [*summary_items, *padding]else:- scoped_filter: Final[dict[str, str]] = {}+ scoped_filter: Final[dict[str, object]] = {}if api_key is not None and isinstance(api_key, str):if api_key.startswith("sk-"):hashed_token = prisma_client.hash_token(token=api_key)@@@ -4375,106 -4682,30 +4756,107 @@@ async def _assert_user_can_view_requestrequest_id: str,) -> None:"""- Verify the requesting non-admin user is allowed to view this spend-log row.- Allowed when the log belongs to the user directly, or to one of their- permitted teams (admin or ``/spend/logs`` permission).- Raises HTTP 403 if not, including when no spend-log row exists for the- request_id (e.g. it was pruned by retention), so a missing row can't be- used to read a payload out of cold storage via the detail endpoint.+ Verify the requesting non-admin user is allowed to view at least one spend-log+ row identified by ``request_id`` or ``litellm_call_id``. The latter is+ client-settable, so an id lookup can match rows across different tenants; the+ data queries scope a non-admin's results to rows they own directly or via a+ permitted team, so a colliding foreign row can neither be served nor deny the- caller their own. Raises HTTP 403 when rows match and none is theirs to view.++ caller their own. Raises HTTP 403 when none of the matching rows is theirs to++ view, including when no row exists at all (e.g. it was pruned by retention),++ so a missing row can't be used to read a payload out of cold storage via the++ detail endpoint."""- row: Final = await _find_spend_log_row(prisma_client, request_id)+ owners: Final = await _find_spend_log_owners(prisma_client, request_id)- if not owners:- return+ for owner in owners:+ if await _user_can_view_spend_log_owner(prisma_client, user_api_key_dict, owner["user"], owner["team_id"]):+ return+ raise _spend_log_forbidden(request_id)+++@dataclass(frozen=True, slots=True)+class _SpendLogViewer:+ user_id: str | None+ team_ids: tuple[str, ...]+++async def _spend_log_viewer(prisma_client: PrismaClient, user_api_key_dict: UserAPIKeyAuth) -> _SpendLogViewer:+ return _SpendLogViewer(+ user_id=user_api_key_dict.user_id,+ team_ids=await _get_permitted_team_ids_for_spend_logs_or_empty(+ prisma_client=prisma_client,+ user_api_key_dict=user_api_key_dict,+ ),+ )- if row is not None and row.user is not None and row.user == user_api_key_dict.user_id:- return- if row is not None and row.team_id:- can_view: Final = await _can_team_member_view_log(+def _viewer_scope_clause(viewer: _SpendLogViewer | None) -> tuple[str, tuple[object, ...]]:+ match viewer:+ case None:+ return ("", ())+ case _SpendLogViewer(user_id=user_id, team_ids=()):+ return (' AND "user" = $2', (user_id,))+ case _SpendLogViewer(user_id=user_id, team_ids=team_ids):+ return (' AND ("user" = $2 OR team_id = ANY($3::text[]))', (user_id, team_ids))+++def _spend_log_payload_query(request_id: str, viewer: _SpendLogViewer | None) -> tuple[str, tuple[object, ...]]:+ """+ Fetch the one row an id lookup resolves to, preferring the exact ``request_id``+ match over rows that merely carry the id as their client-set ``litellm_call_id``.+ A non-admin viewer only ever gets rows they own or rows of a team they may view.+ """+ scope, scope_params = _viewer_scope_clause(viewer)+ return (+ f"""+ SELECT request_id, messages, response, proxy_server_request, metadata, "user", team_id+ FROM "LiteLLM_SpendLogs"+ WHERE (request_id = $1 OR litellm_call_id = $1){scope}+ ORDER BY (request_id = $1) DESC+ LIMIT 1+ """,+ (request_id, *scope_params),+ )+++async def _resolve_spend_log_payload_row(+ prisma_client: PrismaClient,+ user_api_key_dict: UserAPIKeyAuth,+ request_id: str,+ caller_is_admin: bool,+) -> Mapping[str, object] | None:+ """+ Resolve an id lookup to the caller's own spend-log row before any payload+ store is consulted. Cold storage is keyed by the provider ``request_id``, so+ asking it for the raw lookup id could hand back another tenant's payload when+ that id is only the caller's ``litellm_call_id``; the row's stored+ ``request_id`` is the key that names the caller's own request.+ """+ viewer: Final = None if caller_is_admin else await _spend_log_viewer(prisma_client, user_api_key_dict)+ sql_query, sql_params = _spend_log_payload_query(request_id, viewer)+ rows: Final[Sequence[Mapping[str, object]] | None] = await _query_raw_or_none(prisma_client, sql_query, *sql_params)+ if not rows:+ return None+ if not caller_is_admin:+ await _assert_user_owns_fetched_spend_rows(prisma_client=prisma_client,user_api_key_dict=user_api_key_dict,- team_id=row.team_id,+ rows=rows,+ request_id=request_id,)- if can_view:- return+ return rows[0]- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail={"error": f"Not authorized to view spend log for request_id={request_id}"},++def _stored_request_id(row: Mapping[str, object] | None, lookup_id: str) -> str:+ stored: Final = None if row is None else row.get("request_id")+ return stored if isinstance(stored, str) else lookup_id+++def _fetched_row_owner(row: Mapping[str, object]) -> tuple[str | None, str | None]:+ user: Final = row.get("user")+ team_id: Final = row.get("team_id")+ return (+ user if isinstance(user, str) else None,+ team_id if isinstance(team_id, str) else None,)diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex 26cc0c3bd18,6e43ac4a12b..8283ee8395a--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@@ -461,121 -455,34 +487,136 @@@ async def test_assert_user_can_view_reqassert exc_info.value.status_code == 403+async def test_assert_user_can_view_request_id_rejects_when_no_match_is_owned():+ """An id whose every matching row belongs to other tenants is refused outright,+ so the relaxed date window of an id lookup cannot reach a foreign row."""+ prisma = _make_owner_lookup_prisma(+ [+ {"request_id": "foreign-request", "litellm_call_id": "shared-id", "user": "tenant_a", "team_id": None},+ {"request_id": "shared-id", "litellm_call_id": "other-call-id", "user": "tenant_b", "team_id": None},+ ]+ )++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")+ with pytest.raises(HTTPException) as exc_info:+ await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "shared-id")+ assert exc_info.value.status_code == 403+++async def test_assert_user_can_view_request_id_allows_owner_despite_foreign_collision():+ """+ litellm_call_id comes from the client-settable x-litellm-call-id header, so+ another tenant can mint a row whose call id equals the caller's request_id.+ That collision must not lock the caller out of their own row: the pre-check+ passes once one match is theirs, and the scoped data queries keep the foreign+ row out of the result. Regression for the every-match-must-be-owned rule that+ let any tenant deny another's lookup by reusing their id.+ """+ prisma = _make_owner_lookup_prisma(+ [+ {+ "request_id": "attacker-own-request",+ "litellm_call_id": "victim-request-id",+ "user": "attacker",+ "team_id": None,+ },+ {+ "request_id": "victim-request-id",+ "litellm_call_id": "victim-call-id",+ "user": "victim",+ "team_id": None,+ },+ ]+ )++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="victim")+ result = await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "victim-request-id")++ assert result is None+++async def test_assert_user_can_view_request_id_finds_owner_past_any_row_cap():+ """+ An attacker can mint hundreds of rows carrying the victim's request_id as+ their litellm_call_id, so a capped or sampled ownership read could exhaust+ its cap on attacker-owned rows and never see the victim's own row, locking+ the victim out of their lookup. The ownership read must consider every+ matching row's owner no matter how many rows match. Regression for the+ find_many(take=100) sample the first fix used.+ """+ rows = [+ {+ "request_id": f"attacker-request-{i}",+ "litellm_call_id": "victim-request-id",+ "user": "attacker",+ "team_id": None,+ }+ for i in range(150)+ ]+ rows.append(+ {+ "request_id": "victim-request-id",+ "litellm_call_id": "victim-call-id",+ "user": "victim",+ "team_id": None,+ }+ )+ prisma = _make_owner_lookup_prisma(rows)++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="victim")+ result = await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "victim-request-id")++ assert result is None+++async def test_assert_user_can_view_request_id_allows_when_every_match_is_owned():+ """The same ambiguous id matching more than one row is fine when every match+ belongs to the caller (e.g. two of the caller's own requests happen to share+ a request_id/litellm_call_id pairing); only a foreign match should block it."""+ prisma = _make_owner_lookup_prisma(+ [+ {+ "request_id": "shared-request-id",+ "litellm_call_id": "caller-call-a",+ "user": "caller",+ "team_id": None,+ },+ {+ "request_id": "caller-request-b",+ "litellm_call_id": "shared-request-id",+ "user": "caller",+ "team_id": None,+ },+ ]+ )++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")+ result = await spend_management_endpoints._assert_user_can_view_request_id(+ prisma, auth, "shared-request-id"+ )++ assert result is None+++ @pytest.mark.asyncio+ async def test_assert_user_can_view_request_id_rejects_missing_row():+ """+ A request_id with no spend-log row (e.g. pruned by retention) must not+ authorize reading the payload from cold storage; a missing row is not+ the same as an owned row.+ """-- class MockSpendLogs:- async def find_unique(self, where, include=None):- return None-- class MockDB:- def __init__(self):- self.litellm_spendlogs = MockSpendLogs()-- class MockPrisma:- def __init__(self):- self.db = MockDB()++ prisma = _make_owner_lookup_prisma([])++ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")+ with pytest.raises(HTTPException) as exc_info:- await spend_management_endpoints._assert_user_can_view_request_id(- MockPrisma(), auth, "req-missing-row"- )++ await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "req-missing-row")+ assert exc_info.value.status_code == 403++def test_ui_view_request_response_forbids_non_admin_without_db(client, monkeypatch):"""Without prisma, non-admins cannot be authorized to read request/response@@@ -2810,159 -2330,6 +2851,116 @@@ async def test_ui_view_request_responseheaders={"Authorization": "Bearer sk-test"},)assert response.status_code == 403+ assert "victim prompt" not in response.text+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++- @pytest.mark.asyncio- async def test_ui_view_request_response_custom_logger_allows_own_payload_without_db_row(client, monkeypatch):- """The payload-owner authorization must not false-deny a legitimate owner whose- spend-log row is already gone from the DB. An empty owner lookup with a cold-storage- payload the caller owns still serves the payload."""-- class MockDB:- async def query_raw(self, sql_query, *params):- return []-- class MockPrisma:- def __init__(self):- self.db = MockDB()-- class ColdStorageLogger:- async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):- return {- "messages": [{"role": "user", "content": "my own prompt"}],- "response": {"id": "r"},- "metadata": {"user_api_key_user_id": "user_1", "user_api_key_team_id": None},- }-- monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrisma())- monkeypatch.setattr(- litellm.logging_callback_manager,- "get_active_additional_logging_utils_from_custom_logger",- lambda: [ColdStorageLogger()],- )- app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(- user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"- )- try:- response = client.get(- "/spend/logs/ui/shared-id",- params={"start_date": "2026-01-01 00:00:00"},- headers={"Authorization": "Bearer sk-test"},- )- assert response.status_code == 200- assert "my own prompt" in response.text- finally:- app.dependency_overrides.pop(ps.user_api_key_auth, None)--+async def test_ui_view_request_response_custom_logger_is_keyed_by_callers_own_request_id(client, monkeypatch):+ """Cold storage is keyed by the provider request_id. The caller's row carries the+ lookup id only as its client-set litellm_call_id while another tenant's row owns+ that id as its request_id. The custom logger is asked for the caller's own stored+ request_id, so the caller gets their payload rather than a 403 from the foreign+ payload's owner check, and the foreign payload is never fetched."""+ prisma = _make_payload_lookup_prisma(+ [+ _payload_row("shared-id", "other-call-id", "other_user", "other tenant prompt"),+ _payload_row("caller-req", "shared-id", "caller_user", "caller prompt"),+ ]+ )+ cold_storage = {+ "shared-id": {+ "messages": [{"role": "user", "content": "other tenant prompt"}],+ "response": {"id": "shared-id"},+ "metadata": {"user_api_key_user_id": "other_user", "user_api_key_team_id": None},+ },+ "caller-req": {+ "messages": [{"role": "user", "content": "caller prompt"}],+ "response": {"id": "caller-req"},+ "metadata": {"user_api_key_user_id": "caller_user", "user_api_key_team_id": None},+ },+ }+ requested_ids = []++ class ColdStorageLogger:+ async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):+ requested_ids.append(request_id)+ return cold_storage.get(request_id)++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)+ monkeypatch.setattr(+ litellm.logging_callback_manager,+ "get_active_additional_logging_utils_from_custom_logger",+ lambda: [ColdStorageLogger()],+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller_user"+ )+ try:+ response = client.get("/spend/logs/ui/shared-id", headers={"Authorization": "Bearer sk-test"})+ assert response.status_code == 200, response.text+ assert "caller prompt" in response.text+ assert "other tenant prompt" not in response.text+ assert requested_ids == ["caller-req"]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++[email protected]("group_by_session", [False, True])+async def test_ui_view_spend_logs_id_lookup_lists_exact_request_id_row_first(client, monkeypatch, group_by_session):+ """The dashboard's deep link fetches a single row for ``?log_id=``. When a newer+ row carries that id as its client-set litellm_call_id, the row whose request_id+ is the id still comes first, so the link opens the request it names. The+ session-grouped page orders its representatives the same way."""+ today = datetime.datetime.now(timezone.utc)+ corpus = [+ {+ "id": "log_colliding",+ "request_id": "colliding-req",+ "litellm_call_id": "victim-req",+ "api_key": "sk-test-key",+ "user": "other_user",+ "team_id": None,+ "spend": 0.01,+ "startTime": today.isoformat(),+ "model": "gpt-4",+ },+ {+ "id": "log_victim",+ "request_id": "victim-req",+ "litellm_call_id": "victim-call-id",+ "api_key": "sk-test-key",+ "user": "victim_user",+ "team_id": None,+ "spend": 0.02,+ "startTime": (today - datetime.timedelta(minutes=5)).isoformat(),+ "model": "gpt-4",+ },+ ]++ def filter_fn(where):+ rows = _filter_logs_by_date_range(corpus, where)+ rid_either = where.get("request_id_or_call_id")+ if rid_either:+ return [r for r in rows if rid_either in (r["request_id"], r["litellm_call_id"])]+ return rows++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", make_ui_spend_logs_mock_prisma(corpus, filter_fn))+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"+ )+ try:+ response = client.get(+ "/spend/logs/ui",+ params={"request_id": "victim-req", "page_size": 1, "group_by_session": str(group_by_session).lower()},+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["total"] == 2+ assert [row["request_id"] for row in data["data"]] == ["victim-req"]finally:app.dependency_overrides.pop(ps.user_api_key_auth, None)@@@ -6659,3 -6550,660 +7173,657 @@@ def test_scoped_spend_report_range_at_mmock_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}+++ def _session_grouped_paginating_prisma(sessions, counted_total=None):+ """Mock prisma serving the grouped page query out of ``sessions``, honoring the LIMIT and OFFSET it asks for."""++ async def mock_query_raw(sql_query, *params):+ if "COUNT(*) AS total_count" in sql_query:+ return [{"total_count": min(len(sessions) if counted_total is None else counted_total, params[-1])}]+ if "DISTINCT ON" in sql_query:+ return [_session_representative_row(f"req-{session_key}", session_key) for session_key in params[-2]]+ if "COALESCE(SUM(spend)" in sql_query:+ return []+ bounds = re.search(r"LIMIT \$(\d+)(?: OFFSET \$(\d+))?", sql_query)+ limit = params[int(bounds.group(1)) - 1]+ offset = params[int(bounds.group(2)) - 1] if bounds.group(2) else 0+ return [+ _session_page_row(session_key, last_activity)+ for session_key, last_activity in sessions[offset : offset + limit]+ ]++ mock_prisma = MagicMock()+ mock_prisma.db = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)+ return mock_prisma+++ @pytest.mark.asyncio+ 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)+++ @pytest.mark.asyncio+ 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)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_group_by_session_jumps_to_page_without_cursor(client, monkeypatch):+ """page > 1 with no session_cursor (the UI's last-page jump) serves the sessions that page starts at."""+ sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(60))+ mock_prisma = _session_grouped_paginating_prisma(sessions)+ 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": 3,+ "page_size": 25,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["page"] == 3+ assert data["total"] == 60+ assert data["has_more"] is False+ assert data["next_session_cursor"] is None+ assert [row["request_id"] for row in data["data"]] == [f"req-sess-{index:02d}" for index in range(50, 60)]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_group_by_session_short_page_totals_itself(client, monkeypatch):+ """A page that runs out of sessions is the end of the list, so the total comes from it and nothing is counted."""+ sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(10))+ mock_prisma = _session_grouped_paginating_prisma(sessions, counted_total=999)+ 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": 1,+ "page_size": 25,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["total"] == 10, "the count query's 999 would have won if it had been asked"+ assert data["total_is_capped"] is False+ assert data["total_pages"] == 1+ assert len(data["data"]) == 10+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_group_by_session_page_past_the_end_keeps_the_real_total(client, monkeypatch):+ """An empty page past the last one says nothing about the total, so it is counted rather than inferred."""+ sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(100))+ mock_prisma = _session_grouped_paginating_prisma(sessions)+ 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": 4,+ "page_size": 50,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["data"] == []+ assert data["total"] == 100, "the empty page's offset is not a total"+ assert data["total_pages"] == 2+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_group_by_session_page_past_count_cap_is_empty(client, monkeypatch):+ """The last page inside the capped total still lists sessions; the page after it is empty and costs no query."""+ cap = spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ sessions = tuple((f"sess-{index:06d}", "2026-08-29 10:00:00") for index in range(cap + 50))+ mock_prisma = _session_grouped_paginating_prisma(sessions)+ 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()+ params = {+ "start_date": start_date,+ "end_date": end_date,+ "group_by_session": "true",+ "page_size": 25,+ }+ last_page = client.get(+ "/spend/logs/ui",+ params={**params, "page": cap // 25},+ headers={"Authorization": "Bearer sk-test"},+ )+ assert last_page.status_code == 200, last_page.text+ last_page_data = last_page.json()+ assert last_page_data["total"] == cap+ assert last_page_data["total_is_capped"] is True+ assert last_page_data["data"][0]["request_id"] == f"req-sess-{cap - 25:06d}"+ assert len(last_page_data["data"]) == 25++ mock_prisma.db.query_raw.reset_mock()+ past_cap = client.get(+ "/spend/logs/ui",+ params={**params, "page": cap // 25 + 1},+ headers={"Authorization": "Bearer sk-test"},+ )+ assert past_cap.status_code == 200, past_cap.text+ past_cap_data = past_cap.json()+ assert past_cap_data["data"] == []+ assert past_cap_data["has_more"] is False+ assert past_cap_data["total"] == cap+ assert mock_prisma.db.query_raw.await_count == 1, "only the bounded count query runs past the capped window"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_group_by_session_last_page_stops_at_the_capped_total(client, monkeypatch):+ """A page size that does not divide the cap still ends the last page at the capped total it reports."""+ cap = spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ sessions = tuple((f"sess-{index:06d}", "2026-08-29 10:00:00") for index in range(cap + 50))+ mock_prisma = _session_grouped_paginating_prisma(sessions)+ 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": cap // 7 + 1,+ "page_size": 7,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["total"] == cap+ assert [row["request_id"] for row in data["data"]] == [+ f"req-sess-{index:06d}" for index in range(cap - cap % 7, cap)+ ]+ assert data["has_more"] is True+ assert data["next_session_cursor"] is not None+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ 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)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_search_returns_flat_rows_when_grouping_by_session(client, monkeypatch):+ """The dashboard lists sessions by default; a search for an id lists every matching row instead,+ so both calls of a session show up rather than one representative, and no session cursor is returned."""+ rows = [_session_representative_row("req-1", "sess-1"), _session_representative_row("req-2", "sess-1")]++ async def mock_query_raw(sql_query, *params):+ if "mcp_tool_call_count" in sql_query:+ return []+ grouped = "DISTINCT ON" in sql_query or "GROUP BY" in sql_query+ visible = rows[:1] if grouped else rows+ if "COUNT(*)" in sql_query:+ return [{"total_count": len(visible)}]+ return visible++ 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)+ 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={+ "search": "sess-1",+ "group_by_session": "true",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert [row["request_id"] for row in data["data"]] == ["req-1", "req-2"]+ assert data["total"] == 2+ assert "next_session_cursor" not in data+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ def _fake_prisma_with_owned_spend_log(owner_user_id, messages_json, response_json):- class _Row:- user = owner_user_id- team_id = None-- class _SpendLogs:- async def find_unique(self, where, include=None):- return _Row()-+ class _DB:- def __init__(self):- self.litellm_spendlogs = _SpendLogs()-- async def query_raw(self, _sql, *_args):++ async def query_raw(self, sql, *_args):++ if 'SELECT DISTINCT "user", team_id' in sql:++ return [{"user": owner_user_id, "team_id": None}]+ return [+ {++ "request_id": "req-owned-by-user-a",+ "messages": messages_json,+ "response": response_json,+ "proxy_server_request": "{}",+ "metadata": "{}",++ "user": owner_user_id,++ "team_id": None,+ }+ ]++ class _Prisma:+ def __init__(self):+ self.db = _DB()++ return _Prisma()+++ def test_ui_view_request_response_internal_user_owner_gets_payload(client, monkeypatch):+ """+ An internal_user who owns the spend-log row can fetch the Logs drawer+ detail payload for their own request (regression for #34099, where the+ route was blocked for INTERNAL_USER before reaching this ownership check).+ """+ messages_json = json.dumps([{"role": "user", "content": "hi"}])+ response_json = json.dumps({"choices": [{"message": {"content": "hello"}}]})+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.prisma_client",+ _fake_prisma_with_owned_spend_log("user_a", messages_json, response_json),+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_a"+ )+ try:+ response = client.get(+ "/spend/logs/ui/req-owned-by-user-a",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ body = response.json()+ assert json.loads(body["messages"]) == [{"role": "user", "content": "hi"}]+ assert json.loads(body["response"]) == {+ "choices": [{"message": {"content": "hello"}}]+ }+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ class _RecordingAdditionalLoggingUtils:+ """Injectable custom logger that records every request_id it's asked for."""++ def __init__(self, payload):+ self._payload = payload+ self.requested_ids = []++ async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):+ self.requested_ids.append(request_id)+ return self._payload+++ def test_ui_view_request_response_internal_user_non_owner_forbidden(client, monkeypatch):+ """+ A different internal_user requesting someone else's row is forbidden;+ guards against _assert_user_can_view_request_id being skipped in the- detail-drawer handler. Also proves the handler stops before it ever asks- a custom logger or the DB for the payload.++ detail-drawer handler. Also proves the handler stops at the owner lookup,++ before it ever asks a custom logger or the DB for the payload.+ """+ messages_json = json.dumps([{"role": "user", "content": "hi"}])+ response_json = json.dumps({"choices": [{"message": {"content": "hello"}}]})+ fake_prisma = _fake_prisma_with_owned_spend_log("user_a", messages_json, response_json)+ original_query_raw = fake_prisma.db.query_raw+ query_raw_calls = []++ async def _spy_query_raw(*args, **kwargs):+ query_raw_calls.append((args, kwargs))+ return await original_query_raw(*args, **kwargs)++ fake_prisma.db.query_raw = _spy_query_raw+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", fake_prisma)++ custom_logger = _RecordingAdditionalLoggingUtils({"messages": "should-not-be-returned"})+ monkeypatch.setattr(+ litellm.logging_callback_manager,+ "get_active_additional_logging_utils_from_custom_logger",+ lambda: [custom_logger],+ )++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_b"+ )+ try:+ response = client.get(+ "/spend/logs/ui/req-owned-by-user-a",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 403+ assert custom_logger.requested_ids == []- assert query_raw_calls == []++ assert [args[0] for args, _kwargs in query_raw_calls if "messages" in args[0]] == []+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ def test_ui_view_request_response_internal_user_missing_row_forbidden(client, monkeypatch):+ """+ Regression for the fail-open in _assert_user_can_view_request_id: a+ request_id with no spend-log row (e.g. pruned by retention) must be+ denied before the handler ever consults a custom logger, otherwise a+ non-admin who guesses/obtains a request_id could read another tenant's- payload out of cold storage. Fails if `if row is None: return` is- reintroduced.++ payload out of cold storage, and an existing payload that is not theirs++ would still confirm the id exists. Even a payload recorded as the caller's++ own is never fetched once the row is gone. Fails if an empty owner lookup++ is allowed to fall through to the loggers.+ """+- class _SpendLogs:- async def find_unique(self, where, include=None):- return None-+ class _DB:- def __init__(self):- self.litellm_spendlogs = _SpendLogs()++ async def query_raw(self, _sql, *_args):++ return []++ from types import SimpleNamespace++ fake_prisma = SimpleNamespace(db=_DB())+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", fake_prisma)+- custom_logger = _RecordingAdditionalLoggingUtils({"messages": "should-not-be-returned"})++ custom_logger = _RecordingAdditionalLoggingUtils(++ {++ "messages": "should-not-be-returned",++ "metadata": {"user_api_key_user_id": "user_a", "user_api_key_team_id": None},++ }++ )+ monkeypatch.setattr(+ litellm.logging_callback_manager,+ "get_active_additional_logging_utils_from_custom_logger",+ lambda: [custom_logger],+ )++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_a"+ )+ try:+ response = client.get(+ "/spend/logs/ui/req-pruned",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 403+ assert custom_logger.requested_ids == []+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pyindex 488ccd8b81b,e9bbaf0c96e..a72b4e28143--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py@@@ -1066,38 -1326,9 +1326,36 @@@ def test_get_logging_payload_includes_aend_time=end_time,)- assert (- payload["agent_id"] == test_agent_id- ), f"Expected agent_id '{test_agent_id}', got '{payload.get('agent_id')}'"+ assert payload["agent_id"] == test_agent_id, f"Expected agent_id '{test_agent_id}', got '{payload.get('agent_id')}'"+def test_get_logging_payload_populates_litellm_call_id_alongside_provider_request_id():+ """+ LIT-6302: request_id stays the provider response id, so clients holding the+ x-litellm-call-id header value could never find their row. The payload now+ also carries litellm_call_id as its own column for lookups by either id.+ """+ call_id = "b980eea9-5cd9-4099-93cd-8291e46c76fd"++ payload = get_logging_payload(+ kwargs={+ "model": "gpt-4o-mini",+ "litellm_call_id": call_id,+ "litellm_params": {"metadata": {"user_api_key": "test-key"}},+ },+ response_obj=litellm.ModelResponse(+ id="chatcmpl-provider-id",+ choices=[],+ usage=litellm.Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2),+ ),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )++ assert payload["request_id"] == "chatcmpl-provider-id"+ assert payload["litellm_call_id"] == call_id++@patch("litellm.proxy.proxy_server.master_key", None)@patch("litellm.proxy.proxy_server.general_settings", {})def test_get_logging_payload_includes_overhead_in_spend_logs_metadata():diff --cc tests/test_litellm/proxy/test_common_request_processing.pyindex 2d1b73aa17a,efbb5eedad4..69e89d1c604--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@@ -7722,14 -8060,440 +8061,453 @@@ def test_log_llm_api_exception_tracebacassert (records[0].exc_info is not None) is expect_traceback+class TestResolveLitellmCallId:+ def test_client_call_id_within_the_bound_is_kept(self):+ assert resolve_litellm_call_id("req-abc-123") == "req-abc-123"+ at_bound: Final = "y" * MAX_LITELLM_CALL_ID_LENGTH+ assert resolve_litellm_call_id(at_bound) == at_bound++ @pytest.mark.parametrize("client_call_id", [None, "", "x" * (MAX_LITELLM_CALL_ID_LENGTH + 1), "z" * 3000])+ def test_missing_empty_or_oversized_client_call_id_gets_a_generated_uuid(self, client_call_id):+ resolved: Final = resolve_litellm_call_id(client_call_id)+ assert resolved != client_call_id+ assert uuid.UUID(resolved).version == 4+++++ class _FailureHookRecorder:+ """Stands in for ProxyLogging.post_call_failure_hook, recording what the detached-failure closure hands it."""++ def __init__(self, raises: Optional[Exception] = None):+ self.calls = []+ self._raises = raises++ async def post_call_failure_hook(self, **kwargs):+ self.calls.append(kwargs)+ if self._raises is not None:+ raise self._raises+++ class TestDetachedStreamFailureHook:+ """+ Regression for LIT-3798. A streaming /v1/messages request whose client disconnected+ before the provider failed mid-stream never reached the proxy's failure hook: the+ client-facing generator was gone, and the detached upstream drain only fired the+ logging object's callbacks, so no failure spend row was written and the budget+ reservation stayed held. base_process_llm_request now arms a closure on the logging+ object that the detached drain awaits, and that closure runs post_call_failure_hook+ with the request's key and data.+ """++ @staticmethod+ def _logging_obj():+ logging_obj = MagicMock()+ logging_obj.litellm_call_id = "call-lit3798"+ logging_obj.model_call_details = {}+ logging_obj._enqueue_deferred_logging = None+ logging_obj._on_deferred_stream_complete = None+ logging_obj._on_detached_stream_failure = None+ return logging_obj++ @staticmethod+ def _proxy_logging_obj(recorder: _FailureHookRecorder):+ proxy_logging_obj = MagicMock(spec=ProxyLogging)+ proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)+ proxy_logging_obj.update_request_status = AsyncMock(return_value=None)+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})+ proxy_logging_obj.post_call_failure_hook = recorder.post_call_failure_hook+ return proxy_logging_obj++ @pytest.mark.asyncio+ async def test_streaming_messages_arms_the_detached_failure_hook(self, monkeypatch):+ import litellm.proxy.common_request_processing as crp+ from litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth++ async def _stream():+ yield b"event: message_start\n\n"++ async def fake_route_request(**kwargs):+ async def _llm_call():+ return _stream()++ return _llm_call()++ monkeypatch.setattr(crp, "route_request", fake_route_request)+ monkeypatch.setattr(litellm, "callbacks", [])+ recorder = _FailureHookRecorder()+ logging_obj = self._logging_obj()+ user_api_key_dict = RealUserAPIKeyAuth(api_key="sk-test")+ processing_obj = ProxyBaseLLMRequestProcessing(+ data={"litellm_logging_obj": logging_obj, "model": "claude-sonnet-4-5"}+ )++ await processing_obj.base_process_llm_request(+ request=MagicMock(spec=Request, headers={}),+ fastapi_response=Response(),+ user_api_key_dict=user_api_key_dict,+ route_type="anthropic_messages",+ proxy_logging_obj=self._proxy_logging_obj(recorder),+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ select_data_generator=None,+ llm_router=None,+ skip_pre_call_logic=True,+ )++ failure = RuntimeError("upstream died after the client left")+ await logging_obj._on_detached_stream_failure(failure)++ assert recorder.calls == [+ {+ "user_api_key_dict": user_api_key_dict,+ "original_exception": failure,+ "request_data": processing_obj.data,+ }+ ]++ @pytest.mark.asyncio+ async def test_detached_failure_hook_drops_the_replacement_error_it_cannot_deliver(self):+ from litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth++ recorder = _FailureHookRecorder(raises=HTTPException(status_code=429, detail="budget exceeded"))+ logging_obj = self._logging_obj()+ processing_obj = ProxyBaseLLMRequestProcessing(data={"litellm_logging_obj": logging_obj})+ processing_obj._arm_detached_stream_failure_hook(+ logging_obj=logging_obj,+ user_api_key_dict=RealUserAPIKeyAuth(api_key="sk-test"),+ proxy_logging_obj=self._proxy_logging_obj(recorder),+ )+ failure = RuntimeError("upstream died after the client left")++ await logging_obj._on_detached_stream_failure(failure)++ assert [call["original_exception"] for call in recorder.calls] == [failure]+++ class TestStreamingResponseHeadersFollowFallback:+ """LIT-6767: the streaming branch has to publish the deployment that served the stream."""++ @staticmethod+ def _fallback_adopting_stream():+ class _Stream:+ def __init__(self) -> None:+ self._hidden_params = {+ "model_id": "failed-deployment",+ "api_base": "http://127.0.0.1:20769/v1",+ "additional_headers": {"llm_provider-stale-marker": "failed-deployment"},+ }+ self.fallback_headers_adopted = False++ def adopt(self) -> None:+ self._hidden_params = {+ "model_id": "served-deployment",+ "api_base": "https://api.openai.com",+ "additional_headers": {"llm_provider-x-request-id": "req-SERVED"},+ }+ self.fallback_headers_adopted = True++ return _Stream()++ @pytest.mark.asyncio+ async def test_streaming_headers_name_the_deployment_that_served(self, monkeypatch):+ """A pre-first-chunk fallback repoints the stream while the headers are still+ uncommitted, so the published headers must describe the fallback, not the attempt+ the Router picked first."""+ stream = self._fallback_adopting_stream()++ def select_data_generator(**kwargs):+ async def generator():+ stream.adopt()+ yield 'data: {"choices": [{"delta": {"content": "OK"}}]}\n\n'+ yield "data: [DONE]\n\n"++ return generator()++ logging_obj = MagicMock()+ logging_obj.litellm_call_id = "lit-6767-call"+ logging_obj._defer_async_logging = False+ logging_obj._on_deferred_stream_complete = None+ logging_obj.cost_breakdown = None++ processor = ProxyBaseLLMRequestProcessing(+ data={"model": "oa-midfail", "stream": True, "litellm_logging_obj": logging_obj}+ )++ proxy_logging_obj = MagicMock(spec=ProxyLogging)+ proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)+ proxy_logging_obj.update_request_status = AsyncMock(return_value=None)+ proxy_logging_obj.post_call_success_hook = AsyncMock(+ side_effect=lambda data, user_api_key_dict, response: response+ )+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(+ return_value={"x-callback-header": "kept"}+ )++ async def fake_route_request(**kwargs):+ async def call():+ return stream++ return call()++ monkeypatch.setattr(+ litellm.proxy.common_request_processing, "route_request", fake_route_request+ )++ result = await processor.base_process_llm_request(+ request=Request(scope={"type": "http", "headers": []}),+ fastapi_response=Response(),+ user_api_key_dict=ProxyUserAPIKeyAuth(api_key="sk-test"),+ route_type="acompletion",+ proxy_logging_obj=proxy_logging_obj,+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ select_data_generator=select_data_generator,+ is_streaming_request=True,+ skip_pre_call_logic=True,+ )++ assert isinstance(result, StreamingResponse)+ assert result.headers["x-litellm-model-id"] == "served-deployment"+ assert result.headers["x-litellm-model-api-base"] == "https://api.openai.com"+ assert result.headers["llm_provider-x-request-id"] == "req-SERVED"+ assert "llm_provider-stale-marker" not in result.headers+ assert result.headers["x-callback-header"] == "kept"+++ class _MessagesFallbackStream:+ def __init__(self) -> None:+ self.fallback_headers_adopted = False+ self._hidden_params: dict[str, object] = {+ "additional_headers": {+ "x-litellm-complexity-router-tier": "REASONING",+ "x-litellm-complexity-router-reasoning-effort": "xhigh",+ }+ }+ self._chunks = iter(+ (+ b'event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"OK"}}\n\n',+ )+ )++ def __aiter__(self) -> "_MessagesFallbackStream":+ return self++ async def __anext__(self) -> bytes:+ self._hidden_params = {+ "model_id": "fallback-deployment",+ "additional_headers": {"x-fallback-only": "yes"},+ }+ self.fallback_headers_adopted = True+ try:+ return next(self._chunks)+ except StopIteration:+ raise StopAsyncIteration from None++ async def aclose(self) -> None:+ return None+++ @pytest.mark.asyncio+ async def test_messages_http_headers_refresh_after_lazy_fallback(monkeypatch: pytest.MonkeyPatch) -> None:+ from litellm.caching.caching import DualCache++ stream = _MessagesFallbackStream()+ logging_obj = MagicMock()+ logging_obj.litellm_call_id = "messages-fallback-headers"+ logging_obj._defer_async_logging = False+ logging_obj._on_deferred_stream_complete = None+ logging_obj.cost_breakdown = None+ logging_obj.litellm_params = {}+ processor = ProxyBaseLLMRequestProcessing(+ data={"model": "auto-router", "stream": True, "litellm_logging_obj": logging_obj}+ )+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ monkeypatch.setattr(litellm, "callbacks", [])++ async def call() -> _MessagesFallbackStream:+ return stream++ async def fake_route_request(**_kwargs: object) -> object:+ return call()++ monkeypatch.setattr(litellm.proxy.common_request_processing, "route_request", fake_route_request)+ response = await processor.base_process_llm_request(+ request=Request(scope={"type": "http", "headers": []}),+ fastapi_response=Response(),+ user_api_key_dict=ProxyUserAPIKeyAuth(api_key="sk-test"),+ route_type="anthropic_messages",+ proxy_logging_obj=proxy_logging_obj,+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ is_streaming_request=True,+ skip_pre_call_logic=True,+ )++ assert isinstance(response, StreamingResponse)+ assert stream.fallback_headers_adopted is True+ assert response.headers["x-litellm-model-id"] == "fallback-deployment"+ assert response.headers["x-fallback-only"] == "yes"+ assert "x-litellm-complexity-router-tier" not in response.headers+ assert "x-litellm-complexity-router-reasoning-effort" not in response.headers+++ class TestPassthroughHeadersAcceptImmutableMappings:+ """LIT-6767: the streaming branch now hands the passthrough helpers an immutable mapping."""++ def test_merge_passthrough_streaming_headers_accepts_a_read_only_mapping(self):+ merged = ProxyBaseLLMRequestProcessing._merge_passthrough_streaming_headers(+ response_headers=httpx.Headers({"content-type": "text/event-stream", "transfer-encoding": "chunked"}),+ custom_headers=MappingProxyType({"x-litellm-model-id": "served-deployment"}),+ )++ assert merged["x-litellm-model-id"] == "served-deployment"+ assert merged["content-type"] == "text/event-stream"+ # the excluded hop-by-hop header is still dropped+ assert "transfer-encoding" not in merged+++ @pytest.mark.asyncio+ async def test_handle_llm_api_exception_forwards_provider_headers_on_http_status_error():+ """The httpx.HTTPStatusError branch dropped the headers its sibling branches forward.++ A Bedrock passthrough failure reaches this branch, so the request id was gone+ before the client saw the response.+ """+ import httpx++ from litellm.proxy._types import UserAPIKeyAuth++ request = httpx.Request("POST", "https://bedrock-runtime.us-east-1.amazonaws.com/model/m/converse")+ response = httpx.Response(+ status_code=500,+ headers={"x-amzn-RequestId": "req-passthrough-500"},+ content=b'{"message": "Amazon Bedrock is unable to process your request."}',+ request=request,+ )++ processor = ProxyBaseLLMRequestProcessing(data={})+ proxy_logging_obj = MagicMock()+ proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})++ with pytest.raises(HTTPException) as exc_info:+ await processor._handle_llm_api_exception(+ e=httpx.HTTPStatusError("boom", request=request, response=response),+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test"),+ proxy_logging_obj=proxy_logging_obj,+ )++ assert exc_info.value.headers is not None+ assert exc_info.value.headers["llm_provider-x-amzn-requestid"] == "req-passthrough-500"+++ class TestBackgroundResponseRetrievalGovernance:+ """LIT-7175: retrieving a background Response attaches the model's post_call policy pipelines."""++ GOVERNED_MODEL_GROUP = "gpt-5.4-mini"+ GOVERNED_MODEL_ID = "deployment-governed"++ @pytest.fixture+ def policy_engine(self) -> Iterator[None]:+ from litellm.proxy.policy_engine.attachment_registry import get_attachment_registry+ from litellm.proxy.policy_engine.policy_registry import get_policy_registry++ get_policy_registry().load_policies(+ {+ "response-governance": {+ "guardrails": {"add": ["output-word-filter"]},+ "pipeline": {+ "mode": "post_call",+ "steps": [{"guardrail": "output-word-filter", "on_pass": "allow", "on_fail": "block"}],+ },+ }+ }+ )+ get_attachment_registry().load_attachments(+ [{"policy": "response-governance", "models": [self.GOVERNED_MODEL_GROUP]}]+ )+ yield+ get_policy_registry().clear()+ get_attachment_registry().clear()++ def _router(self) -> MagicMock:+ from litellm.types.router import Deployment, LiteLLM_Params++ router = MagicMock()+ router.get_deployment.side_effect = lambda model_id: (+ Deployment(+ model_name=self.GOVERNED_MODEL_GROUP,+ litellm_params=LiteLLM_Params(model=f"openai/{self.GOVERNED_MODEL_GROUP}"),+ model_info={"id": model_id},+ )+ if model_id == self.GOVERNED_MODEL_ID+ else None+ )+ return router++ async def _pre_call(self, route_type: str, monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:+ from litellm.responses.utils import ResponsesAPIRequestUtils++ client_facing_response_id = "resp_opaque-client-facing-id"+ encoded_response_id = ResponsesAPIRequestUtils._build_responses_api_response_id(+ custom_llm_provider="openai", model_id=self.GOVERNED_MODEL_ID, response_id="resp_upstream"+ )+ processing_obj = ProxyBaseLLMRequestProcessing(+ data={"response_id": client_facing_response_id, "litellm_metadata": {}}+ )+ mock_request = MagicMock(spec=Request)+ mock_request.headers = {}++ async def passthrough_add_litellm_data_to_request(+ data: dict[str, object], **kwargs: object+ ) -> dict[str, object]:+ return data++ async def decrypting_pre_call_hook(+ user_api_key_dict: ProxyUserAPIKeyAuth, data: dict[str, object], call_type: str+ ) -> dict[str, object]:+ if data.get("response_id") == client_facing_response_id:+ data["response_id"] = encoded_response_id+ return data++ monkeypatch.setattr(+ litellm.proxy.common_request_processing,+ "add_litellm_data_to_request",+ passthrough_add_litellm_data_to_request,+ )+ proxy_logging_obj = MagicMock(spec=ProxyLogging)+ proxy_logging_obj.pre_call_hook = AsyncMock(side_effect=decrypting_pre_call_hook)+ proxy_config = MagicMock(spec=ProxyConfig)+ proxy_config._get_hierarchical_router_settings = AsyncMock(return_value=None)+ returned_data, _ = await processing_obj.common_processing_pre_call_logic(+ request=mock_request,+ general_settings={},+ user_api_key_dict=ProxyUserAPIKeyAuth(),+ proxy_logging_obj=proxy_logging_obj,+ proxy_config=proxy_config,+ route_type=route_type,+ llm_router=self._router(),+ )+ return returned_data++ @pytest.mark.asyncio+ async def test_retrieving_a_background_response_attaches_its_model_post_call_pipeline(+ self, policy_engine: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ data = await self._pre_call("aget_responses", monkeypatch)++ assert data["response_id"].startswith("resp_bGl0ZWxsbTpjdXN0b21f")+ pipelines = data["litellm_metadata"]["_guardrail_pipelines"]+ assert [(policy_name, [step.guardrail for step in pipeline.steps]) for policy_name, pipeline in pipelines] == [+ ("response-governance", ["output-word-filter"])+ ]+ assert data["litellm_metadata"]["applied_policies"] == ["response-governance"]+ assert data["model"] is None++ @pytest.mark.asyncio+ async def test_submitting_a_response_does_not_attach_pipelines_from_its_response_id(+ self, policy_engine: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ data = await self._pre_call("aresponses", monkeypatch)++ assert "_guardrail_pipelines" not in data["litellm_metadata"]+ assert "applied_policies" not in data["litellm_metadata"]diff --cc ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsxindex a138eecdd6c,4f39bb3b79b..0b5e5ff9616--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx@@@ -24,11 -26,8 +26,11 @@@ import { LogDetailsDrawer } from "./Logimport { LiveTailBanner, LogsTableToolbar } from "./LogsTableToolbar";import { RequestLogsTable } from "./RequestLogsTable";- const PAGE_SIZE = LOGS_PAGE_SIZE_OPTIONS[0];+ const PAGE_SIZE = DEFAULT_PAGE_SIZE_OPTIONS[0];const DEFAULT_INTERVAL = { value: 24, unit: "hours" };+const matchesLogId = (log: LogEntry, logId: string) => log.request_id === logId || log.litellm_call_id === logId;+const findLogById = (logs: readonly LogEntry[], logId: string): LogEntry | null =>+ logs.find((log) => log.request_id === logId) ?? logs.find((log) => log.litellm_call_id === logId) ?? null;interface RequestLogsPanelProps {accessToken: string;