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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_spend_log_request_id_call_id

mateo-berri0c2be34fb13b
diff --cc litellm/proxy/spend_tracking/spend_management_endpoints.py
index 102047380be,bb7dfafb297..499b200a160
--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py
+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py
@@@ -2699,13 -2662,29 +2692,30 @@@ async def ui_view_spend_logs
cache_hit, cache_key, request_tags, team_id,
organization_id, end_user, requester_ip_address,
session_id, status, mcp_namespaced_tool_name, agent_id,
+ litellm_call_id,
- COALESCE(request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER) AS request_duration_ms
+ 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}
+ FROM "LiteLLM_SpendLogs"
+ WHERE {joined_conditions}
+ ORDER BY {_SESSION_GROUP_KEY_SQL}, call_type IN {_MCP_CALL_TYPES_SQL}, "startTime" DESC
+ ) AS session_representatives
- ORDER BY {_order_expr} {_sql_dir}{_nulls_clause}, request_id
++ ORDER BY {exact_request_id_first}{_order_expr} {_sql_dir}{_nulls_clause}, request_id
+ LIMIT ${p} OFFSET ${p + 1}
+ """
+ if session_grouping
+ else f"""
+ SELECT
+ {select_columns}
FROM "LiteLLM_SpendLogs"
- WHERE {" AND ".join(sql_conditions)}
+ 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}
"""
+ )
sql_params.extend([page_size, skip])
data: Final = await prisma_client.db.query_raw(sql_query, *sql_params)
diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 8db2b301725,30b086bab61..3b4c1e662fa
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
@@@ -2854,68 -2281,13 +2854,70 @@@ async def test_ui_view_request_response
@pytest.mark.asyncio
- async def test_ui_view_spend_logs_id_lookup_lists_exact_request_id_row_first(client, monkeypatch):
-async def test_ui_view_spend_logs_request_id_owner_scoped_by_id_only(
[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."""
++ 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},
++ 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)
+
+
+async def test_ui_view_spend_logs_request_id_owner_lookup_drops_window_keeps_scope(
client, monkeypatch
):
- """A non-admin owner looking up their own request_id resolves across all time.
- The ownership check authorizes the single row, so the query drops both the date
- window and the general user/team scoping and filters by the primary key alone;
- without that skip an internal user would have a `user`/`OR` clause added."""
+ """A non-admin owner looking up their own request_id resolves across all time:
+ the query drops the date window the dashboard sends, while the caller's own-user
+ scope stays on the id lookup so a colliding foreign row can never be served."""
today = datetime.datetime.now(timezone.utc)
mock_spend_logs = [
{
diff --cc ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
index 6673808981f,c368a43dd1e..a85b06b790f
--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx
@@@ -296,51 -302,9 +302,52 @@@ describe("RequestLogsPanel", () =>
if (!byIdCall) throw new Error("expected a by-id uiSpendLogsCall");
expect(byIdCall.page).toBe(1);
expect(byIdCall.page_size).toBe(1);
+ expect(byIdCall.params?.group_by_session).toBeUndefined();
});
+ it("opens the drawer when ?log_id= is the log's litellm_call_id rather than its request_id", async () => {
+ respondWith([logEntry({ request_id: "chatcmpl-provider", litellm_call_id: "call-1" })]);
+ renderPanel("?log_id=call-1");
+
+ await waitFor(() => {
+ expect(drawer()).toHaveTextContent("open");
+ });
+ expect(drawer()).toHaveAttribute("data-log-id", "chatcmpl-provider");
+ });
+
+ it("fetches by litellm_call_id and opens the drawer when that log is not in the loaded page", async () => {
+ vi.mocked(uiSpendLogsCall).mockImplementation(async ({ params }) =>
+ params?.request_id === "call-old"
+ ? {
+ data: [logEntry({ request_id: "chatcmpl-old", litellm_call_id: "call-old" })],
+ total: 1,
+ page: 1,
+ page_size: 1,
+ total_pages: 1,
+ }
+ : { data: [], total: 0, page: 1, page_size: 50, total_pages: 0 },
+ );
+ renderPanel("?log_id=call-old");
+
+ await waitFor(() => {
+ expect(drawer()).toHaveTextContent("open");
+ });
+ 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 --cc ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
index 2f67320fa59,2ebabf64ab0..a138eecdd6c
--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx
@@@ -24,11 -24,8 +24,11 @@@ import { LogDetailsDrawer } from "./Log
import { LiveTailBanner, LogsTableToolbar } from "./LogsTableToolbar";
import { RequestLogsTable } from "./RequestLogsTable";
- const PAGE_SIZE = 50;
+ const PAGE_SIZE = LOGS_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;