Skip to content

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]

fix(spend_logs): resolve the caller's own row before cold storage and list the exact request_id row first

mateo-berria196a504509b
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py
index a1f259861e3..102047380be 100644
--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py
+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py
@@ -2586,6 +2586,7 @@ async def ui_view_spend_logs(
p += 1
request_id_filter: Final = where_conditions.get("request_id")
+ exact_request_id_first: Final = f"(request_id = ${p}) DESC, " if isinstance(request_id_filter, str) else ""
if isinstance(request_id_filter, str):
sql_conditions.append(f"(request_id = ${p} OR litellm_call_id = ${p})")
sql_params.append(request_id_filter)
@@ -2702,7 +2703,7 @@ async def ui_view_spend_logs(
COALESCE(request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER) AS request_duration_ms
FROM "LiteLLM_SpendLogs"
WHERE {" AND ".join(sql_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}
"""
sql_params.extend([page_size, skip])
@@ -2895,9 +2896,21 @@ async def ui_view_request_response_for_request_id(
if end_date is not None:
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
+ spend_log_row: Final = (
+ None
+ if prisma_client is None
+ else await _resolve_spend_log_payload_row(
+ prisma_client=prisma_client,
+ user_api_key_dict=user_api_key_dict,
+ request_id=request_id,
+ caller_is_admin=caller_is_admin,
+ )
+ )
+ stored_request_id: Final = _stored_request_id(spend_log_row, request_id)
+
for custom_logger in custom_loggers:
payload = await custom_logger.get_request_response_payload(
- request_id=request_id,
+ request_id=stored_request_id,
start_time_utc=start_date_obj,
end_time_utc=end_date_obj,
)
@@ -2911,32 +2924,17 @@ async def ui_view_request_response_for_request_id(
)
return payload
+ if spend_log_row is None:
+ return None
+
# Fallback: the list endpoint omits the heavy columns for performance, so
# serve them here. When prompts were offloaded to cold storage the DB holds
# only placeholders, so _resolve_request_response_payload fetches the real
# payload from the configured cold storage backend by object key.
- if prisma_client is not None:
- from litellm.proxy.spend_tracking.cold_storage_handler import (
- ColdStorageHandler,
- )
-
- 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)
- db_result: Final[Sequence[Mapping[str, object]] | None] = await _query_raw_or_none(
- prisma_client, sql_query, *sql_params
- )
- if db_result and len(db_result) > 0:
- if not caller_is_admin:
- await _assert_user_owns_fetched_spend_rows(
- prisma_client=prisma_client,
- user_api_key_dict=user_api_key_dict,
- rows=db_result,
- request_id=request_id,
- )
- resolved = await _resolve_request_response_payload(db_result[0], cold_storage_handler=ColdStorageHandler())
- return resolved._asdict()
+ from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler
- return None
+ resolved: Final = await _resolve_request_response_payload(spend_log_row, cold_storage_handler=ColdStorageHandler())
+ return resolved._asdict()
@router.get(
@@ -4412,7 +4410,7 @@ def _spend_log_payload_query(request_id: str, viewer: _SpendLogViewer | None) ->
scope, scope_params = _viewer_scope_clause(viewer)
return (
f"""
- SELECT messages, response, proxy_server_request, metadata, "user", team_id
+ 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
@@ -4422,6 +4420,39 @@ def _spend_log_payload_query(request_id: str, viewer: _SpendLogViewer | None) ->
)
+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,
+ rows=rows,
+ request_id=request_id,
+ )
+ return rows[0]
+
+
+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")
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.py
index 5d677bcdde3..8db2b301725 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
@@ -199,7 +199,13 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=No
return [{"total_count": min(total, cap_plus_one)}]
page_size = params[-2] if len(params) >= 2 else 50
skip = params[-1] if len(params) >= 1 else 0
- return [row for row in filtered[skip : skip + page_size]]
+ exact_first = re.search(r"ORDER BY \(request_id = \$(\d+)\) DESC", sql_query)
+ ordered = (
+ sorted(filtered, key=lambda row: row["request_id"] == params[int(exact_first.group(1)) - 1], reverse=True)
+ if exact_first
+ else filtered
+ )
+ return [row for row in ordered[skip : skip + page_size]]
class MockPrismaClient:
def __init__(self):
@@ -2796,6 +2802,113 @@ async def test_ui_view_request_response_custom_logger_allows_own_payload_without
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)
+
+
+async def test_ui_view_spend_logs_id_lookup_lists_exact_request_id_row_first(client, monkeypatch):
+ """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."""
+ 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},
+ 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)
+
+
@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_owner_lookup_drops_window_keeps_scope(
client, monkeypatch
diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
index 4f788e180d2..6673808981f 100644
--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
@@ -328,6 +328,19 @@ describe("RequestLogsPanel", () => {
expect(drawer()).toHaveAttribute("data-log-id", "chatcmpl-old");
});
+ it("opens the exact request_id row when another log in the page carries that id as its litellm_call_id", async () => {
+ respondWith([
+ logEntry({ request_id: "chatcmpl-other", litellm_call_id: "victim-req" }),
+ logEntry({ request_id: "victim-req", litellm_call_id: "victim-call" }),
+ ]);
+ renderPanel("?log_id=victim-req");
+
+ await waitFor(() => {
+ expect(drawer()).toHaveTextContent("open");
+ });
+ expect(drawer()).toHaveAttribute("data-log-id", "victim-req");
+ });
+
it("closing the drawer removes ?log_id= from the URL and closes the drawer", async () => {
const user = userEvent.setup();
respondWith([logEntry({ request_id: "req-1" })]);
diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
index cf73b695044..2f67320fa59 100644
--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
@@ -27,6 +27,8 @@ import { RequestLogsTable } from "./RequestLogsTable";
const PAGE_SIZE = 50;
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;
@@ -134,7 +136,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
page_size: 1,
params: { request_id: urlLogId },
});
- return response.data.find((log) => matchesLogId(log, urlLogId)) ?? null;
+ return findLogById(response.data, urlLogId);
},
enabled: urlLogId !== null && !(selectedLog !== null && matchesLogId(selectedLog, urlLogId)),
staleTime: Infinity,
@@ -145,7 +147,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
const displayLog = useMemo<LogEntry | null>(() => {
if (urlLogId === null) return null;
if (selectedLog !== null && matchesLogId(selectedLog, urlLogId)) return selectedLog;
- return filteredLogs.data.find((log) => matchesLogId(log, urlLogId)) ?? urlLog ?? null;
+ return findLogById(filteredLogs.data, urlLogId) ?? urlLog ?? null;
}, [urlLogId, selectedLog, filteredLogs.data, urlLog]);
const displaySessionId = useMemo<string | null>(() => {