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 remote-tracking branch 'origin/main' into litellm_session_total_duration
mateo-berri3441f73118a3
diff --cc litellm/proxy/spend_tracking/spend_management_endpoints.pyindex d49bd6eb912,0ec2788fbaa..a319535f725--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@@ -43,9 -61,324 +61,326 @@@ if TYPE_CHECKINGelse:PrismaClient = Any- router = APIRouter()+ router: Final = APIRouter()++ SPEND_LOGS_PAGINATION_COUNT_CAP: Final = 10000++ _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,+ hash_token(token=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME),+ )++ _RowT = TypeVar("_RowT")+++ class _SupportsModelDump(Protocol):+ def model_dump(self) -> Mapping[str, object]: ...+++ class _SpendLogOwnerRow(TypedDict):+ user: ReadOnly[str | None]+ team_id: ReadOnly[str | None]+++ class _ActivityRow(TypedDict):+ date: str+ api_requests: int+ total_tokens: int+++ class _ActivityModelRow(TypedDict):+ model_group: str+ date: str+ api_requests: int+ total_tokens: int+++ class _DeploymentExceptionsRow(TypedDict):+ api_base: str+ date: str+ num_rate_limit_exceptions: int+++ class _ExceptionsRow(TypedDict):+ date: str+ num_rate_limit_exceptions: int+++ class _ModelIdSpendRow(TypedDict):+ model_id: str+ spend: float+++ class _TagNameRow(TypedDict):+ individual_request_tag: str+++ class _TeamSpendRow(TypedDict):+ team_alias: str | None+ total_spend: float+++ class _TagSpendRow(TypedDict):+ individual_request_tag: str+ total_spend: float+++ class _SpendLogsCountRow(TypedDict):+ total_count: int+++ class _PgClassRow(TypedDict):+ relname: str+ relkind: str+++ class _TotalSpendRow(TypedDict):+ total_spend: float+++ class _TeamDailySpendRow(TypedDict):+ team_alias: str | None+ spend_date: str | None+ total_spend: float+++ class _EndUserRow(TypedDict):+ end_user: str | None+++ class _DailyTagSpendRow(TypedDict):+ individual_request_tag: str+ log_count: int+ total_spend: float+++ class _SessionSpendRow(TypedDict):+ session_id: str+ api_key: ReadOnly[str]+ session_total_count: ReadOnly[int]+ session_total_spend: float++ session_total_duration_ms: ReadOnly[int]+ mcp_tool_call_count: int+ mcp_tool_call_spend: float+ session_cache_hit_count: ReadOnly[int]+ session_llm_count: ReadOnly[int]+ session_agent_count: ReadOnly[int]+ session_total_prompt_tokens: ReadOnly[int]+ session_total_completion_tokens: ReadOnly[int]+ session_total_tokens: ReadOnly[int]+ session_models: ReadOnly[Sequence[str]]+++ _SESSION_MODELS_LIMIT: Final = 10+ _SESSION_MODEL_NAME_MAX_LEN: Final = 256+++ class _SessionSpendStats(NamedTuple):+ session_total_count: int+ session_total_spend: float++ session_total_duration_ms: int+ mcp_tool_call_count: int+ mcp_tool_call_spend: float+ session_cache_hit_count: int+ session_llm_count: int+ session_agent_count: int+ session_total_prompt_tokens: int+ session_total_completion_tokens: int+ session_total_tokens: int+ session_models: Sequence[str]+ session_models_truncated: bool+++ _SessionSpendMap: TypeAlias = Mapping[tuple[str, str], _SessionSpendStats]+++ class _SpendDailySummaryRow(TypedDict):+ day: ReadOnly[str]+ api_key: ReadOnly[str]+ user: ReadOnly[str | None]+ model: ReadOnly[str]+ spend: ReadOnly[float]+++ async def _query_raw(prisma_client: PrismaClient, sql_query: str, *args: object) -> Sequence[_RowT]:+ """Run a raw read query and return its rows as the row type the caller declares."""+ return await prisma_client.db.query_raw(sql_query, *args)+++ async def _query_raw_or_none(prisma_client: PrismaClient, sql_query: str, *args: object) -> Sequence[_RowT] | None:+ """``_query_raw`` for the call sites that guard the result against ``None``."""+ return await _query_raw(prisma_client, sql_query, *args)+- SPEND_LOGS_PAGINATION_COUNT_CAP = 10000+ class _TeamTable(Protocol):+ """The subset of the Prisma team table API this module uses."""++ async def find_unique(self, *, where: Mapping[str, object]) -> _SupportsModelDump | None: ...++ async def find_many(self, *, where: Mapping[str, object]) -> Sequence[_SupportsModelDump]: ...++ async def update_many(self, *, data: Mapping[str, float], where: Mapping[str, object]) -> int: ...+++ class _VerificationTokenTable(Protocol):+ """The subset of the Prisma verification token table API this module uses."""++ async def update_many(self, *, data: Mapping[str, float], where: Mapping[str, object]) -> int: ...+++ def _spend_logs_table(prisma_client: PrismaClient) -> TableActions["prisma_models.LiteLLM_SpendLogs"]:+ return SpendLogsRepository(prisma_client).table+++ def _team_table(prisma_client: PrismaClient) -> _TeamTable:+ return TeamRepository(prisma_client).table+++ def _verification_token_table(prisma_client: PrismaClient) -> _VerificationTokenTable:+ return VerificationTokenRepository(prisma_client).table+++ def _spend_logs_daily_summary_sql(+ *,+ start_date_iso: str,+ end_date_iso: str,+ api_key: str | None,+ request_id: str | None,+ user_id: str | None,+ ) -> tuple[str, tuple[object, ...]]:+ filter_params: Final[tuple[tuple[str, object], ...]] = tuple(+ (column, value)+ for column, value in (+ ("api_key", api_key),+ ("request_id", request_id),+ ('"user"', user_id),+ )+ if value is not None+ )+ filter_clauses: Final[tuple[str, ...]] = tuple(+ f"AND {column} = ${index}" for index, (column, _) in enumerate(filter_params, start=3)+ )+ filter_sql: Final = "\n".join(filter_clauses)+ sql_query: Final = f"""+ SELECT+ to_char(date_trunc('day', "startTime"), 'YYYY-MM-DD') AS day,+ api_key,+ "user",+ model,+ SUM(spend) AS spend+ FROM "LiteLLM_SpendLogs"+ WHERE "startTime" >= ($1::timestamptz AT TIME ZONE 'UTC') AND "startTime" <= ($2::timestamptz AT TIME ZONE 'UTC')+ {filter_sql}+ GROUP BY 1, 2, 3, 4+ ORDER BY 1+ """+ params: Final[tuple[object, ...]] = (+ start_date_iso,+ end_date_iso,+ *(value for _, value in filter_params),+ )+ return sql_query, params+++ def _sum_spend_by(+ rows: Sequence[_SpendDailySummaryRow], column: Literal["api_key", "user", "model"]+ ) -> Mapping[str | None, float]:+ keys: Final = frozenset(row[column] for row in rows)+ return {key: sum(float(row["spend"]) for row in rows if row[column] == key) for key in keys}+++ def _daily_summary_item(summary_date: date, rows: Sequence[_SpendDailySummaryRow]) -> Mapping[str, object]:+ api_key_spend: Final = {key: value for key, value in _sum_spend_by(rows, "api_key").items() if key is not None}+ return {+ **api_key_spend,+ "startTime": summary_date,+ "spend": sum(float(row["spend"]) for row in rows),+ "users": _sum_spend_by(rows, "user"),+ "models": _sum_spend_by(rows, "model"),+ }+++ async def _find_spend_logs(+ prisma_client: PrismaClient,+ where: Mapping[str, object],+ order: Mapping[str, str],+ take: int,+ http_response: Response,+ ) -> Sequence[_SupportsModelDump]:+ """Read spend log rows as Prisma model instances, capped at ``take`` rows."""+ rows: Final = await _spend_logs_table(prisma_client).find_many(where=where, order=order, take=take)+ if len(rows) == take:+ http_response.headers["x-litellm-spend-logs-truncated"] = "true"+ verbose_proxy_logger.warning(+ "/spend/logs result truncated to the %s most recent rows; use /spend/logs/v2 for paginated access",+ take,+ )+ return rows+++ class _RequestIdEquals(TypedDict):+ request_id: ReadOnly[str]+++ class _LitellmCallIdEquals(TypedDict):+ litellm_call_id: ReadOnly[str]+++ def _request_id_or_call_id_clause(request_id: str) -> tuple[_RequestIdEquals, _LitellmCallIdEquals]:+ request_id_clause: Final[_RequestIdEquals] = {"request_id": request_id}+ call_id_clause: Final[_LitellmCallIdEquals] = {"litellm_call_id": request_id}+ return (request_id_clause, call_id_clause)+++ async def _find_spend_log_owners(prisma_client: PrismaClient, request_id: str) -> Sequence[_SpendLogOwnerRow]:+ """Read the distinct ``(user, team_id)`` owner pairs across every spend log row+ identified by ``request_id`` or ``litellm_call_id``.++ ``litellm_call_id`` is populated from the client-settable ``x-litellm-call-id``+ request header, so it is not guaranteed unique to one tenant: any number of rows+ can match one id. The read is uncapped because a flood of another tenant's rows+ carrying the caller's id could otherwise push the caller's own owner pair past a+ row-sample cap and lock them out of their own lookup.+ """+ sql_query: Final = """+ SELECT DISTINCT "user", team_id+ FROM "LiteLLM_SpendLogs"+ WHERE request_id = $1 OR litellm_call_id = $1+ """+ owners: Final[Sequence[_SpendLogOwnerRow] | None] = await _query_raw_or_none(prisma_client, sql_query, request_id)+ return owners if owners is not None else ()+++ async def _count_spend_logs(prisma_client: PrismaClient, where: Mapping[str, object]) -> int:+ """Count the spend log rows matching ``where``."""+ return await _spend_logs_table(prisma_client).count(where=where)+++ async def _find_team_row(prisma_client: PrismaClient, team_id: str) -> _SupportsModelDump | None:+ """Read a single team row as a Prisma model instance."""+ return await _team_table(prisma_client).find_unique(where={"team_id": team_id})+++ async def _find_team_rows(prisma_client: PrismaClient, team_ids: Sequence[str]) -> Sequence[_SupportsModelDump]:+ """Read team rows as Prisma model instances."""+ return await _team_table(prisma_client).find_many(where={"team_id": {"in": team_ids}})@router.get(@@@ -3454,42 -4532,72 +4534,79 @@@ async def _build_ui_spend_logs_response{(row.get("api_key") if isinstance(row, dict) else getattr(row, "api_key", None))for row in data- if (row.get("api_key") if isinstance(row, dict) else getattr(row, "api_key", None))+ if (row.get("api_key") if isinstance(row, dict) else getattr(row, "api_key", None)) is not None})- rows = await prisma_client.db.query_raw(- """- SELECT session_id,- COALESCE(SUM(spend), 0)::double precision AS session_total_spend,- COALESCE(SUM(- COALESCE(- request_duration_ms,- (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER- )- ), 0)::double precision AS session_total_duration_ms,- COUNT(*) FILTER (- WHERE call_type IN ('call_mcp_tool', 'list_mcp_tools')- )::int AS mcp_tool_call_count,- COALESCE(SUM(spend) FILTER (- WHERE call_type IN ('call_mcp_tool', 'list_mcp_tools')- ), 0)::double precision AS mcp_tool_call_spend- FROM "LiteLLM_SpendLogs"- WHERE session_id = ANY($1::text[])- AND api_key = ANY($2::text[])- GROUP BY session_id+ rows: Final[Sequence[_SessionSpendRow]] = await _query_raw(+ prisma_client,+ f"""+ SELECT s.*, COALESCE(m.session_models, ARRAY[]::text[]) AS session_models+ FROM (+ SELECT session_id, api_key,+ COUNT(*)::int AS session_total_count,+ COALESCE(SUM(spend), 0)::double precision AS session_total_spend,++ COALESCE(SUM(++ COALESCE(++ request_duration_ms,++ (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER++ )++ ), 0)::bigint AS session_total_duration_ms,+ COUNT(*) FILTER (+ WHERE call_type IN {_MCP_CALL_TYPES_SQL}+ )::int AS mcp_tool_call_count,+ COALESCE(SUM(spend) FILTER (+ WHERE call_type IN {_MCP_CALL_TYPES_SQL}+ ), 0)::double precision AS mcp_tool_call_spend,+ COUNT(*) FILTER (WHERE LOWER(cache_hit) = 'true')::int AS session_cache_hit_count,+ COUNT(*) FILTER (+ WHERE call_type NOT IN {_MCP_CALL_TYPES_SQL} AND call_type != {_AGENT_CALL_TYPE_SQL}+ )::int AS session_llm_count,+ COUNT(*) FILTER (WHERE call_type = {_AGENT_CALL_TYPE_SQL})::int AS session_agent_count,+ COALESCE(SUM(prompt_tokens), 0)::bigint AS session_total_prompt_tokens,+ COALESCE(SUM(completion_tokens), 0)::bigint AS session_total_completion_tokens,+ COALESCE(SUM(total_tokens), 0)::bigint AS session_total_tokens+ FROM "LiteLLM_SpendLogs"+ WHERE session_id = ANY($1::text[])+ AND api_key = ANY($2::text[])+ GROUP BY session_id, api_key+ ) s+ LEFT JOIN LATERAL (+ SELECT ARRAY_AGG(d.model ORDER BY d.model) AS session_models+ FROM (+ SELECT DISTINCT LEFT(model, $3::int) AS model+ FROM "LiteLLM_SpendLogs"+ WHERE session_id = s.session_id+ AND api_key = s.api_key+ AND model IS NOT NULL AND model <> ''+ ORDER BY 1+ LIMIT $4::int+ ) d+ ) m ON TRUE""",session_ids,authorized_api_keys,+ _SESSION_MODEL_NAME_MAX_LEN,+ _SESSION_MODELS_LIMIT + 1,)session_spend_map = {- row["session_id"]: {- "session_total_spend": float(row.get("session_total_spend") or 0.0),- "session_total_duration_ms": int(row.get("session_total_duration_ms") or 0),- "mcp_tool_call_count": int(row.get("mcp_tool_call_count") or 0),- "mcp_tool_call_spend": float(row.get("mcp_tool_call_spend") or 0.0),- }+ (row["session_id"], row["api_key"]): _SessionSpendStats(+ session_total_count=int(row.get("session_total_count") or 0),+ session_total_spend=float(row.get("session_total_spend") or 0.0),++ session_total_duration_ms=int(row.get("session_total_duration_ms") or 0),+ mcp_tool_call_count=int(row.get("mcp_tool_call_count") or 0),+ mcp_tool_call_spend=float(row.get("mcp_tool_call_spend") or 0.0),+ session_cache_hit_count=int(row.get("session_cache_hit_count") or 0),+ session_llm_count=int(row.get("session_llm_count") or 0),+ session_agent_count=int(row.get("session_agent_count") or 0),+ session_total_prompt_tokens=int(row.get("session_total_prompt_tokens") or 0),+ session_total_completion_tokens=int(row.get("session_total_completion_tokens") or 0),+ session_total_tokens=int(row.get("session_total_tokens") or 0),+ session_models=models[:_SESSION_MODELS_LIMIT],+ session_models_truncated=len(models) > _SESSION_MODELS_LIMIT,+ )for row in rows- if row.get("session_id")+ if row.get("session_id") and row.get("api_key") is not None+ for models in (TypeAdapter(list[str]).validate_python(row.get("session_models") or ()),)}except PrismaError:verbose_proxy_logger.debug(@@@ -3502,14 -4610,22 +4619,23 @@@for row in data:row_dict = dict(row) if isinstance(row, dict) else row.model_dump()sid = row_dict.get("session_id")- row_dict["session_total_count"] = count_map.get(sid, 1) if sid else 1- session_stats = session_spend_map.get(sid) if sid else None+ row_api_key = row_dict.get("api_key")+ session_stats = session_spend_map.get((sid, row_api_key)) if sid and row_api_key is not None else None+ row_dict["session_total_count"] = session_stats.session_total_count if session_stats else 1if session_stats:- row_dict["session_total_spend"] = session_stats["session_total_spend"]- row_dict["session_total_duration_ms"] = session_stats["session_total_duration_ms"]- if session_stats["mcp_tool_call_count"]:- row_dict["mcp_tool_call_count"] = session_stats["mcp_tool_call_count"]- row_dict["mcp_tool_call_spend"] = session_stats["mcp_tool_call_spend"]+ row_dict["session_total_spend"] = session_stats.session_total_spend++ row_dict["session_total_duration_ms"] = session_stats.session_total_duration_ms+ if session_stats.mcp_tool_call_count:+ row_dict["mcp_tool_call_count"] = session_stats.mcp_tool_call_count+ row_dict["mcp_tool_call_spend"] = session_stats.mcp_tool_call_spend+ row_dict["session_cache_hit_count"] = session_stats.session_cache_hit_count+ row_dict["session_llm_count"] = session_stats.session_llm_count+ row_dict["session_agent_count"] = session_stats.session_agent_count+ row_dict["session_total_prompt_tokens"] = session_stats.session_total_prompt_tokens+ row_dict["session_total_completion_tokens"] = session_stats.session_total_completion_tokens+ row_dict["session_total_tokens"] = session_stats.session_total_tokens+ row_dict["session_models"] = session_stats.session_models+ row_dict["session_models_truncated"] = session_stats.session_models_truncatedenriched.append(row_dict)response_data: list = enrichedelse:diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex c93810bdce0,60bff50f000..772c5f674d5--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@@ -2418,264 -3957,1536 +3957,1617 @@@ class TestSpendLogsPayload})- differences = _compare_nested_dicts(- payload, expected_payload, ignore_keys=ignored_keys- )- if differences:- assert False, f"Dictionary mismatch: {differences}"+ differences = _compare_nested_dicts(+ payload, expected_payload, ignore_keys=ignored_keys+ )+ if differences:+ pytest.fail(f"Dictionary mismatch: {differences}")+++ def _compare_nested_dicts(+ actual: dict, expected: dict, path: str = "", ignore_keys: list[str] = []+ ) -> list[str]:+ """Compare nested dictionaries and return a list of differences in a human-friendly format."""+ differences = []++ # Check if current path should be ignored+ if path in ignore_keys:+ return differences++ # Check for keys in actual but not in expected+ for key in actual:+ current_path = f"{path}.{key}" if path else key+ if current_path not in ignore_keys and key not in expected:+ differences.append(f"Extra key in actual: {current_path}")++ for key, expected_value in expected.items():+ current_path = f"{path}.{key}" if path else key+ if current_path in ignore_keys:+ continue+ if key not in actual:+ differences.append(f"Missing key: {current_path}")+ continue++ actual_value = actual[key]++ # Try to parse JSON strings+ if isinstance(expected_value, str):+ try:+ expected_value = json.loads(expected_value)+ except json.JSONDecodeError:+ pass+ if isinstance(actual_value, str):+ try:+ actual_value = json.loads(actual_value)+ except json.JSONDecodeError:+ pass++ if isinstance(expected_value, dict) and isinstance(actual_value, dict):+ differences.extend(+ _compare_nested_dicts(+ actual_value, expected_value, current_path, ignore_keys+ )+ )+ elif isinstance(expected_value, dict) or isinstance(actual_value, dict):+ differences.append(+ f"Type mismatch at {current_path}: expected dict, got {type(actual_value).__name__}"+ )+ else:+ # For non-dict values, only report if they're different+ if actual_value != expected_value:+ # Format the values to be more readable+ actual_str = str(actual_value)+ expected_str = str(expected_value)+ if len(actual_str) > 50 or len(expected_str) > 50:+ actual_str = f"{actual_str[:50]}..."+ expected_str = f"{expected_str[:50]}..."+ differences.append(+ f"Value mismatch at {current_path}:\n expected: {expected_str}\n got: {actual_str}"+ )+ return differences+++ @pytest.mark.asyncio+ async def test_global_spend_keys_endpoint_limit_validation(client, monkeypatch):+ """+ Test to ensure that the global_spend_keys endpoint is protected against SQL injection attacks.+ Verifies that the limit parameter is properly parameterized and not directly interpolated.+ """+ # Create a simple mock for prisma client with empty response+ mock_prisma_client = MagicMock()+ mock_db = MagicMock()+ mock_query_raw = AsyncMock(return_value=[])+ mock_db.query_raw = mock_query_raw+ mock_prisma_client.db = mock_db+ # Apply the mock to the prisma_client module+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)++ # Override auth to bypass API key validation+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ # Call the endpoint without specifying a limit+ no_limit_response = client.get("/global/spend/keys")+ assert no_limit_response.status_code == 200+ mock_query_raw.assert_called_once_with('SELECT * FROM "Last30dKeysBySpend";')+ # Reset the mock for the next test+ mock_query_raw.reset_mock()+ # Test with valid input+ normal_limit = "10"+ good_input_response = client.get(f"/global/spend/keys?limit={normal_limit}")+ assert good_input_response.status_code == 200+ # Verify the mock was called with the correct parameters+ mock_query_raw.assert_called_once_with(+ 'SELECT * FROM "Last30dKeysBySpend" LIMIT $1 ;', 10+ )+ # Reset the mock for the next test+ mock_query_raw.reset_mock()+ # Test with SQL injection payload+ sql_injection_limit = "10; DROP TABLE spend_logs; --"+ response = client.get(f"/global/spend/keys?limit={sql_injection_limit}")+ # Verify the response is a validation error (422)+ assert response.status_code == 422+ # Verify the mock was not called with the SQL injection payload+ # This confirms that the validation happens before the database query+ mock_query_raw.assert_not_called()+ # Reset the mock for the next test+ mock_query_raw.reset_mock()+ # Test with non-numeric input+ non_numeric_limit = "abc"+ response = client.get(f"/global/spend/keys?limit={non_numeric_limit}")+ assert response.status_code == 422+ mock_query_raw.assert_not_called()+ mock_query_raw.reset_mock()+ # Test with negative number+ negative_limit = "-5"+ response = client.get(f"/global/spend/keys?limit={negative_limit}")+ assert response.status_code == 422+ mock_query_raw.assert_not_called()+ mock_query_raw.reset_mock()+ # Test with zero+ zero_limit = "0"+ response = client.get(f"/global/spend/keys?limit={zero_limit}")+ assert response.status_code == 422+ mock_query_raw.assert_not_called()+ mock_query_raw.reset_mock()+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_logs_summarize_parameter(client, monkeypatch):+ """Test the new summarize parameter in the /spend/logs endpoint"""+ import datetime+ from datetime import timedelta, timezone++ # Mock spend logs data+ mock_spend_logs = [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.05,+ "startTime": (+ datetime.datetime.now(timezone.utc) - timedelta(days=1)+ ).isoformat(),+ "model": "gpt-3.5-turbo",+ "prompt_tokens": 100,+ "completion_tokens": 50,+ "total_tokens": 150,+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.10,+ "startTime": (+ datetime.datetime.now(timezone.utc) - timedelta(days=1)+ ).isoformat(),+ "model": "gpt-4",+ "prompt_tokens": 200,+ "completion_tokens": 100,+ "total_tokens": 300,+ },+ ]++ # Mock for unsummarized data (summarize=false)+ class MockDB:+ def __init__(self):+ self.litellm_spendlogs = self++ async def find_many(self, *args, **kwargs):+ # Return individual log entries when summarize=false+ return mock_spend_logs++ async def query_raw(self, sql_query, *params):+ yesterday = datetime.datetime.now(timezone.utc) - timedelta(days=1)+ return [+ {+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "model": "gpt-3.5-turbo",+ "day": yesterday.date().isoformat(),+ "spend": 0.05,+ },+ {+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "model": "gpt-4",+ "day": yesterday.date().isoformat(),+ "spend": 0.10,+ },+ ]++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ # Apply the monkeypatch+ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)++ # Set up test dates+ start_date = (datetime.datetime.now(timezone.utc) - timedelta(days=2)).strftime(+ "%Y-%m-%d"+ )+ end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d")++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ try:+ # Test 1: summarize=false should return individual log entries+ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "summarize": "false",+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()++ # Should return the raw log entries+ assert isinstance(data, list)+ assert len(data) == 2+ assert data[0]["id"] == "log1"+ assert data[1]["id"] == "log2"+ assert data[0]["request_id"] == "req1"+ assert data[1]["request_id"] == "req2"++ # Test 2: summarize=true should return grouped data+ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "summarize": "true",+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()++ # Should return grouped/summarized data+ assert isinstance(data, list)+ # The structure should be different - grouped by date with aggregated spend+ assert "startTime" in data[0]+ assert "spend" in data[0]+ assert "users" in data[0]+ assert "models" in data[0]++ # Test 3: default behavior (no summarize parameter) should maintain backward compatibility+ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()++ # Should return grouped/summarized data (same as summarize=true)+ assert isinstance(data, list)+ assert "startTime" in data[0]+ assert "spend" in data[0]+ assert "users" in data[0]+ assert "models" in data[0]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_logs_bounds_row_count(client, monkeypatch):+ """Every /spend/logs read path must send take=SPEND_LOGS_PAGINATION_COUNT_CAP to Prisma (LIT-6284)."""+ captured_find_many_kwargs = []++ class MockDB:+ def __init__(self):+ self.litellm_spendlogs = self+ self.available_rows = 0++ async def find_many(self, *args, **kwargs):+ captured_find_many_kwargs.append(kwargs)+ return [{}] * min(kwargs.get("take", 0), self.available_rows)++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ def hash_token(self, token):+ return f"hashed-{token}"++ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ start_date = (+ datetime.datetime.now(timezone.utc) - datetime.timedelta(days=2)+ ).strftime("%Y-%m-%d")+ end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d")+ try:+ response = client.get(+ "/spend/logs",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )+ assert "x-litellm-spend-logs-truncated" not in response.headers++ response = client.get(+ "/spend/logs",+ params={"user_id": "test-user"},+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert captured_find_many_kwargs[-1].get("where") == {"user": "test-user"}+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )++ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ "summarize": "false",+ },+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert "startTime" in captured_find_many_kwargs[-1].get("where", {})+ assert (+ captured_find_many_kwargs[-1].get("take")+ == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )++ mock_prisma_client.db.available_rows = (+ spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ )+ response = client.get(+ "/spend/logs",+ headers={"Authorization": "Bearer sk-test"},+ )+ assert response.status_code == 200+ assert len(response.json()) == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP+ assert response.headers["x-litellm-spend-logs-truncated"] == "true"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_tags(client, monkeypatch):+ """Test the /spend/tags endpoint"""++ # Mock the prisma client and get_spend_by_tags function+ mock_prisma_client = MagicMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)++ # Mock response data+ mock_response = [+ {"individual_request_tag": "tag1", "log_count": 10, "total_spend": 0.15},+ {"individual_request_tag": "tag2", "log_count": 5, "total_spend": 0.08},+ ]++ # Mock the get_spend_by_tags function+ async def mock_get_spend_by_tags(prisma_client, start_date=None, end_date=None):+ return mock_response++ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.spend_management_endpoints.get_spend_by_tags",+ mock_get_spend_by_tags,+ )++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ # Test without date filters+ response = client.get(+ "/spend/tags",+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert isinstance(data, list)+ assert len(data) == 2+ assert data[0]["individual_request_tag"] == "tag1"+ assert data[0]["log_count"] == 10+ assert data[0]["total_spend"] == 0.15++ # Test with date filters+ start_date = "2024-01-01"+ end_date = "2024-01-31"++ response = client.get(+ "/spend/tags",+ params={+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert isinstance(data, list)+ assert len(data) == 2+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_tags_no_database(client, monkeypatch):+ """Test /spend/tags endpoint when database is not connected"""++ # Mock prisma_client as None+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ response = client.get(+ "/spend/tags",+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 500+ data = response.json()+ # Check the actual error message structure+ assert "error" in data+ assert "Database not connected" in data["error"]["message"]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_provider_budget_under(disable_budget_sync):+ """Test that router allows completion when under budget"""+ provider_budget_config = {+ "azure": BudgetConfig(max_budget=0.01, budget_duration="10d")+ }++ router = Router(+ enable_pre_call_checks=True,+ provider_budget_config=provider_budget_config,+ model_list=MODEL_LIST,+ )++ response = await router.acompletion(+ model="azure-gpt-4o",+ messages=[{"role": "user", "content": "Hello, world!"}],+ )++ assert response is not None+++ @pytest.mark.asyncio+ async def test_provider_budget_over(disable_budget_sync):+ """Test that router allows completion when over budget"""+ provider_budget_config = {+ "azure": BudgetConfig(max_budget=-0.01, budget_duration="10d")+ }++ router = Router(+ num_retries=0,+ enable_pre_call_checks=True,+ provider_budget_config=provider_budget_config,+ model_list=MODEL_LIST,+ )++ with pytest.raises(Exception, match='No deployments available - crossed budget: Exceeded budget') as e:+ await router.acompletion(+ model="azure-gpt-4o",+ messages=[{"role": "user", "content": "Hello, world!"}],+ )+ assert "Exceeded budget for provider" in str(e.value)+++ @pytest.mark.asyncio+ async def test_provider_budget_provider_budgets(disable_budget_sync):+ """Test that provider_budgets() returns correct values"""+ provider = "azure"+ max_budget = -0.01+ budget_duration = "10d"+ provider_budget_config = {+ provider: BudgetConfig(max_budget=max_budget, budget_duration=budget_duration)+ }++ router = Router(+ num_retries=0,+ enable_pre_call_checks=True,+ provider_budget_config=provider_budget_config,+ model_list=MODEL_LIST,+ )++ with patch("litellm.proxy.proxy_server.llm_router", router):+ response = await spend_management_endpoints.provider_budgets()+ provider_budget_response = response.providers[provider]+ assert provider_budget_response.budget_limit == max_budget+ assert provider_budget_response.time_period == budget_duration+++ @pytest.mark.asyncio+ async def test_view_spend_logs_with_date_range_summarized(client, monkeypatch):+ """+ Tests the /spend/logs endpoint with both start_date and end_date,+ ensuring it returns summarized data and not an empty list.+ This test specifically validates the fix for dates being passed as ISO strings.+ """+ from datetime import datetime, timedelta, timezone++ mock_summarized_response = [+ {+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "model": "gpt-4",+ "day": (datetime.now(timezone.utc) - timedelta(days=1)).date().isoformat(),+ "spend": 0.15,+ }+ ]++ class MockDB:+ async def query_raw(self, sql_query, *params):+ assert isinstance(params[0], str)+ assert isinstance(params[1], str)+ assert "T" in params[0]+ assert "T" in params[1]+ return mock_summarized_response++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())++ start_date = (datetime.now(timezone.utc) - timedelta(days=2)).strftime("%Y-%m-%d")+ end_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ try:+ response = client.get(+ "/spend/logs",+ params={+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()++ assert isinstance(data, list)+ assert len(data) > 0+ assert "startTime" in data[0]+ assert "spend" in data[0]+ assert "users" in data[0]+ assert "models" in data[0]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_logs_summarize_groups_by_day_in_sql(client, monkeypatch):+ mock_rows = [+ {+ "day": "2024-01-01",+ "api_key": "hashed::sk-abc",+ "user": "u1",+ "model": "gpt-4",+ "spend": 0.1,+ },+ {+ "day": "2024-01-01",+ "api_key": "hashed::sk-abc",+ "user": "u1",+ "model": "gpt-4o",+ "spend": 0.2,+ },+ ]++ class MockDB:+ def __init__(self):+ self.captured_sql = None+ self.captured_params = None++ async def query_raw(self, sql_query, *params):+ self.captured_sql = sql_query+ self.captured_params = params+ return mock_rows++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ def hash_token(self, token):+ return "hashed::" + token++ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ try:+ response = client.get(+ "/spend/logs",+ params={+ "start_date": "2024-01-01",+ "end_date": "2024-01-03",+ "api_key": "sk-abc",+ "request_id": "req-123",+ "user_id": "u1",+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ sql = mock_prisma_client.db.captured_sql+ assert "date_trunc('day'" in sql+ assert "GROUP BY" in sql+ assert "find_many" not in sql+ assert not hasattr(mock_prisma_client.db, "group_by")+ assert mock_prisma_client.db.captured_params == (+ "2024-01-01T00:00:00+00:00",+ "2024-01-03T00:00:00+00:00",+ "hashed::sk-abc",+ "req-123",+ "u1",+ )+ assert len(data) == 3+ assert data[0]["startTime"] == "2024-01-01"+ assert data[0]["spend"] == pytest.approx(0.3)+ assert data[0]["models"] == {"gpt-4": 0.1, "gpt-4o": 0.2}+ assert data[0]["users"] == {"u1": pytest.approx(0.3)}+ assert data[0]["hashed::sk-abc"] == pytest.approx(0.3)+ assert data[1] == {+ "startTime": "2024-01-02",+ "spend": 0,+ "users": {},+ "models": {},+ }+ assert data[2] == {+ "startTime": "2024-01-03",+ "spend": 0,+ "users": {},+ "models": {},+ }+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_logs_summarize_empty_rows(client, monkeypatch):+ class MockDB:+ async def query_raw(self, sql_query, *params):+ return []++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ try:+ response = client.get(+ "/spend/logs",+ params={"start_date": "2024-01-01", "end_date": "2024-01-01"},+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ assert response.json() == []+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_view_spend_logs_summarize_unhashed_api_key_without_padding(client, monkeypatch):+ mock_rows = [+ {+ "day": "2024-01-01",+ "api_key": "plain-key",+ "user": "u1",+ "model": "gpt-4",+ "spend": 0.4,+ }+ ]++ class MockDB:+ def __init__(self):+ self.captured_params = None++ async def query_raw(self, sql_query, *params):+ self.captured_params = params+ return mock_rows++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()++ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ try:+ response = client.get(+ "/spend/logs",+ params={+ "start_date": "2024-01-01",+ "end_date": "2024-01-01",+ "api_key": "plain-key",+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert mock_prisma_client.db.captured_params == (+ "2024-01-01T00:00:00+00:00",+ "2024-01-01T00:00:00+00:00",+ "plain-key",+ )+ assert data == [+ {+ "startTime": "2024-01-01",+ "spend": pytest.approx(0.4),+ "plain-key": pytest.approx(0.4),+ "users": {"u1": pytest.approx(0.4)},+ "models": {"gpt-4": pytest.approx(0.4)},+ }+ ]+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_with_error_code(client):+ """Test filtering spend logs by error code"""+ mock_spend_logs = [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.05,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-3.5-turbo",+ "metadata": '{"error_information": {"error_code": "404"}}',+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": "sk-test-key",+ "user": "test_user_2",+ "team_id": "team1",+ "spend": 0.10,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-4",+ "metadata": '{"error_information": {"error_code": "500"}}',+ },+ ]++ def filter_by_error_code(where):+ if "metadata" in where:+ mf = where["metadata"]+ if mf.get("path") == ["error_information", "error_code"]:+ code = str(mf.get("equals", "")).strip('"')+ if code == "404":+ return [mock_spend_logs[0]]+ if code == "500":+ return [mock_spend_logs[1]]+ return mock_spend_logs++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ with patch.object(+ ps,+ "prisma_client",+ make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_error_code),+ ):+ start_date, end_date = _default_date_range()++ response = client.get(+ "/spend/logs/ui",+ params={+ "error_code": "404",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert len(data["data"]) == 1+ assert data["data"][0]["id"] == "log1"+ metadata = data["data"][0]["metadata"]+ assert isinstance(metadata, dict)+ assert "error_information" in metadata+ assert metadata["error_information"]["error_code"] == "404"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_with_error_message(client):+ """Test filtering spend logs by error message"""+ mock_spend_logs = [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.05,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-3.5-turbo",+ "metadata": '{"error_information": {"error_message": "Rate limit exceeded"}}',+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": "sk-test-key",+ "user": "test_user_2",+ "team_id": "team1",+ "spend": 0.10,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-4",+ "metadata": '{"error_information": {"error_message": "Invalid API key"}}',+ },+ ]++ def filter_by_error_message(where):+ if "metadata" in where:+ mf = where["metadata"]+ if mf.get("path") == ["error_information", "error_message"]:+ msg = mf.get("string_contains")+ if msg == "Rate limit":+ return [mock_spend_logs[0]]+ if msg == "Invalid API":+ return [mock_spend_logs[1]]+ return mock_spend_logs++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ with patch.object(+ ps,+ "prisma_client",+ make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_error_message),+ ):+ start_date, end_date = _default_date_range()++ response = client.get(+ "/spend/logs/ui",+ params={+ "error_message": "Rate limit",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert len(data["data"]) == 1+ assert data["data"][0]["id"] == "log1"+ metadata = data["data"][0]["metadata"]+ assert isinstance(metadata, dict)+ assert "error_information" in metadata+ assert (+ "Rate limit exceeded" in metadata["error_information"]["error_message"]+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_ui_view_spend_logs_with_error_code_and_key_alias(client):+ """Test merging error_code and key_alias filters with AND logic"""+ mock_spend_logs = [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.05,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-3.5-turbo",+ "metadata": '{"user_api_key_alias": "test-key-1", "error_information": {"error_code": "404"}}',+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": "sk-test-key",+ "user": "test_user_2",+ "team_id": "team1",+ "spend": 0.10,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-4",+ "metadata": '{"user_api_key_alias": "test-key-2", "error_information": {"error_code": "500"}}',+ },+ {+ "id": "log3",+ "request_id": "req3",+ "api_key": "sk-test-key",+ "user": "test_user_3",+ "team_id": "team1",+ "spend": 0.15,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-4",+ "metadata": '{"user_api_key_alias": "test-key-1", "error_information": {"error_code": "500"}}',+ },+ ]++ def filter_by_error_code_and_key_alias(where):+ if "AND" in where:+ key_alias = error_code = None+ for cond in where["AND"]:+ if "metadata" in cond:+ mf = cond["metadata"]+ if mf.get("path") == ["user_api_key_alias"]:+ key_alias = mf.get("string_contains")+ elif mf.get("path") == ["error_information", "error_code"]:+ error_code = str(mf.get("equals", "")).strip('"')+ if key_alias == "test-key-1" and error_code == "500":+ return [mock_spend_logs[2]]+ return mock_spend_logs++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ with patch.object(+ ps,+ "prisma_client",+ make_ui_spend_logs_mock_prisma(+ mock_spend_logs, filter_by_error_code_and_key_alias+ ),+ ):+ start_date, end_date = _default_date_range()++ response = client.get(+ "/spend/logs/ui",+ params={+ "error_code": "500",+ "key_alias": "test-key-1",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert len(data["data"]) == 1+ assert data["data"][0]["id"] == "log3"+ metadata = data["data"][0]["metadata"]+ assert isinstance(metadata, dict)+ assert "user_api_key_alias" in metadata+ assert metadata["user_api_key_alias"] == "test-key-1"+ assert "error_information" in metadata+ assert metadata["error_information"]["error_code"] == "500"+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_dict_rows_session_counts():+ """+ Regression test: _build_ui_spend_logs_response must enrich session_total_count+ even when rows are plain dicts (as returned by query_raw) rather than Prisma+ model instances. Previously getattr(dict, "session_id", None) silently+ returned None, so every row got session_total_count=1 and the UI never+ grouped session rows.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-abc-123"+ api_key = "hashed-key-xyz"+ dict_rows = [+ {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key},+ {"request_id": "req-2", "session_id": session_id, "call_type": "mcp_tool_call", "api_key": api_key},+ {"request_id": "req-3", "session_id": None, "call_type": "completion", "api_key": api_key},+ ]++ mock_prisma = MagicMock()+ mock_prisma.db.litellm_spendlogs.group_by = AsyncMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": api_key,+ "session_total_count": 2,+ "session_total_spend": 15.0,+ "mcp_tool_call_count": 1,+ "mcp_tool_call_spend": 10.0,+ "session_llm_count": 1,+ "session_agent_count": 0,+ "session_models": ["claude-haiku-4-5", "gpt-5.4-nano"],+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=3,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ rows = result["data"]+ assert len(rows) == 3++ # Rows with the shared session_id should have session_total_count=2+ assert rows[0]["session_total_count"] == 2+ assert rows[1]["session_total_count"] == 2+ assert rows[0]["mcp_tool_call_count"] == 1+ assert rows[0]["mcp_tool_call_spend"] == 10.0+ assert rows[1]["mcp_tool_call_count"] == 1+ assert rows[1]["mcp_tool_call_spend"] == 10.0+ assert rows[0]["session_llm_count"] == 1+ assert rows[0]["session_agent_count"] == 0+ assert rows[0]["session_models"] == ["claude-haiku-4-5", "gpt-5.4-nano"]++ # Every row in the session carries the full session spend, not just its own+ assert rows[0]["session_total_spend"] == 15.0+ assert rows[1]["session_total_spend"] == 15.0++ # Row without a session_id defaults to 1+ assert rows[2]["session_total_count"] == 1+ assert "session_models" not in rows[2]++ # The count is folded into the single aggregate query; no separate group_by call.+ mock_prisma.db.litellm_spendlogs.group_by.assert_not_called()+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_caps_session_models():+ """The per-session model list is bounded server-side and flags when it was cut."""+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _SESSION_MODELS_LIMIT,+ _build_ui_spend_logs_response,+ )++ session_id = "sess-many-models"+ api_key = "hashed-key-xyz"+ over_limit_models = [f"model-{i:02d}" for i in range(_SESSION_MODELS_LIMIT + 1)]++ mock_prisma = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": api_key,+ "session_total_count": len(over_limit_models),+ "session_total_spend": 1.0,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_llm_count": len(over_limit_models),+ "session_agent_count": 0,+ "session_models": over_limit_models,+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=[{"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key}],+ total_records=1,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ row = result["data"][0]+ assert row["session_models"] == over_limit_models[:_SESSION_MODELS_LIMIT]+ assert row["session_models_truncated"] is True- def mock_anthropic_response(*args, **kwargs):- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.headers = {"Content-Type": "application/json"}- mock_response.json.return_value = {- "content": [{"text": "Hi! My name is Claude.", "type": "text"}],- "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",- "model": "claude-4-sonnet-20250514",- "role": "assistant",- "stop_reason": "end_turn",- "stop_sequence": None,- "type": "message",- "usage": {"input_tokens": 2095, "output_tokens": 503},- }- return mock_response+ sql, *params = mock_prisma.db.query_raw.await_args.args+ assert "LIMIT $4" in sql+ assert params[3] == _SESSION_MODELS_LIMIT + 1+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_key_split_session_gets_per_key_aggregates():+ """+ Two keys reusing one session id are separate rows under grouped pagination,+ and each row must carry ITS key's totals, never the combined session's:+ the aggregate query and its lookup are keyed by (session_id, api_key).+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-shared"+ dict_rows = [+ {"request_id": "req-a", "session_id": session_id, "call_type": "completion", "api_key": "key-a"},+ {"request_id": "req-b", "session_id": session_id, "call_type": "completion", "api_key": "key-b"},+ ]++ mock_prisma = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": "key-a",+ "session_total_count": 2,+ "session_total_spend": 0.2,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 1,+ "session_llm_count": 2,+ "session_agent_count": 0,+ },+ {+ "session_id": session_id,+ "api_key": "key-b",+ "session_total_count": 1,+ "session_total_spend": 0.7,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 0,+ "session_llm_count": 1,+ "session_agent_count": 0,+ },+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=2,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ rows = result["data"]+ assert [(r["session_total_count"], r["session_total_spend"]) for r in rows] == [(2, 0.2), (1, 0.7)]+ assert [r["session_cache_hit_count"] for r in rows] == [1, 0]+ assert [r["session_llm_count"] for r in rows] == [2, 1]++ aggregate_sql = mock_prisma.db.query_raw.mock_calls[0][1][0]+ assert "GROUP BY session_id, api_key" in aggregate_sql+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_empty_api_key_keeps_session_aggregates():+ """+ The spend-log schema defaults api_key to an empty string, which is a real+ group value and not a missing one: a multi-call session logged under an+ empty key must keep its count and spend instead of degrading to a plain+ single-call row.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-keyless"+ dict_rows = [+ {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": ""},+ ]++ mock_prisma = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": "",+ "session_total_count": 3,+ "session_total_spend": 0.09,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 0,+ "session_llm_count": 3,+ "session_agent_count": 0,+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=1,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ row = result["data"][0]+ assert row["session_total_count"] == 3+ assert row["session_total_spend"] == 0.09++ # The empty key must reach the aggregate's authorized-keys filter too.+ _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]+ assert call_args[2] == [""]+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_sums_multi_round_session_spend():+ """+ Regression test for LIT-4342: for a multi-round session the UI must show the+ summed cost of every round, not just the first call. _build_ui_spend_logs_response+ enriches each row of a session with session_total_spend aggregated across the+ whole session, scoped to the authorized api_keys of the page.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-multi-round"+ api_key = "hashed-key-xyz"+ # Three rounds of the same chat session with different per-call spend.+ dict_rows = [+ {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.01},+ {"request_id": "req-2", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.02},+ {"request_id": "req-3", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.03},+ ]++ mock_prisma = MagicMock()+ # The raw aggregate query returns the full session spend (0.01 + 0.02 + 0.03).+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": api_key,+ "session_total_count": 3,+ "session_total_spend": 0.06,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=3,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ rows = result["data"]+ assert [row["session_total_spend"] for row in rows] == [0.06, 0.06, 0.06]+ # No MCP calls in this session, so MCP fields must not be attached.+ assert all("mcp_tool_call_count" not in row for row in rows)++ # The aggregate must be scoped to the authorized api_keys of the page.+ _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]+ assert call_args[1] == [session_id]+ assert call_args[2] == [api_key]+++ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_sums_multi_round_session_tokens():+ """+ Regression test for LIT-4929: the logs table showed the summed session cost but+ only the last call's token usage. Every row of a multi-round session must carry+ the session-wide prompt, completion and total token sums from the aggregate+ query, while rows outside a session carry none of them.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-multi-round-tokens"+ api_key = "hashed-key-xyz"+ dict_rows = [+ {+ "request_id": "req-1",+ "session_id": session_id,+ "call_type": "completion",+ "api_key": api_key,+ "total_tokens": 10,+ "prompt_tokens": 7,+ "completion_tokens": 3,+ },+ {+ "request_id": "req-2",+ "session_id": session_id,+ "call_type": "completion",+ "api_key": api_key,+ "total_tokens": 50,+ "prompt_tokens": 35,+ "completion_tokens": 15,+ },+ {+ "request_id": "req-3",+ "session_id": None,+ "call_type": "completion",+ "api_key": api_key,+ "total_tokens": 5,+ "prompt_tokens": 4,+ "completion_tokens": 1,+ },+ ]++ mock_prisma = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": api_key,+ "session_total_count": 2,+ "session_total_spend": 0.06,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_total_prompt_tokens": 42,+ "session_total_completion_tokens": 18,+ "session_total_tokens": 60,+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=3,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ rows = result["data"]+ session_rows = rows[:2]+ assert [row["session_total_tokens"] for row in session_rows] == [60, 60]+ assert [row["session_total_prompt_tokens"] for row in session_rows] == [42, 42]+ assert [row["session_total_completion_tokens"] for row in session_rows] == [18, 18]+ assert [(row["total_tokens"], row["prompt_tokens"], row["completion_tokens"]) for row in session_rows] == [+ (10, 7, 3),+ (50, 35, 15),+ ]++ token_keys = ("session_total_tokens", "session_total_prompt_tokens", "session_total_completion_tokens")+ assert all(key not in rows[2] for key in token_keys)++++async def test_build_ui_spend_logs_response_sums_multi_round_session_duration():++ """++ Regression test: a multi-round session collapses into a single UI row, so that row++ must carry the duration of every round summed, not just the representative call's.++ Rows written before request_duration_ms existed are NULL, so the aggregate falls back++ to endTime - startTime for them.++ """++ from litellm.proxy.spend_tracking.spend_management_endpoints import (++ _build_ui_spend_logs_response,++ )++++ session_id = "sess-multi-round-duration"++ api_key = "hashed-key-xyz"++ dict_rows = [++ {++ "request_id": "req-1",++ "session_id": session_id,++ "call_type": "completion",++ "api_key": api_key,++ "spend": 0.01,++ "request_duration_ms": 1200,++ },++ {++ "request_id": "req-2",++ "session_id": session_id,++ "call_type": "completion",++ "api_key": api_key,++ "spend": 0.02,++ "request_duration_ms": 4200,++ },++ {++ "request_id": "req-3",++ "session_id": None,++ "call_type": "completion",++ "api_key": api_key,++ "spend": 0.03,++ "request_duration_ms": 900,++ },++ ]++++ mock_prisma = MagicMock()++ mock_prisma.db.query_raw = AsyncMock(++ return_value=[++ {++ "session_id": session_id,++ "api_key": api_key,++ "session_total_count": 2,++ "session_total_spend": 0.03,++ "session_total_duration_ms": 5400,++ "mcp_tool_call_count": 0,++ "mcp_tool_call_spend": 0.0,++ }++ ]++ )++++ result = await _build_ui_spend_logs_response(++ prisma_client=mock_prisma,++ data=dict_rows,++ total_records=3,++ page=1,++ page_size=50,++ total_pages=1,++ enrich_session_counts=True,++ )+- @pytest.mark.asyncio- async def test_spend_logs_payload_success_log_with_api_base(self, monkeypatch):- from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ rows = result["data"]++ session_rows = rows[:2]++ assert [row["session_total_duration_ms"] for row in session_rows] == [5400, 5400]++ assert all(isinstance(row["session_total_duration_ms"], int) for row in session_rows)++ assert [row["request_duration_ms"] for row in rows] == [1200, 4200, 900]++ assert "session_total_duration_ms" not in rows[2]+- # Clear any env overrides that would change the recorded api_base- monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)- monkeypatch.delenv("ANTHROPIC_API_BASE", raising=False)++ _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]++ sql = " ".join(call_args[0].split())++ assert (++ 'SUM( COALESCE( request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER ) )'++ in sql++ )+- litellm.callbacks = [_ProxyDBLogger(message_logging=False)]- # litellm._turn_on_debug()+- client = AsyncHTTPHandler()+ @pytest.mark.asyncio+ async def test_build_ui_spend_logs_response_session_cache_hit_count():+ """+ Each row of a session must carry session_cache_hit_count aggregated across+ the whole session so the UI can show how many requests in the session were+ served from the response cache.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )- with (- patch.object(- litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter,- "_insert_spend_log_to_db",- ) as mock_client,- patch.object(litellm.proxy.proxy_server, "prisma_client"),- patch.object(client, "post", side_effect=self.mock_anthropic_response),- ):- response = await litellm.acompletion(- model="claude-4-sonnet-20250514",- messages=[{"role": "user", "content": "Hello, world!"}],- metadata={"user_api_key_end_user_id": "test_user_1"},- client=client,- )+ session_id = "sess-cache-hits"+ api_key = "hashed-key-xyz"+ dict_rows = [+ {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key},+ {"request_id": "req-2", "session_id": session_id, "call_type": "completion", "api_key": api_key},+ {"request_id": "req-3", "session_id": None, "call_type": "completion", "api_key": api_key},+ ]- assert response.choices[0].message.content == "Hi! My name is Claude."+ mock_prisma = MagicMock()+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "api_key": api_key,+ "session_total_count": 2,+ "session_total_spend": 0.05,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 2,+ }+ ]+ )- await _wait_for_mock_call(mock_client)+ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=3,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )- kwargs = mock_client.call_args.kwargs- payload: SpendLogsPayload = kwargs["payload"]- expected_payload = SpendLogsPayload(- **{- "request_id": "chatcmpl-34df56d5-4807-45c1-bb99-61e52586b802",- "call_type": "acompletion",- "api_key": "",- "cache_hit": "None",- "startTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 975883, tzinfo=datetime.timezone.utc- ),- "endTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc- ),- "completionStartTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc- ),- "model": "claude-4-sonnet-20250514",- "user": "",- "team_id": "",- "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',- "cache_key": "Cache OFF",- "spend": 0.01383,- "total_tokens": 2598,- "prompt_tokens": 2095,- "completion_tokens": 503,- "request_tags": "[]",- "end_user": "test_user_1",- "api_base": "https://api.anthropic.com/v1/messages",- "model_group": "",- "model_id": "",- "requester_ip_address": None,- "custom_llm_provider": "anthropic",- "messages": "{}",- "response": "{}",- "proxy_server_request": "{}",- "status": "success",- "mcp_namespaced_tool_name": None,- "agent_id": None,- }- )+ rows = result["data"]+ assert rows[0]["session_cache_hit_count"] == 2+ assert rows[1]["session_cache_hit_count"] == 2+ assert "session_cache_hit_count" not in rows[2]- differences = _compare_nested_dicts(- payload, expected_payload, ignore_keys=ignored_keys- )- if differences:- assert False, f"Dictionary mismatch: {differences}"+ # The aggregate SQL must actually compute the cache-hit count.+ _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]+ assert "session_cache_hit_count" in call_args[0]+ assert "LOWER(cache_hit) = 'true'" in call_args[0]- @pytest.mark.asyncio- async def test_spend_logs_payload_success_log_with_router(self, monkeypatch):- from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler- # Clear any env overrides that would change the recorded api_base- monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)- monkeypatch.delenv("ANTHROPIC_API_BASE", raising=False)+ # ---------------------------------------------------------------------------+ # Tests for /spend/logs team-member permission+ # ---------------------------------------------------------------------------- litellm.callbacks = [_ProxyDBLogger(message_logging=False)]- # litellm._turn_on_debug()- client = AsyncHTTPHandler()+ @pytest.mark.asyncio+ async def test_can_team_member_view_log_with_spend_logs_permission(monkeypatch):+ """+ Non-admin team member WITH /spend/logs permission should be allowed.+ """- router = Router(- model_list=[- {- "model_name": "my-anthropic-model-group",- "litellm_params": {- "model": "claude-4-sonnet-20250514",- },- "model_info": {- "id": "my-unique-model-id",- },- }- ]- )+ class MockTeam:+ team_id = "team_abc"+ members_with_roles = [Member(user_id="member_1", role="user")]+ team_member_permissions = ["/spend/logs"]- with (- patch.object(- litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter,- "_insert_spend_log_to_db",- ) as mock_client,- patch.object(litellm.proxy.proxy_server, "prisma_client"),- patch.object(client, "post", side_effect=self.mock_anthropic_response),- ):- response = await router.acompletion(- model="my-anthropic-model-group",- messages=[{"role": "user", "content": "Hello, world!"}],- metadata={"user_api_key_end_user_id": "test_user_1"},- client=client,- )+ def model_dump(self):+ return {+ "team_id": self.team_id,+ "members_with_roles": [{"user_id": "member_1", "role": "user"}],+ "team_member_permissions": self.team_member_permissions,+ }- assert response.choices[0].message.content == "Hi! My name is Claude."+ class MockPrisma:+ class DB:+ class TeamTable:+ async def find_unique(self, where: dict):+ return MockTeam()- await _wait_for_mock_call(mock_client)+ def __init__(self):+ self.litellm_teamtable = self.TeamTable()- kwargs = mock_client.call_args.kwargs- payload: SpendLogsPayload = kwargs["payload"]- expected_payload = SpendLogsPayload(- **{- "request_id": "chatcmpl-34df56d5-4807-45c1-bb99-61e52586b802",- "call_type": "acompletion",- "api_key": "",- "cache_hit": "None",- "startTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 975883, tzinfo=datetime.timezone.utc- ),- "endTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc- ),- "completionStartTime": datetime.datetime(- 2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc- ),- "model": "claude-4-sonnet-20250514",- "user": "",- "team_id": "",- "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',- "cache_key": "Cache OFF",- "spend": 0.01383,- "total_tokens": 2598,- "prompt_tokens": 2095,- "completion_tokens": 503,- "request_tags": "[]",- "end_user": "test_user_1",- "api_base": "https://api.anthropic.com/v1/messages",- "model_group": "my-anthropic-model-group",- "model_id": "my-unique-model-id",- "requester_ip_address": None,- "custom_llm_provider": "anthropic",- "messages": "{}",- "response": "{}",- "proxy_server_request": "{}",- "status": "success",- "mcp_namespaced_tool_name": None,- "agent_id": None,- }- )+ def __init__(self):+ self.db = self.DB()- differences = _compare_nested_dicts(- payload, expected_payload, ignore_keys=ignored_keys- )- if differences:- assert False, f"Dictionary mismatch: {differences}"+ prisma = MockPrisma()+ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1")+ allowed = await spend_management_endpoints._can_team_member_view_log(+ prisma, auth, "team_abc"+ )+ assert allowed is True- def _compare_nested_dicts(- actual: dict, expected: dict, path: str = "", ignore_keys: list[str] = []- ) -> list[str]:- """Compare nested dictionaries and return a list of differences in a human-friendly format."""- differences = []+ @pytest.mark.asyncio+ async def test_can_team_member_view_log_without_spend_logs_permission(monkeypatch):+ """+ Non-admin team member WITHOUT /spend/logs permission should be denied.+ """- # Check if current path should be ignored- if path in ignore_keys:- return differences+ class MockTeam:+ team_id = "team_abc"+ members_with_roles = [Member(user_id="member_1", role="user")]+ team_member_permissions = ["/key/info"]- # Check for keys in actual but not in expected- for key in actual.keys():- current_path = f"{path}.{key}" if path else key- if current_path not in ignore_keys and key not in expected:- differences.append(f"Extra key in actual: {current_path}")+ def model_dump(self):+ return {+ "team_id": self.team_id,+ "members_with_roles": [{"user_id": "member_1", "role": "user"}],+ "team_member_permissions": self.team_member_permissions,+ }- for key, expected_value in expected.items():- current_path = f"{path}.{key}" if path else key- if current_path in ignore_keys:- continue- if key not in actual:- differences.append(f"Missing key: {current_path}")- continue+ class MockPrisma:+ class DB:+ class TeamTable:+ async def find_unique(self, where: dict):+ return MockTeam()- actual_value = actual[key]+ def __init__(self):+ self.litellm_teamtable = self.TeamTable()- # Try to parse JSON strings- if isinstance(expected_value, str):- try:- expected_value = json.loads(expected_value)- except json.JSONDecodeError:- pass- if isinstance(actual_value, str):- try:- actual_value = json.loads(actual_value)- except json.JSONDecodeError:- pass+ def __init__(self):+ self.db = self.DB()- if isinstance(expected_value, dict) and isinstance(actual_value, dict):- differences.extend(- _compare_nested_dicts(- actual_value, expected_value, current_path, ignore_keys- )- )- elif isinstance(expected_value, dict) or isinstance(actual_value, dict):- differences.append(- f"Type mismatch at {current_path}: expected dict, got {type(actual_value).__name__}"- )- else:- # For non-dict values, only report if they're different- if actual_value != expected_value:- # Format the values to be more readable- actual_str = str(actual_value)- expected_str = str(expected_value)- if len(actual_str) > 50 or len(expected_str) > 50:- actual_str = f"{actual_str[:50]}..."- expected_str = f"{expected_str[:50]}..."- differences.append(- f"Value mismatch at {current_path}:\n expected: {expected_str}\n got: {actual_str}"- )- return differences+ prisma = MockPrisma()+ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1")+ allowed = await spend_management_endpoints._can_team_member_view_log(+ prisma, auth, "team_abc"+ )+ assert allowed is False@pytest.mark.asynciodiff --cc ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.test.tsxindex 0b54f78736d,9f0e659cb1f..d60b9ce30f1--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.test.tsx@@@ -73,68 -73,171 +73,231 @@@ describe("Cost column", () =>expect(screen.queryByText("$0.010000")).not.toBeInTheDocument();expect(screen.getByText("session total")).toBeInTheDocument();});++ it("does not label the per-call spend a session total when the aggregate is unavailable", () => {+ renderRows([+ logEntry({+ request_id: "req-session-no-aggregate",+ spend: 0.01,+ session_id: "sess-1",+ session_total_count: 3,+ }),+ ]);++ expect(screen.getByText("$0.010000")).toBeInTheDocument();+ expect(screen.queryByText("session total")).not.toBeInTheDocument();+ });+});++describe("Duration column", () => {+ it("shows the summed session duration, not the representative call's duration, for a multi-round session", () => {+ renderRows([+ logEntry({+ request_id: "req-session-duration",+ request_duration_ms: 1200,+ session_id: "sess-1",+ session_total_count: 3,+ session_total_duration_ms: 5400,+ }),+ ]);++ expect(screen.getByText("5.40")).toBeInTheDocument();+ expect(screen.queryByText("1.20")).not.toBeInTheDocument();+ expect(screen.getByText("session total")).toBeInTheDocument();+ });++ it("does not label the per-call duration a session total when the aggregate is unavailable", () => {+ renderRows([+ logEntry({+ request_id: "req-no-aggregate",+ request_duration_ms: 1200,+ session_id: "sess-3",+ session_total_count: 3,+ }),+ ]);++ expect(screen.getByText("1.20")).toBeInTheDocument();+ expect(screen.queryByText("session total")).not.toBeInTheDocument();+ });++ it("shows the call's own duration for a single-call session", () => {+ renderRows([+ logEntry({+ request_id: "req-single-duration",+ request_duration_ms: 1200,+ session_id: "sess-2",+ session_total_count: 1,+ session_total_duration_ms: 1200,+ }),+ ]);++ expect(screen.getByText("1.20")).toBeInTheDocument();+ });});+ describe("Tokens column", () => {+ const sessionRow: Partial<LogEntry> = {+ request_id: "req-session-tokens",+ total_tokens: 10,+ prompt_tokens: 7,+ completion_tokens: 3,+ session_id: "sess-1",+ session_total_count: 3,+ };++ it("shows the summed session token usage, not the representative call's tokens, for a multi-round session", () => {+ const aggregatedRow: Partial<LogEntry> = {+ ...sessionRow,+ session_total_tokens: 60,+ session_total_prompt_tokens: 42,+ session_total_completion_tokens: 18,+ };+ renderRows([logEntry(aggregatedRow)]);++ const tokensCell = screen.getByRole("cell", { name: /\(42\+18\)/ });+ expect(tokensCell).toHaveTextContent("60");+ expect(tokensCell).toHaveTextContent("session total");+ expect(screen.queryByText("10")).not.toBeInTheDocument();+ expect(screen.queryByText("(7+3)")).not.toBeInTheDocument();+ });++ it("falls back to the call's own tokens with no session label when the backend sent no session token sums", () => {+ renderRows([logEntry(sessionRow)]);++ const tokensCell = screen.getByRole("cell", { name: /\(7\+3\)/ });+ expect(tokensCell).toHaveTextContent("10");+ expect(tokensCell).not.toHaveTextContent("session total");+ });+ });++ describe("Type column", () => {+ it("shows the conversation badge and composition even when an MCP call represents the conversation", async () => {+ const user = userEvent.setup();+ const mcpRepresentative = {+ request_id: "req-mcp-rep",+ call_type: "call_mcp_tool",+ session_id: "sess-edge",+ session_total_count: 3,+ session_llm_count: 2,+ mcp_tool_call_count: 1,+ session_agent_count: 0,+ };+ renderRows([logEntry(mcpRepresentative)]);++ expect(screen.queryByText("MCP")).not.toBeInTheDocument();+ await user.hover(screen.getByText("3"));+ expect(await screen.findByText("2 LLM • 1 MCP")).toBeInTheDocument();+ });++ it("keeps the plain MCP badge for a single MCP call", () => {+ renderRows([logEntry({ request_id: "req-mcp-solo", call_type: "call_mcp_tool", session_total_count: 1 })]);++ expect(screen.getByText("MCP")).toBeInTheDocument();+ });++ it("marks a batch cost row with the Batch badge instead of LLM", () => {+ renderRows([logEntry({ request_id: "batch_1_batch_cost", call_type: "aretrieve_batch" })]);++ expect(screen.getByText("Batch")).toBeInTheDocument();+ expect(screen.queryByText("LLM")).not.toBeInTheDocument();+ });++ it("keeps the Batch label on the grouped create-plus-cost session instead of a row count", () => {+ const groupedCostRow: Partial<LogEntry> = {+ request_id: "batch_1_batch_cost",+ call_type: "aretrieve_batch",+ session_id: "batch_1",+ session_total_count: 2,+ };+ renderRows([logEntry(groupedCostRow)]);++ expect(screen.getByText("Batch")).toBeInTheDocument();+ expect(screen.queryByText("2")).not.toBeInTheDocument();+ });+ });++ describe("batch rows", () => {+ const batchRow = (overrides: Partial<LogEntry>): LogEntry =>+ logEntry({+ request_id: "batch_abc123_batch_cost",+ call_type: "aretrieve_batch",+ ...overrides,+ });++ it("rolls partial failures into the status badge instead of reporting blanket Success", async () => {+ const user = userEvent.setup();+ renderRows([batchRow({ metadata: { batch_successful_requests: 2, batch_failed_requests: 1 } })]);++ expect(screen.queryByText("Success")).not.toBeInTheDocument();+ await user.hover(screen.getByText("2/3 succeeded"));+ expect(await screen.findByText("1 of 3 batch requests failed")).toBeInTheDocument();+ });++ it("keeps the Success badge when every batch request succeeded", () => {+ renderRows([batchRow({ metadata: { batch_successful_requests: 3, batch_failed_requests: 0 } })]);++ expect(screen.getByText("Success")).toBeInTheDocument();+ });++ it("keeps the Failure badge when the batch row itself failed, whatever the counts say", () => {+ renderRows([batchRow({ metadata: { status: "failure", batch_successful_requests: 2, batch_failed_requests: 1 } })]);++ expect(screen.getByText("Failure")).toBeInTheDocument();+ expect(screen.queryByText("2/3 succeeded")).not.toBeInTheDocument();+ });++ it("shows the provider batch id, not the synthetic _batch_cost request id", () => {+ renderRows([batchRow({ metadata: { batch_successful_requests: 1, batch_failed_requests: 0 } })]);++ expect(screen.getByText("batch_abc123")).toBeInTheDocument();+ expect(screen.queryByText("batch_abc123_batch_cost")).not.toBeInTheDocument();+ expect(screen.getByText("batch cost")).toBeInTheDocument();+ });++ it("leaves ordinary request ids untouched", () => {+ renderRows([logEntry({ request_id: "chatcmpl-42" })]);++ expect(screen.getByText("chatcmpl-42")).toBeInTheDocument();+ expect(screen.queryByText("batch cost")).not.toBeInTheDocument();+ });+ });++ describe("Model column", () => {+ it("lists every model used across a conversation, not only the representative call's model", () => {+ const conversationCall: Partial<LogEntry> = {+ request_id: "req-session",+ model: "gpt-5.6",+ session_id: "sess-1",+ session_total_count: 3,+ session_models: ["claude-sonnet-5", "gpt-5.6"],+ };+ renderRows([logEntry(conversationCall)]);++ expect(screen.getByText("claude-sonnet-5, gpt-5.6")).toBeInTheDocument();+ expect(screen.queryByText("gpt-5.6")).not.toBeInTheDocument();+ });++ it("marks a conversation whose model list was capped by the server", () => {+ const cappedCall = {+ request_id: "req-capped",+ model: "gpt-5.6",+ session_id: "sess-2",+ session_total_count: 30,+ session_models: ["claude-sonnet-5", "gpt-5.6"],+ session_models_truncated: true,+ };+ renderRows([logEntry(cappedCall)]);++ expect(screen.getByText("claude-sonnet-5, gpt-5.6, ...")).toBeInTheDocument();+ });++ it("keeps a single call's own model", () => {+ renderRows([logEntry({ request_id: "req-single", model: "gpt-5.6" })]);++ expect(screen.getByText("gpt-5.6")).toBeInTheDocument();+ });+ });+describe("row action cells", () => {it("reports the key hash through the injected dependency rather than a row field", async () => {const user = userEvent.setup();diff --cc ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsxindex 1bd7c5c8dba,1ec1087a1a4..ea171df5082--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsx@@@ -144,9 -173,9 +174,9 @@@ export const getRequestLogsTableColumnreturn (<div className="flex flex-col items-end">{spend ? <CellTooltip content={`$${String(spend)}`} trigger={money} /> : money}- {sessionTotalSpend != null && <span className="text-[10px] text-gray-400">session total</span>}- {isMultiCallSession && <span className="text-[10px] text-muted-foreground">session total</span>}++ {sessionTotalSpend != null && <span className="text-[10px] text-muted-foreground">session total</span>}{mcpCount > 0 && mcpSpend > 0 && (- <span className="text-[10px] text-amber-600">+ <span className="text-[10px] text-warning">incl. {getSpendString(mcpSpend)} from {mcpCount} MCP</span>)}@@@ -161,19 -190,13 +191,19 @@@enableSorting: true,meta: { numeric: true },cell: ({ row }) => {- const ms = row.original.request_duration_ms;+ const log = row.original;+ const isMultiCallSession = (log.session_total_count || 1) > 1;+ const sessionTotalMs = isMultiCallSession ? log.session_total_duration_ms : undefined;+ const ms = sessionTotalMs ?? log.request_duration_ms;if (ms == null) return <span>-</span>;return (- <CellTooltip- content={`${ms}ms`}- trigger={<span className="max-w-[15ch] truncate inline-block">{(ms / 1000).toFixed(2)}</span>}- />+ <div className="flex flex-col items-end">+ <CellTooltip+ content={`${ms}ms`}+ trigger={<span className="max-w-[15ch] truncate inline-block">{(ms / 1000).toFixed(2)}</span>}+ />- {sessionTotalMs != null && <span className="text-[10px] text-gray-400">session total</span>}++ {sessionTotalMs != null && <span className="text-[10px] text-muted-foreground">session total</span>}+ </div>);},},diff --cc ui/litellm-dashboard/src/components/view_logs/columns.tsxindex 5b89c6f282c,0a2b22b95e4..ce4a72a6d38--- a/ui/litellm-dashboard/src/components/view_logs/columns.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/columns.tsx@@@ -42,7 -43,10 +43,11 @@@ export type LogEntry =request_duration_ms?: number;session_total_count?: number;session_total_spend?: number;+ session_total_duration_ms?: number;+ session_total_tokens?: number;+ session_total_prompt_tokens?: number;+ session_total_completion_tokens?: number;+ session_cache_hit_count?: number;mcp_tool_call_count?: number;mcp_tool_call_spend?: number;session_llm_count?: number;