diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py index 13e9e5093a80..e18e4fd8578e 100644 --- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py +++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py @@ -10,6 +10,7 @@ from litellm._logging import verbose_proxy_logger from litellm._uuid import uuid from litellm.constants import ( + CLI_SESSION_KEY_PREFIX, MANAGED_OBJECT_STALENESS_CUTOFF_DAYS, MAX_OBJECTS_PER_POLL_CYCLE, ) @@ -112,10 +113,12 @@ async def _get_user_info(self, batch_id: str, user_id: Optional[str]) -> dict[st verbose_proxy_logger.error(f"CheckBatchCost: could not look up user {user_id} for batch {batch_id}: {e}") return {} - async def _get_key_alias(self, batch_id: str, api_key: str | None) -> str | None: + async def _get_key_alias(self, batch_id: str, api_key: str | None, created_by: str | None) -> str | None: """Resolve the creating virtual key's alias from its hashed token.""" if not api_key: return None + if created_by and api_key == f"{CLI_SESSION_KEY_PREFIX}-{created_by}": + return api_key try: key_row: prisma_models.LiteLLM_VerificationToken | None = ( await self.prisma_client.db.litellm_verificationtoken.find_unique( @@ -204,7 +207,7 @@ async def _build_creator_attribution_metadata( **(await self._get_user_info(batch_id, job.created_by)), } - key_alias = await self._get_key_alias(batch_id, api_key) + key_alias = await self._get_key_alias(batch_id, api_key, job.created_by) if key_alias is not None: metadata["user_api_key_alias"] = key_alias team_alias = await self._get_team_alias(team_id) diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py index 09cd0ed192f0..83dd91471d94 100644 --- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py +++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py @@ -50,6 +50,7 @@ ProxyException, UserAPIKeyAuth, ) +from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup from litellm.proxy.openai_files_endpoints.common_utils import ( BATCH_CREATE_HIDDEN_PARAM, FILE_LIST_CONTINUATION_CHUNK_SIZE, @@ -359,7 +360,7 @@ async def store_unified_object_id( from prisma import Json - api_key = user_api_key_dict.api_key or None + api_key = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) or None attribution_columns = ( { **({"api_key": api_key} if api_key is not None else {}), diff --git a/enterprise/pyproject.toml b/enterprise/pyproject.toml index 729f3264706c..be4ce9ab5079 100644 --- a/enterprise/pyproject.toml +++ b/enterprise/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "litellm-enterprise" -version = "0.1.69" +version = "0.1.69.post1" description = "Package for LiteLLM Enterprise features" readme = "README.md" requires-python = ">=3.9" @@ -26,7 +26,7 @@ required-version = ">=0.10.9" module-root = "" [tool.commitizen] -version = "0.1.69" +version = "0.1.69.post1" version_files = [ "pyproject.toml:^version", "../pyproject.toml:litellm-enterprise==", diff --git a/litellm/constants.py b/litellm/constants.py index edfcf67f2128..8871978d440b 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -1861,6 +1861,7 @@ SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL: Final = 30 SPEND_LOG_KEY_METADATA_CACHE_MAX_ITEMS: Final = 10000 SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS: Final = 5000 +SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE: Final = 100 # Short TTL for negative MCP access-group existence lookups. Keeps unauthenticated # callers from forcing a DB query per request for unknown names, while bounding # staleness so a transient DB error (which surfaces as an empty list) cannot diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 37b7344917e5..aff1934f959d 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -2553,6 +2553,7 @@ async def async_post_call_failure_hook( from litellm.litellm_core_utils.litellm_logging import ( StandardLoggingPayloadSetup, ) + from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup status_code: Final = self._extract_status_code(exception=original_exception) @@ -2571,7 +2572,9 @@ async def async_post_call_failure_hook( end_user=user_api_key_dict.end_user_id, user=user_api_key_dict.user_id, user_email=user_api_key_dict.user_email, - hashed_api_key=None if status_code == 401 else user_api_key_dict.api_key, + hashed_api_key=None + if status_code == 401 + else LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict), api_key_alias=user_api_key_dict.key_alias, team=user_api_key_dict.team_id, team_alias=user_api_key_dict.team_alias, diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index 6a4c67c7db1f..84d94f5425bb 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -1638,7 +1638,7 @@ def _build_search_request_metadata( return { # mutable-ok: litellm's metadata channel is a plain dict its logging path reads and enriches **user_api_key_metadata, "model_group": search_tool_name, - "user_api_key": user_api_key_auth.api_key, + "user_api_key": LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_auth), "user_api_key_auth": user_api_key_auth, } diff --git a/litellm/proxy/batches_endpoints/litellm_executed_batches.py b/litellm/proxy/batches_endpoints/litellm_executed_batches.py index 67201d99422b..caf34404a7d8 100644 --- a/litellm/proxy/batches_endpoints/litellm_executed_batches.py +++ b/litellm/proxy/batches_endpoints/litellm_executed_batches.py @@ -656,7 +656,7 @@ def _router_call(self, endpoint: BatchEndpoint) -> _RouterCall: def _row_metadata(self, run: _BatchRun) -> dict[str, object]: # mutable-ok: router updates metadata in place return { # mutable-ok: the router updates request metadata in place **LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(run.user_api_key_dict), - "user_api_key": run.user_api_key_dict.api_key, + "user_api_key": LiteLLMProxyRequestSetup.get_logged_api_key(run.user_api_key_dict), "user_api_end_user_max_budget": run.user_api_key_dict.end_user_max_budget, "tags": list(run.request_tags), # mutable-ok: litellm types request tags as a list "batch_id": run.unified_batch_id, diff --git a/litellm/proxy/common_utils/semantic_text_index.py b/litellm/proxy/common_utils/semantic_text_index.py index b8d3595163e6..d3fe68e65f73 100644 --- a/litellm/proxy/common_utils/semantic_text_index.py +++ b/litellm/proxy/common_utils/semantic_text_index.py @@ -68,7 +68,7 @@ def embedding_spend_metadata(user_api_key_dict: UserAPIKeyAuth) -> dict[str, obj return { # mutable-ok: the router mutates the metadata dict it is handed **LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(user_api_key_dict), - "user_api_key": user_api_key_dict.api_key, + "user_api_key": LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict), } diff --git a/litellm/proxy/hooks/parallel_request_limiter.py b/litellm/proxy/hooks/parallel_request_limiter.py index b313cb64c3fb..7bfb2de99605 100644 --- a/litellm/proxy/hooks/parallel_request_limiter.py +++ b/litellm/proxy/hooks/parallel_request_limiter.py @@ -20,6 +20,7 @@ from litellm.proxy.auth.budget_throttle import throttled_limit from litellm.proxy.common_utils.proxy_rate_limit_error import ProxyRateLimitError from litellm.proxy.hooks.rate_limiter_utils import resolve_llm_provider_for_rate_limit +from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup from litellm.types.utils import Usage if TYPE_CHECKING: @@ -250,7 +251,7 @@ async def async_pre_call_hook( call_type: str, ): self.print_verbose("Inside Max Parallel Request Pre-Call Hook") - api_key: Final = user_api_key_dict.api_key + api_key: Final = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) max_parallel_requests = user_api_key_dict.max_parallel_requests if max_parallel_requests is None: max_parallel_requests = sys.maxsize @@ -803,7 +804,7 @@ async def async_post_call_success_hook(self, data: dict, user_api_key_dict: User """ Retrieve the key's remaining rate limits. """ - api_key: Final = user_api_key_dict.api_key + api_key: Final = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) current_date: Final = datetime.now().strftime("%Y-%m-%d") current_hour: Final = datetime.now().strftime("%H") current_minute: Final = datetime.now().strftime("%M") diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.py index b38fb8562154..425466396f42 100644 --- a/litellm/proxy/hooks/proxy_track_cost_callback.py +++ b/litellm/proxy/hooks/proxy_track_cost_callback.py @@ -163,7 +163,7 @@ async def async_post_call_failure_hook( _metadata = dict( LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(user_api_key_dict=user_api_key_dict) ) - _metadata["user_api_key"] = user_api_key_dict.api_key + _metadata["user_api_key"] = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) _metadata["status"] = "failure" _error_information = StandardLoggingPayloadSetup.get_error_information( original_exception=original_exception, @@ -257,7 +257,7 @@ async def async_post_call_failure_hook( ) await self._spend_writer().update_database( - token=user_api_key_dict.api_key, + token=LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict), response_cost=recovered_response_cost, user_id=user_api_key_dict.user_id, end_user_id=user_api_key_dict.end_user_id, diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py index 9a9737558942..2376648f701a 100644 --- a/litellm/proxy/litellm_pre_call_utils.py +++ b/litellm/proxy/litellm_pre_call_utils.py @@ -1602,6 +1602,12 @@ def add_litellm_metadata_from_request_headers( data[_metadata_variable_name].update(metadata_from_headers) return data + @staticmethod + def get_logged_api_key(user_api_key_dict: UserAPIKeyAuth) -> str | None: + if user_api_key_dict.is_session_token and user_api_key_dict.key_alias: + return user_api_key_dict.key_alias + return user_api_key_dict.api_key + @staticmethod def get_sanitized_user_information_from_key( user_api_key_dict: UserAPIKeyAuth, @@ -1609,7 +1615,7 @@ def get_sanitized_user_information_from_key( stripped_metadata: Final = strip_callback_config(user_api_key_dict.metadata) auth_metadata: Final = cast("dict[str, str] | None", stripped_metadata) # cast-ok: metadata is free-form JSON user_api_key_logged_metadata: Final = StandardLoggingUserAPIKeyMetadata( - user_api_key_hash=user_api_key_dict.api_key, # just the hashed token + user_api_key_hash=LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict), user_api_key_alias=user_api_key_dict.key_alias, user_api_key_spend=user_api_key_dict.spend, user_api_key_max_budget=user_api_key_dict.max_budget, @@ -1647,7 +1653,7 @@ def add_user_api_key_auth_to_request_metadata( user_api_key_dict=user_api_key_dict ) data[_metadata_variable_name].update(user_api_key_logged_metadata) - data[_metadata_variable_name]["user_api_key"] = user_api_key_dict.api_key # this is just the hashed token + data[_metadata_variable_name]["user_api_key"] = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) # Key-owned agent_id for spend attribution; keep existing (e.g. from header) if key has none _key_agent_id: Final = getattr(user_api_key_dict, "agent_id", None) diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.py index b22d57170a4f..644e9e2cbd5d 100644 --- a/litellm/proxy/management_endpoints/common_daily_activity.py +++ b/litellm/proxy/management_endpoints/common_daily_activity.py @@ -12,9 +12,11 @@ from litellm.constants import PTU_SENTINEL_API_KEY from litellm.proxy._types import CommonProxyErrors from litellm.proxy.spend_tracking.key_metadata_recovery import ( - attach_user_emails, + attach_user_details, + recover_cli_session_key_metadata, recover_double_hashed_key_metadata, recover_key_metadata_from_spend_logs, + recover_key_owner_from_daily_spend, ) from litellm.proxy.spend_tracking.ptu_feature_flag import is_ptu_cost_attribution_enabled from litellm.proxy.utils import PrismaClient @@ -466,6 +468,17 @@ def _parse_spend_date(raw: str | None) -> datetime | None: _EMPTY_KEY_METADATA: Final[Mapping[str, _KeyMetadataDict]] = MappingProxyType({}) +def _metadata_with_recovered_owner( + metadata: Mapping[str, _KeyMetadataDict], + key: str, + owner: str, +) -> _KeyMetadataDict: + current: Final = metadata.get(key) + if current is None: + return {"user_id": owner} + return {**current, "user_id": owner} + + async def get_api_key_metadata( prisma_client: PrismaClient, api_keys: AbstractSet[str], @@ -515,11 +528,12 @@ async def get_api_key_metadata( e, ) - still_missing: Final = api_keys - frozenset(result) + from_session_keys: Final = await recover_cli_session_key_metadata(prisma_client, api_keys - frozenset(result)) + still_missing: Final = api_keys - frozenset(result) - frozenset(from_session_keys) from_reverse_hash: Final = ( await recover_double_hashed_key_metadata(prisma_client, still_missing) if still_missing else _EMPTY_KEY_METADATA ) - after_token_recovery: Final = MappingProxyType({**result, **from_reverse_hash}) + after_token_recovery: Final = MappingProxyType({**result, **from_session_keys, **from_reverse_hash}) unresolved: Final = api_keys - frozenset(after_token_recovery) from_spend_logs: Final = ( await recover_key_metadata_from_spend_logs(prisma_client, unresolved, spend_logs_window) @@ -527,7 +541,19 @@ async def get_api_key_metadata( else _EMPTY_KEY_METADATA ) combined: Final = MappingProxyType({**after_token_recovery, **from_spend_logs}) - return await attach_user_emails(prisma_client, combined) + ownerless: Final = frozenset( + key + for key in api_keys + if not combined.get(key, {}).get("user_id") and not combined.get(key, {}).get("key_exists") + ) + owners: Final = await recover_key_owner_from_daily_spend(prisma_client, ownerless) + metadata_with_owners: Final[Mapping[str, _KeyMetadataDict]] = MappingProxyType( + { + **combined, + **{key: _metadata_with_recovered_owner(combined, key, owner) for key, owner in owners.items()}, + } + ) + return await attach_user_details(prisma_client, metadata_with_owners) def _adjust_dates_for_timezone( @@ -941,7 +967,7 @@ async def _aggregate_spend_records( record.api_key for record in records if record.api_key and record.api_key != PTU_SENTINEL_API_KEY } - api_key_metadata: dict[str, _KeyMetadataDict] = {} + api_key_metadata: Mapping[str, _KeyMetadataDict] = MappingProxyType({}) if api_keys: api_key_metadata = await get_api_key_metadata( prisma_client, api_keys, _spend_logs_window(frozenset(record.date for record in records)) @@ -1141,7 +1167,7 @@ async def _aggregate_grouping_sets_records( """Async wrapper: fetch api_key_metadata, then dispatch on a worker thread.""" api_keys: Final[set[str]] = {r.api_key for r in records if r.api_key and r.api_key != PTU_SENTINEL_API_KEY} - api_key_metadata: dict[str, _KeyMetadataDict] = {} + api_key_metadata: Mapping[str, _KeyMetadataDict] = MappingProxyType({}) if api_keys: api_key_metadata = await get_api_key_metadata( prisma_client, api_keys, _spend_logs_window(frozenset(r.date for r in records)) diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index 79a328f5199d..b4fe8800f41e 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -596,7 +596,7 @@ def _init_kwargs_for_pass_through_endpoint( # body that mirrors them cannot clobber the authenticated key, the real # parent span, or the proxy's own session-id decision. _metadata.pop(SESSION_ID_OMITTED_METADATA_KEY, None) - _metadata["user_api_key"] = user_api_key_dict.api_key + _metadata["user_api_key"] = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) _metadata["litellm_parent_otel_span"] = user_api_key_dict.parent_otel_span _metadata["user_api_key_budget_reservation"] = user_api_key_dict.budget_reservation _metadata[MODEL_ACCESS_GROUP_METADATA_KEY] = user_api_key_dict.matched_model_access_groups diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 7ad10a870a83..52b7200d1e9a 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -514,7 +514,7 @@ def generate_feedback_box(): problem_response, request_validation_problem, ) -from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request +from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup, add_litellm_data_to_request from litellm.proxy.logging_endpoints.callback_logs_endpoints import ( rust_control_plane_router, ) @@ -16032,8 +16032,9 @@ async def async_queue_request( # Covers both missing and JSON-string metadata (multipart / # extra_body); see above for the same guard upstream. data["metadata"] = {} - data["metadata"]["user_api_key"] = user_api_key_dict.api_key - data["metadata"]["user_api_key_hash"] = user_api_key_dict.api_key + logged_api_key: Final = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict) + data["metadata"]["user_api_key"] = logged_api_key + data["metadata"]["user_api_key_hash"] = logged_api_key data["metadata"]["user_api_key_metadata"] = strip_callback_config(user_api_key_dict.metadata) _headers: Final = _safe_get_request_headers(request).copy() _headers.pop("authorization", None) # do not store the original `sk-..` api key in the db diff --git a/litellm/proxy/spend_tracking/key_metadata_recovery.py b/litellm/proxy/spend_tracking/key_metadata_recovery.py index ee2e1cfeaf70..9cc02a74c990 100644 --- a/litellm/proxy/spend_tracking/key_metadata_recovery.py +++ b/litellm/proxy/spend_tracking/key_metadata_recovery.py @@ -1,9 +1,10 @@ import asyncio from collections.abc import Awaitable, Callable, Mapping, Sequence from collections.abc import Set as AbstractSet +from dataclasses import dataclass from datetime import datetime, timedelta from types import MappingProxyType -from typing import Final, TypeVar +from typing import Final, Literal, TypeVar from pydantic import BaseModel, TypeAdapter from typing_extensions import ReadOnly, TypedDict @@ -11,10 +12,12 @@ from litellm._logging import verbose_proxy_logger from litellm.caching.in_memory_cache import InMemoryCache from litellm.constants import ( + CLI_SESSION_KEY_PREFIX, SPEND_LOG_KEY_METADATA_CACHE_MAX_ITEMS, SPEND_LOG_KEY_METADATA_CACHE_TTL, SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL, SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS, + SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE, ) from litellm.litellm_core_utils.litellm_logging import is_valid_sha256_hash from litellm.proxy.utils import PrismaClient @@ -36,32 +39,73 @@ ORDER BY token, deleted_at DESC """ -_SPEND_LOG_ALIAS_SQL: Final = """ -SELECT api_key AS digest, - MIN(key_alias) AS first_alias, - MAX(key_alias) AS last_alias, - MIN(team_id) AS first_team, - MAX(team_id) AS last_team, - MIN(user_id) AS first_owner, - MAX(user_id) AS last_owner -FROM ( - SELECT api_key, - NULLIF(metadata->>'user_api_key_alias', '') AS key_alias, - COALESCE(NULLIF(team_id, ''), NULLIF(metadata->>'user_api_key_team_id', '')) AS team_id, - COALESCE(NULLIF("user", ''), NULLIF(metadata->>'user_api_key_user_id', '')) AS user_id - FROM "LiteLLM_SpendLogs" - WHERE api_key = ANY($1::text[]) - AND "startTime" >= $2::timestamp - AND "startTime" < $3::timestamp -) named -WHERE COALESCE(key_alias, user_id, team_id) IS NOT NULL + +def _named_spend_log_edge_row_sql( + direction: Literal["ASC", "DESC"], since: Literal["$2::timestamp", "oldest_probe.stopped_at"] +) -> str: + return f""" + SELECT "startTime", key_alias, team_id, user_id + FROM ( + SELECT "startTime", + NULLIF(metadata->>'user_api_key_alias', '') AS key_alias, + COALESCE(NULLIF(team_id, ''), NULLIF(metadata->>'user_api_key_team_id', '')) AS team_id, + COALESCE(NULLIF("user", ''), NULLIF(metadata->>'user_api_key_user_id', '')) AS user_id + FROM ( + SELECT "startTime", metadata, team_id, "user" + FROM "LiteLLM_SpendLogs" + WHERE api_key = keys.digest + AND "startTime" >= {since} + AND "startTime" < $3::timestamp + ORDER BY "startTime" {direction} + LIMIT {SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE} + ) edge + ) named + WHERE COALESCE(key_alias, user_id, team_id) IS NOT NULL + ORDER BY "startTime" {direction} + LIMIT 1 + """ + + +_OLDEST_PROBE_STOPPED_AT_SQL: Final = f""" + SELECT COALESCE(first_row."startTime", ( + SELECT "startTime" + FROM "LiteLLM_SpendLogs" + WHERE api_key = keys.digest + AND "startTime" >= $2::timestamp + AND "startTime" < $3::timestamp + ORDER BY "startTime" ASC + OFFSET {SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE - 1} + LIMIT 1 + )) AS stopped_at +""" + +_SPEND_LOG_ALIAS_SQL: Final = f""" +SELECT keys.digest, + first_row.key_alias AS first_alias, + last_row.key_alias AS last_alias, + first_row.team_id AS first_team, + last_row.team_id AS last_team, + first_row.user_id AS first_owner, + last_row.user_id AS last_owner +FROM unnest($1::text[]) AS keys(digest) +LEFT JOIN LATERAL ({_named_spend_log_edge_row_sql("ASC", "$2::timestamp")}) first_row ON true +LEFT JOIN LATERAL ({_OLDEST_PROBE_STOPPED_AT_SQL}) oldest_probe ON true +LEFT JOIN LATERAL ({_named_spend_log_edge_row_sql("DESC", "oldest_probe.stopped_at")}) last_row ON true +""" + +_DAILY_USER_SPEND_OWNER_SQL: Final = """ +SELECT api_key, MIN(user_id) AS first_owner, MAX(user_id) AS last_owner +FROM "LiteLLM_DailyUserSpend" +WHERE api_key = ANY($1::text[]) AND user_id IS NOT NULL AND user_id <> '' GROUP BY api_key """ _SPEND_LOG_STATEMENT_TIMEOUT_SQL: Final = f"SET LOCAL statement_timeout = {SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS}" +_SPEND_LOG_NO_BITMAP_SCAN_SQL: Final = "SET LOCAL enable_bitmapscan = off" _SPEND_LOG_TRANSACTION_TIMEOUT: Final = timedelta(milliseconds=2 * SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS) _HASHED_JWT_PREFIX: Final = "hashed-jwt-" +_CLI_SESSION_KEY_PREFIX: Final = f"{CLI_SESSION_KEY_PREFIX}-" class KeyMetadataDict(TypedDict, total=False): @@ -80,7 +124,9 @@ class _TokenDigestRow(BaseModel): def _unanimous(first: str | None, last: str | None) -> str | None: - return first if first == last else None + if first is None: + return last + return first if last is None or first == last else None class _SpendLogDigestRow(BaseModel): @@ -100,8 +146,15 @@ def metadata(self) -> KeyMetadataDict: ) +class _DailyUserSpendOwnerRow(BaseModel): + api_key: str + first_owner: str | None = None + last_owner: str | None = None + + _TOKEN_DIGEST_ROWS: Final = TypeAdapter(tuple[_TokenDigestRow, ...]) _SPEND_LOG_DIGEST_ROWS: Final = TypeAdapter(tuple[_SpendLogDigestRow, ...]) +_DAILY_USER_SPEND_OWNER_ROWS: Final = TypeAdapter(tuple[_DailyUserSpendOwnerRow, ...]) _CACHED_KEY_METADATA: Final = TypeAdapter(KeyMetadataDict) _SPEND_LOG_METADATA_CACHE: Final = InMemoryCache( max_size_in_memory=SPEND_LOG_KEY_METADATA_CACHE_MAX_ITEMS, @@ -109,7 +162,7 @@ def metadata(self) -> KeyMetadataDict: ) _SPEND_LOG_QUERY_LOCK: Final = asyncio.Lock() _EMPTY_KEY_METADATA: Final[Mapping[str, KeyMetadataDict]] = MappingProxyType({}) -_EMPTY_EMAILS: Final[Mapping[str, str]] = MappingProxyType({}) +_EMPTY_KEY_OWNERS: Final[Mapping[str, str]] = MappingProxyType({}) async def _db_or_empty( @@ -126,6 +179,19 @@ async def _db_or_empty( return None +async def _rows_within_the_statement_timeout( + prisma_client: PrismaClient, + sql: str, + *params: object, + planner_settings: tuple[str, ...] = (), +) -> Sequence[Mapping[str, object]]: + async with prisma_client.db.tx(timeout=_SPEND_LOG_TRANSACTION_TIMEOUT) as transaction: + await transaction.execute_raw(_SPEND_LOG_STATEMENT_TIMEOUT_SQL) + for setting in planner_settings: + await transaction.execute_raw(setting) + return await transaction.query_raw(sql, *params) + + async def _reverse_hash_key_metadata( prisma_client: PrismaClient, sql: str, @@ -149,54 +215,130 @@ async def _reverse_hash_key_metadata( ) -async def _emails_for_user_ids( +async def recover_key_owner_from_daily_spend( prisma_client: PrismaClient, - user_ids: AbstractSet[str], + keys: AbstractSet[str], ) -> Mapping[str, str]: + if not keys: + return _EMPTY_KEY_OWNERS + rows: Final = await _db_or_empty( + lambda: _rows_within_the_statement_timeout(prisma_client, _DAILY_USER_SPEND_OWNER_SQL, sorted(keys)), + "Failed daily-spend key owner recovery for %d keys: %s", + len(keys), + ) + if rows is None: + return _EMPTY_KEY_OWNERS + return MappingProxyType( + { + row.api_key: owner + for row in _DAILY_USER_SPEND_OWNER_ROWS.validate_python(rows) + for owner in (_unanimous(row.first_owner, row.last_owner),) + if row.api_key in keys and owner is not None + } + ) + + +@dataclass(frozen=True, slots=True) +class _UserDetails: + email: str | None + only_team: str | None + + +_EMPTY_USER_DETAILS: Final[Mapping[str, _UserDetails]] = MappingProxyType({}) + + +async def _details_for_user_ids( + prisma_client: PrismaClient, + user_ids: AbstractSet[str], +) -> Mapping[str, _UserDetails]: if not user_ids: - return _EMPTY_EMAILS + return _EMPTY_USER_DETAILS users: Final = await _db_or_empty( lambda: UserRepository(prisma_client).table.find_many( where={"user_id": {"in": list(user_ids)}}, # mutable-ok: Prisma find_many where= is a dict ), - "Failed user_email recovery for %d user ids: %s", + "Failed user detail recovery for %d user ids: %s", len(user_ids), ) if users is None: - return _EMPTY_EMAILS + return _EMPTY_USER_DETAILS return MappingProxyType( { - user.user_id: user.user_email + user.user_id: _UserDetails( + email=getattr(user, "user_email", None) or None, + only_team=_only_team(getattr(user, "teams", None)), + ) for user in users - if getattr(user, "user_id", None) and getattr(user, "user_email", None) + if getattr(user, "user_id", None) } ) -def _meta_with_email(meta: KeyMetadataDict, emails: Mapping[str, str]) -> KeyMetadataDict: - if meta.get("user_email"): - return meta +def _only_team(teams: object) -> str | None: + if not isinstance(teams, list) or len(teams) != 1: + return None + team: Final = teams[0] + return team if isinstance(team, str) and team else None + + +def _is_cli_session_key(api_key: str) -> bool: + return api_key.startswith(_CLI_SESSION_KEY_PREFIX) and len(api_key) > len(_CLI_SESSION_KEY_PREFIX) + + +def _meta_with_user_details( + api_key: str, meta: KeyMetadataDict, details: Mapping[str, _UserDetails] +) -> KeyMetadataDict: user_id: Final = meta.get("user_id") - if not isinstance(user_id, str) or user_id not in emails: + if not isinstance(user_id, str) or user_id not in details: return meta - updated: Final[KeyMetadataDict] = {**meta, "user_email": emails[user_id]} + user: Final = details[user_id] + email: Final = meta.get("user_email") or user.email + team_id: Final = meta.get("team_id") or (user.only_team if _is_cli_session_key(api_key) else None) + updated: Final[KeyMetadataDict] = { + **meta, + **({"user_email": email} if email else {}), + **({"team_id": team_id} if team_id else {}), + } return updated -async def attach_user_emails( +async def attach_user_details( prisma_client: PrismaClient, recovered: Mapping[str, KeyMetadataDict], ) -> Mapping[str, KeyMetadataDict]: - needing_email: Final = frozenset( + needing_details: Final = frozenset( user_id - for meta in recovered.values() + for api_key, meta in recovered.items() for user_id in (meta.get("user_id"),) - if isinstance(user_id, str) and user_id and not meta.get("user_email") + if isinstance(user_id, str) + and user_id + and (not meta.get("user_email") or (_is_cli_session_key(api_key) and not meta.get("team_id"))) ) - emails: Final = await _emails_for_user_ids(prisma_client, needing_email) - if not emails: + details: Final = await _details_for_user_ids(prisma_client, needing_details) + if not details: return recovered - return MappingProxyType({api_key: _meta_with_email(meta, emails) for api_key, meta in recovered.items()}) + return MappingProxyType( + {api_key: _meta_with_user_details(api_key, meta, details) for api_key, meta in recovered.items()} + ) + + +async def recover_cli_session_key_metadata( + prisma_client: PrismaClient, + missing_keys: AbstractSet[str], +) -> Mapping[str, KeyMetadataDict]: + candidates: Final = MappingProxyType( + {key: key.removeprefix(_CLI_SESSION_KEY_PREFIX) for key in missing_keys if _is_cli_session_key(key)} + ) + if not candidates: + return _EMPTY_KEY_METADATA + known_users: Final = await _details_for_user_ids(prisma_client, frozenset(candidates.values())) + return MappingProxyType( + { + key: KeyMetadataDict(key_alias=key, user_id=user_id) + for key, user_id in candidates.items() + if user_id in known_users + } + ) async def recover_double_hashed_key_metadata( @@ -249,24 +391,21 @@ def _cached_spend_log_metadata( ) -async def _spend_log_rows_within_the_statement_timeout( - prisma_client: PrismaClient, - digests: AbstractSet[str], - window: tuple[datetime, datetime], -) -> Sequence[Mapping[str, object]]: - start, end = window - async with prisma_client.db.tx(timeout=_SPEND_LOG_TRANSACTION_TIMEOUT) as transaction: - await transaction.execute_raw(_SPEND_LOG_STATEMENT_TIMEOUT_SQL) - return await transaction.query_raw(_SPEND_LOG_ALIAS_SQL, sorted(digests), start, end) - - async def _query_spend_log_metadata( prisma_client: PrismaClient, digests: AbstractSet[str], window: tuple[datetime, datetime], ) -> Mapping[str, KeyMetadataDict] | None: + start, end = window rows: Final = await _db_or_empty( - lambda: _spend_log_rows_within_the_statement_timeout(prisma_client, digests, window), + lambda: _rows_within_the_statement_timeout( + prisma_client, + _SPEND_LOG_ALIAS_SQL, + sorted(digests), + start, + end, + planner_settings=(_SPEND_LOG_NO_BITMAP_SCAN_SQL,), + ), "Failed spend-log alias recovery for %d missing keys: %s", len(digests), ) @@ -384,9 +523,15 @@ async def fill_missing_api_key_aliases( if not missing_keys: return tuple(rows) - recovered: Final = await attach_user_emails( + from_session_keys: Final = await recover_cli_session_key_metadata(prisma_client, missing_keys) + recovered: Final = await attach_user_details( prisma_client, - await recover_double_hashed_key_metadata(prisma_client, missing_keys), + MappingProxyType( + { + **from_session_keys, + **await recover_double_hashed_key_metadata(prisma_client, missing_keys - frozenset(from_session_keys)), + } + ), ) if not recovered: return tuple(rows) diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py index a319535f7252..4f2ed21f2b75 100644 --- a/litellm/proxy/spend_tracking/spend_management_endpoints.py +++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py @@ -37,6 +37,7 @@ from litellm.proxy._types import * from litellm.proxy._types import ProviderBudgetResponse, ProviderBudgetResponseObject from litellm.proxy.auth.user_api_key_auth import user_api_key_auth +from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup # NOTE: Avoid module-level import from common_utils: proxy_server imports this # module while common_utils may pull proxy_server during init, which can leave @@ -1828,7 +1829,7 @@ async def get_key_spend_report( scoped_api_key = _resolve_spend_report_scope( user_api_key_dict=user_api_key_dict, requested=requested, - caller_value=user_api_key_dict.api_key, + caller_value=LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict), scope_name="api_key", ) db_response: Sequence[Mapping[str, object]] | None = await _query_raw_or_none( diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py index 8f85ecdd480e..1c51fb21d6e8 100644 --- a/litellm/proxy/spend_tracking/spend_tracking_utils.py +++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py @@ -14,6 +14,7 @@ import litellm from litellm._logging import verbose_proxy_logger from litellm.constants import ( + CLI_SESSION_KEY_PREFIX, EMPTY_MAPPING, LITELLM_PROXY_MASTER_KEY_ALIAS, LITELLM_TRUNCATED_PAYLOAD_FIELD, @@ -102,19 +103,28 @@ def _is_master_key(api_key: str | None, _master_key: str | None) -> bool: ) -def _is_non_secret_key_value(value: str) -> bool: +def _is_cli_session_alias(value: str, key_alias: object) -> bool: + return value.startswith(f"{CLI_SESSION_KEY_PREFIX}-") and value == key_alias + + +def _is_non_secret_key_value(value: str, *, key_alias: object = None) -> bool: return ( - value in _NON_SECRET_KEY_ALIASES or is_valid_sha256_hash(value) or _HASHED_JWT_RE.fullmatch(value) is not None + value in _NON_SECRET_KEY_ALIASES + or is_valid_sha256_hash(value) + or _HASHED_JWT_RE.fullmatch(value) is not None + or _is_cli_session_alias(value, key_alias) ) -def _redact_logged_api_key(value: str | None, *, already_redacted: bool = False) -> str | None: +def _redact_logged_api_key( + value: str | None, *, already_redacted: bool = False, key_alias: object = None +) -> str | None: if not isinstance(value, str) or not value: return None stripped: Final = re.sub(r"(?i)^bearer ", "", value) if not stripped: return None - if already_redacted and _is_non_secret_key_value(stripped): + if already_redacted and _is_non_secret_key_value(stripped, key_alias=key_alias): return stripped return hash_token(stripped) @@ -230,10 +240,15 @@ def _get_spend_logs_metadata( ) _raw_key: Final = clean_metadata.get("user_api_key") _trusted_hash: Final = metadata.get("user_api_key_hash") + _key_alias: Final = metadata.get("user_api_key_alias") _already_redacted: Final = ( - isinstance(_trusted_hash, str) and _is_non_secret_key_value(_trusted_hash) and _trusted_hash == _raw_key + isinstance(_trusted_hash, str) + and _is_non_secret_key_value(_trusted_hash, key_alias=_key_alias) + and _trusted_hash == _raw_key + ) + clean_metadata["user_api_key"] = _redact_logged_api_key( + _raw_key, already_redacted=_already_redacted, key_alias=_key_alias ) - clean_metadata["user_api_key"] = _redact_logged_api_key(_raw_key, already_redacted=_already_redacted) clean_metadata["applied_guardrails"] = applied_guardrails clean_metadata["batch_models"] = batch_models clean_metadata["batch_successful_requests"] = batch_successful_requests @@ -537,10 +552,13 @@ def get_logging_payload( standard_logging_completion_tokens = standard_logging_payload.get("completion_tokens", 0) standard_logging_total_tokens = standard_logging_payload.get("total_tokens", 0) _trusted_hash = metadata.get("user_api_key_hash") + _key_alias = metadata.get("user_api_key_alias") _key_already_redacted = ( - isinstance(_trusted_hash, str) and _is_non_secret_key_value(_trusted_hash) and _trusted_hash == api_key + isinstance(_trusted_hash, str) + and _is_non_secret_key_value(_trusted_hash, key_alias=_key_alias) + and _trusted_hash == api_key ) - api_key = _redact_logged_api_key(api_key, already_redacted=_key_already_redacted) or "" + api_key = _redact_logged_api_key(api_key, already_redacted=_key_already_redacted, key_alias=_key_alias) or "" if ( standard_logging_payload is not None @@ -548,7 +566,9 @@ def get_logging_payload( api_key = ( api_key or _redact_logged_api_key( - standard_logging_payload["metadata"].get("user_api_key_hash"), already_redacted=True + standard_logging_payload["metadata"].get("user_api_key_hash"), + already_redacted=True, + key_alias=standard_logging_payload["metadata"].get("user_api_key_alias"), ) or "" ) diff --git a/pyproject.toml b/pyproject.toml index bc943992c05f..64338ba38ffc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "litellm" -version = "1.103.1" +version = "1.103.2" description = "Library to easily interface with LLM API providers" readme = "README.md" requires-python = ">=3.10, <3.15" @@ -72,7 +72,7 @@ proxy = [ "httpx2>=2.5.0,<3", "pydantic>=2.12.0,<3", "litellm-proxy-extras==0.4.100", - "litellm-enterprise==0.1.69", + "litellm-enterprise==0.1.69.post1", "RestrictedPython>=8.5,<9.0", "rich>=13.9.4,<14.0", "InquirerPy>=0.3.4,<1.0", @@ -342,7 +342,7 @@ litellm-enterprise = { workspace = true } members = ["enterprise", "litellm-proxy-extras"] [tool.commitizen] -version = "1.103.1" +version = "1.103.2" version_files = [ "pyproject.toml:^version", ] diff --git a/tests/integration/_support/daily_activity.py b/tests/integration/_support/daily_activity.py new file mode 100644 index 000000000000..346fc156ea9b --- /dev/null +++ b/tests/integration/_support/daily_activity.py @@ -0,0 +1,302 @@ +import os +import uuid +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from datetime import datetime, timedelta +from hashlib import sha256 +from itertools import chain +from typing import Final + +import httpx +import psycopg +import pytest +from integration._support.client import Gateway, Scenario, object_value +from psycopg import sql +from psycopg.types.json import Jsonb +from pydantic import JsonValue + +USER_SPEND: Final = "LiteLLM_DailyUserSpend" +TEAM_SPEND: Final = "LiteLLM_DailyTeamSpend" +TAG_SPEND: Final = "LiteLLM_DailyTagSpend" +ORGANIZATION_SPEND: Final = "LiteLLM_DailyOrganizationSpend" +END_USER_SPEND: Final = "LiteLLM_DailyEndUserSpend" +AGENT_SPEND: Final = "LiteLLM_DailyAgentSpend" +DAY: Final = "2026-02-03" +AGGREGATED_USER_ACTIVITY: Final = "/user/daily/activity/aggregated" + +INSERT_DAILY_ROW: Final = sql.SQL( + "INSERT INTO {table} (id, {entity}, date, api_key, model, model_group, custom_llm_provider, prompt_tokens," + " completion_tokens, spend, api_requests, successful_requests, failed_requests, updated_at)" + " VALUES (gen_random_uuid()::text, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, now())" +) +DELETE_DAILY_ROWS: Final = sql.SQL("DELETE FROM {table} WHERE api_key = ANY(%s)") +INSERT_SPEND_LOG: Final = ( + 'INSERT INTO "LiteLLM_SpendLogs" (request_id, call_type, api_key, "startTime", "endTime", metadata)' + " VALUES (%s, 'acompletion', %s, %s::timestamp, %s::timestamp, %s)" +) +DELETE_SPEND_LOG: Final = 'DELETE FROM "LiteLLM_SpendLogs" WHERE request_id = %s' +INSERT_SPEND_LOG_ROW: Final = ( + 'INSERT INTO "LiteLLM_SpendLogs" (request_id, call_type, api_key, "startTime", "endTime", metadata, team_id, "user")' + " VALUES (%s, 'acompletion', %s, %s::timestamp, %s::timestamp, %s, %s, %s)" +) +DELETE_SPEND_LOG_ROWS: Final = 'DELETE FROM "LiteLLM_SpendLogs" WHERE request_id = ANY(%s)' +DELETE_KEY_ROW: Final = 'DELETE FROM "LiteLLM_VerificationToken" WHERE token = %s' +DELETE_ARCHIVED_KEY_ROW: Final = 'DELETE FROM "LiteLLM_DeletedVerificationToken" WHERE token = %s' +LOCK_TABLE: Final = sql.SQL("LOCK TABLE {table} IN ACCESS EXCLUSIVE MODE") +SPEND_LOGS_TABLE: Final = "LiteLLM_SpendLogs" +FIRST_SPEND_LOG_AT: Final = datetime(2026, 2, 3, 12, 0, 0) + + +@dataclass(frozen=True, slots=True) +class Route: + path: str + table: str + entity_column: str + entity_filter: str | None + + +ROUTES: Final = ( + Route("/user/daily/activity", USER_SPEND, "user_id", None), + Route(AGGREGATED_USER_ACTIVITY, USER_SPEND, "user_id", None), + Route("/team/daily/activity", TEAM_SPEND, "team_id", "team_ids"), + Route("/team/daily/activity/aggregated", TEAM_SPEND, "team_id", "team_ids"), + Route("/tag/daily/activity", TAG_SPEND, "tag", "tags"), + Route("/organization/daily/activity", ORGANIZATION_SPEND, "organization_id", "organization_ids"), + Route("/customer/daily/activity", END_USER_SPEND, "end_user_id", "end_user_ids"), + Route("/end_user/daily/activity", END_USER_SPEND, "end_user_id", "end_user_ids"), + Route("/agent/daily/activity", AGENT_SPEND, "agent_id", "agent_ids"), +) + + +def user_with_an_email(scenario: Scenario) -> tuple[str, str]: + email: Final = f"integration-{uuid.uuid4().hex}@example.com" + return scenario.user(user_email=email), email + + +def key_no_key_table_holds() -> str: + return f"integration-ownerless-{uuid.uuid4().hex}" + + +def digest_no_key_table_holds() -> str: + return sha256(uuid.uuid4().bytes).hexdigest() + + +def activity_of_key( + gateway: Gateway, path: str, api_key: str, *, reader: str | None = None, **filters: str +) -> httpx.Response: + return gateway.request( + "GET", path, params={"start_date": DAY, "end_date": DAY, "api_key": api_key, **filters}, key=reader + ) + + +@dataclass(frozen=True, slots=True) +class DailyRow: + table: str + entity_column: str + entity: str | None + api_key: str + date: str + model: str + provider: str + prompt_tokens: int + completion_tokens: int + spend: float + successful_requests: int + failed_requests: int + + +def _insert(connection: psycopg.Connection[tuple[object, ...]], row: DailyRow) -> None: + connection.execute( + INSERT_DAILY_ROW.format(table=sql.Identifier(row.table), entity=sql.Identifier(row.entity_column)), + ( + row.entity, + row.date, + row.api_key, + row.model, + row.model, + row.provider, + row.prompt_tokens, + row.completion_tokens, + row.spend, + row.successful_requests + row.failed_requests, + row.successful_requests, + row.failed_requests, + ), + ) + + +def insert_daily_rows(rows: Sequence[DailyRow], *, database_url: str | None = None) -> None: + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + for row in rows: + _insert(connection, row) + + +def delete_daily_rows(rows: Sequence[DailyRow], *, database_url: str | None = None) -> None: + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + for table in sorted({row.table for row in rows}): + connection.execute( + DELETE_DAILY_ROWS.format(table=sql.Identifier(table)), + (sorted({row.api_key for row in rows if row.table == table}),), + ) + + +@contextmanager +def daily_rows(rows: Sequence[DailyRow], *, database_url: str | None = None) -> Iterator[None]: + insert_daily_rows(rows, database_url=database_url) + try: + yield + finally: + delete_daily_rows(rows, database_url=database_url) + + +@contextmanager +def spend_log_naming_only_an_alias(request_id: str, api_key: str, started: str, alias: str) -> Iterator[None]: + with psycopg.connect(os.environ["DATABASE_URL"]) as connection: + connection.execute( + INSERT_SPEND_LOG, (request_id, api_key, started, started, Jsonb({"user_api_key_alias": alias})) + ) + try: + yield + finally: + with psycopg.connect(os.environ["DATABASE_URL"]) as connection: + connection.execute(DELETE_SPEND_LOG, (request_id,)) + + +@dataclass(frozen=True, slots=True) +class SpendLogRow: + started: str + metadata: JsonValue = None + team_id: str | None = None + user: str | None = None + + +def started_at(index: int) -> str: + return (FIRST_SPEND_LOG_AT + timedelta(seconds=index)).strftime("%Y-%m-%d %H:%M:%S") + + +def nameless_rows(count: int, first_index: int = 0) -> tuple[SpendLogRow, ...]: + return tuple(SpendLogRow(started_at(first_index + offset), {}) for offset in range(count)) + + +def named_row(index: int, alias: str) -> SpendLogRow: + return SpendLogRow(started_at(index), {"user_api_key_alias": alias}) + + +@contextmanager +def spend_logs_of_key( + api_key: str, rows: Sequence[SpendLogRow], *, database_url: str | None = None +) -> Iterator[tuple[str, ...]]: + request_ids: Final = tuple(f"integration-{uuid.uuid4().hex}" for _ in rows) + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + connection.cursor().executemany( + INSERT_SPEND_LOG_ROW, + tuple( + (request_id, api_key, row.started, row.started, Jsonb(row.metadata), row.team_id, row.user) + for request_id, row in zip(request_ids, rows, strict=True) + ), + ) + try: + yield request_ids + finally: + delete_spend_logs(request_ids, database_url=database_url) + + +def delete_spend_logs(request_ids: Sequence[str], *, database_url: str | None = None) -> None: + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + connection.execute(DELETE_SPEND_LOG_ROWS, (list(request_ids),)) + + +def purge_key_from_the_key_tables(digest: str, *, database_url: str | None = None) -> None: + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + connection.execute(DELETE_KEY_ROW, (digest,)) + connection.execute(DELETE_ARCHIVED_KEY_ROW, (digest,)) + + +@contextmanager +def locked_table(table: str, *, database_url: str | None = None) -> Iterator[None]: + with psycopg.connect(database_url or os.environ["DATABASE_URL"]) as connection: + connection.execute(LOCK_TABLE.format(table=sql.Identifier(table))) + try: + yield + finally: + connection.rollback() + + +def records_of_key(node: JsonValue, api_key: str) -> tuple[JsonValue, ...]: + if isinstance(node, list): + return tuple(chain.from_iterable(records_of_key(item, api_key) for item in node)) + if not isinstance(node, dict): + return () + nested: Final = tuple(chain.from_iterable(records_of_key(value, api_key) for value in node.values())) + return (node[api_key], *nested) if api_key in node else nested + + +def seeded_row(table: str, entity_column: str, entity: str | None, api_key: str, date: str) -> DailyRow: + return DailyRow(table, entity_column, entity, api_key, date, "gpt-4o-mini", "openai", 10, 5, 0.25, 1, 0) + + +def user_row(user: str | None, api_key: str, date: str) -> DailyRow: + return seeded_row(USER_SPEND, "user_id", user, api_key, date) + + +def seeded_metrics(rows: int) -> dict[str, float]: + return { + "spend": 0.25 * rows, + "prompt_tokens": 10 * rows, + "completion_tokens": 5 * rows, + "total_tokens": 15 * rows, + "api_requests": rows, + "successful_requests": rows, + } + + +def key_metadata( + *, + alias: str | None = None, + team: str | None = None, + user: str | None = None, + email: str | None = None, + exists: bool = False, +) -> dict[str, JsonValue]: + return {"key_alias": alias, "team_id": team, "user_id": user, "user_email": email, "key_exists": exists} + + +def counted(metrics: JsonValue) -> dict[str, JsonValue]: + return {name: value for name, value in object_value(metrics).items() if value} + + +def assert_key_reported( + response: httpx.Response, + api_key: str, + date: str, + metadata: Mapping[str, JsonValue], + metrics: Mapping[str, float], +) -> None: + assert response.status_code == 200, response.text + body: Final = object_value(response.json()) + records: Final = tuple(object_value(record) for record in records_of_key(body, api_key)) + assert records, response.text + assert all(record["metadata"] == metadata for record in records), response.text + assert all(counted(record["metrics"]) == pytest.approx(metrics) for record in records), response.text + days: Final = body["results"] + assert isinstance(days, list) and len(days) == 1, response.text + day: Final = object_value(days[0]) + assert day["date"] == date, response.text + assert counted(day["metrics"]) == pytest.approx(metrics), response.text + assert object_value(body["metadata"])["total_spend"] == pytest.approx(metrics["spend"]), response.text + + +def assert_key_owner_and_totals( + response: httpx.Response, + api_key: str, + metadata: Mapping[str, JsonValue], + totals: Mapping[str, float], +) -> None: + assert response.status_code == 200, response.text + body: Final = object_value(response.json()) + records: Final = tuple(object_value(record) for record in records_of_key(body, api_key)) + assert records, response.text + assert all(record["metadata"] == metadata for record in records), response.text + reported: Final = object_value(body["metadata"]) + assert {name: reported[name] for name in totals} == pytest.approx(totals), response.text diff --git a/tests/integration/_support/database.py b/tests/integration/_support/database.py index 283d26a632ea..6b8ec470c2d6 100644 --- a/tests/integration/_support/database.py +++ b/tests/integration/_support/database.py @@ -1,7 +1,12 @@ import os +import uuid +from collections.abc import Generator +from contextlib import contextmanager from typing import Final +from urllib.parse import urlsplit, urlunsplit import psycopg +from psycopg import sql from psycopg.rows import dict_row from pydantic import JsonValue, TypeAdapter @@ -12,3 +17,14 @@ def read_rows(query: str, parameters: tuple[str, ...]) -> list[dict[str, JsonVal with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as connection: connection.execute("SET TRANSACTION READ ONLY") return ROWS.validate_python(connection.execute(query, parameters).fetchall()) + + +@contextmanager +def scratch_database() -> Generator[str]: + name: Final = f"integration_{uuid.uuid4().hex}" + with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as admin: + admin.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(name))) + try: + yield urlunsplit(urlsplit(os.environ["DATABASE_URL"])._replace(path=f"/{name}")) + finally: + admin.execute(sql.SQL("DROP DATABASE {} WITH (FORCE)").format(sql.Identifier(name))) diff --git a/tests/integration/contracts.json b/tests/integration/contracts.json index e9fc2230805a..67c7df8ee7ee 100644 --- a/tests/integration/contracts.json +++ b/tests/integration/contracts.json @@ -1383,6 +1383,222 @@ ], "tests/integration/spend/test_team_member_spend_flush.py::test_fractional_member_spend_lands_after_a_whole_number_flush_on_the_same_connection": [ "quota_management.spend_tracking.team_member_spend_lands_after_zero_cost_flush" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[user_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[user_daily_activity_aggregated]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[team_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[team_daily_activity_aggregated]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[tag_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[organization_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[customer_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[end_user_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route[agent_daily_activity]": [ + "quota_management.spend_tracking.spend_log_alias.every_daily_activity_route" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[named_between_50_and_50_nameless]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[oldest_named_150_nameless_newer]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[newest_named_150_nameless_older]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[both_edges_named_150_nameless_between]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[100_nameless_named_99_nameless]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it[99_nameless_named_100_nameless]": [ + "quota_management.spend_tracking.spend_log_alias.window_edge_reported" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_named_only_in_the_middle_of_two_hundred_nameless_rows_is_not_picked_up": [ + "quota_management.spend_tracking.spend_log_alias.middle_of_nameless_rows_not_picked_up" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_key_renamed_and_renamed_back_is_reported_with_the_alias_on_both_edges": [ + "quota_management.spend_tracking.spend_log_alias.rename_and_rename_back_both_edges" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_team_named_only_by_a_spend_log_is_reported_next_to_the_daily_owner[team_id_column]": [ + "quota_management.spend_tracking.spend_log_alias.team_next_to_daily_owner" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_team_named_only_by_a_spend_log_is_reported_next_to_the_daily_owner[team_id_in_metadata]": [ + "quota_management.spend_tracking.spend_log_alias.team_next_to_daily_owner" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_user_named_by_a_spend_log_beats_the_owner_the_daily_rows_name[user_column]": [ + "quota_management.spend_tracking.spend_log_alias.user_beats_daily_owner" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_user_named_by_a_spend_log_beats_the_owner_the_daily_rows_name[user_id_in_metadata]": [ + "quota_management.spend_tracking.spend_log_alias.user_beats_daily_owner" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_hashed_jwt_digest_is_named_by_its_spend_log": [ + "quota_management.spend_tracking.spend_log_alias.hashed_jwt_digest" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_spend_log_names_the_key_only_from_one_day_before_to_two_days_after_the_read[second_before_the_window]": [ + "quota_management.spend_tracking.spend_log_alias.lookup_window_bounds" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_spend_log_names_the_key_only_from_one_day_before_to_two_days_after_the_read[first_second_of_the_window]": [ + "quota_management.spend_tracking.spend_log_alias.lookup_window_bounds" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_spend_log_names_the_key_only_from_one_day_before_to_two_days_after_the_read[last_second_of_the_window]": [ + "quota_management.spend_tracking.spend_log_alias.lookup_window_bounds" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_spend_log_names_the_key_only_from_one_day_before_to_two_days_after_the_read[first_second_after_the_window]": [ + "quota_management.spend_tracking.spend_log_alias.lookup_window_bounds" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_two_aliases_on_the_two_edges_leave_the_key_unnamed": [ + "quota_management.spend_tracking.spend_log_alias.two_edge_aliases_unnamed" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_rows_without_a_usable_alias_do_not_hide_the_named_row_after_them[empty_string_alias]": [ + "quota_management.spend_tracking.spend_log_alias.unusable_rows_do_not_hide_named_row" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_rows_without_a_usable_alias_do_not_hide_the_named_row_after_them[array_then_string_metadata]": [ + "quota_management.spend_tracking.spend_log_alias.unusable_rows_do_not_hide_named_row" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_of_an_unexpected_shape_is_reported_as_postgres_renders_it[json_int]": [ + "quota_management.spend_tracking.spend_log_alias.unexpected_shape_as_postgres_renders" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_of_an_unexpected_shape_is_reported_as_postgres_renders_it[json_list]": [ + "quota_management.spend_tracking.spend_log_alias.unexpected_shape_as_postgres_renders" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_of_an_unexpected_shape_is_reported_as_postgres_renders_it[five_kb_string]": [ + "quota_management.spend_tracking.spend_log_alias.unexpected_shape_as_postgres_renders" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_found_once_is_served_from_the_cache_for_the_same_window_only": [ + "quota_management.spend_tracking.spend_log_alias.cache_per_window" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_logged_after_a_cached_miss_shows_once_the_miss_expires": [ + "quota_management.spend_tracking.spend_log_alias.cached_miss_expires" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_alias_lookup_gives_up_while_spend_logs_are_locked_and_answers_once_they_are_not": [ + "quota_management.spend_tracking.spend_log_alias.gives_up_while_locked" + ], + "tests/integration/spend/test_daily_activity_key_alias_probes.py::test_concurrent_reads_over_every_route_all_name_a_fresh_key": [ + "quota_management.spend_tracking.spend_log_alias.concurrent_reads_name_fresh_key" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[user_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[user_daily_activity_aggregated]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[team_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[team_daily_activity_aggregated]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[tag_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[organization_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[customer_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[end_user_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names[agent_daily_activity]": [ + "quota_management.spend_tracking.daily_spend_owner.missing_key_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_whose_daily_spend_names_two_users_is_reported_with_no_owner": [ + "quota_management.spend_tracking.daily_spend_owner.two_users_no_owner" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_daily_spend_rows_naming_no_user_do_not_hide_the_one_user_the_others_name[blank_user]": [ + "quota_management.spend_tracking.daily_spend_owner.unnamed_rows_do_not_hide_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_daily_spend_rows_naming_no_user_do_not_hide_the_one_user_the_others_name[null_user]": [ + "quota_management.spend_tracking.daily_spend_owner.unnamed_rows_do_not_hide_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_whose_daily_spend_names_no_user_at_all_is_reported_with_no_owner": [ + "quota_management.spend_tracking.daily_spend_owner.no_user_no_owner" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_owner_the_user_table_does_not_hold_is_reported_by_id_with_no_email": [ + "quota_management.spend_tracking.daily_spend_owner.unknown_user_id_no_email" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_live_key_keeps_its_own_user_when_its_daily_spend_names_another": [ + "quota_management.spend_tracking.daily_spend_owner.live_key_keeps_own_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_live_key_with_no_user_is_not_given_the_user_its_daily_spend_names": [ + "quota_management.spend_tracking.daily_spend_owner.live_key_without_user_not_given_one" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_deleted_key_keeps_its_own_user_when_its_daily_spend_names_another": [ + "quota_management.spend_tracking.daily_spend_owner.deleted_key_keeps_own_user" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_deleted_key_with_no_user_keeps_its_alias_and_gains_the_one_user_its_daily_spend_names": [ + "quota_management.spend_tracking.daily_spend_owner.deleted_key_without_user_gains_one" + ], + "tests/integration/spend/test_daily_activity_key_owner.py::test_key_named_only_by_a_spend_log_alias_keeps_that_alias_and_gains_the_one_user_its_daily_spend_names": [ + "quota_management.spend_tracking.daily_spend_owner.spend_log_alias_gains_one_user" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_user_reading_a_key_shared_with_another_user_is_shown_no_owner_and_nothing_of_the_other_user": [ + "quota_management.spend_tracking.daily_spend_owner.shared_key_hides_other_user" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_user_reading_a_key_only_they_spent_with_is_shown_themselves_as_its_owner": [ + "quota_management.spend_tracking.daily_spend_owner.own_key_shows_self" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_user_reading_a_key_only_another_user_spent_with_is_shown_nothing_of_it": [ + "quota_management.spend_tracking.daily_spend_owner.other_users_key_hidden" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_invalid_key_is_refused_without_naming_the_owner": [ + "quota_management.spend_tracking.daily_spend_owner.invalid_key_refused" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_five_kilobyte_key_is_reported_with_the_one_user_its_daily_spend_names": [ + "quota_management.spend_tracking.daily_spend_owner.five_kilobyte_key" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_key_with_no_daily_spend_is_reported_as_no_activity": [ + "quota_management.spend_tracking.daily_spend_owner.no_daily_spend_no_activity" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_every_key_of_a_team_is_reported_with_its_own_user": [ + "quota_management.spend_tracking.daily_spend_owner.every_team_key_own_user" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_reading_the_same_activity_twice_gives_the_same_answer": [ + "quota_management.spend_tracking.daily_spend_owner.repeat_read_same_answer" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_key_stops_being_reported_with_an_owner_once_a_second_user_spends_with_it": [ + "quota_management.spend_tracking.daily_spend_owner.second_user_drops_owner" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_owner_lookup_gives_up_while_daily_user_spend_is_locked_and_answers_once_it_is_not": [ + "quota_management.spend_tracking.daily_spend_owner.gives_up_while_locked" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_owner_is_reported_while_a_worker_is_killed_and_after_it_is_replaced": [ + "quota_management.spend_tracking.daily_spend_owner.survives_worker_replacement" + ], + "tests/integration/spend/test_daily_activity_key_owner_faults.py::test_owner_is_reported_again_after_the_proxy_restarts": [ + "quota_management.spend_tracking.daily_spend_owner.survives_proxy_restart" + ], + "tests/integration/spend/test_daily_activity_key_owner_traffic.py::test_key_used_on_every_unified_endpoint_is_reported_with_its_own_alias_and_user": [ + "quota_management.spend_tracking.key_attribution.every_unified_endpoint" + ], + "tests/integration/spend/test_daily_activity_key_owner_traffic.py::test_key_purged_from_the_key_tables_is_reported_with_the_alias_its_spend_logs_name": [ + "quota_management.spend_tracking.key_attribution.purged_key_named_by_spend_logs" + ], + "tests/integration/spend/test_daily_activity_key_owner_traffic.py::test_cli_session_spend_is_reported_with_the_user_and_team_of_the_session": [ + "quota_management.spend_tracking.key_attribution.cli_session_user_and_team" + ], + "tests/integration/spend/test_daily_activity_key_owner_traffic.py::test_usage_ai_chat_hands_the_model_the_usage_summary_without_any_key_owner": [ + "quota_management.spend_tracking.key_attribution.usage_ai_chat_without_key_owner" + ], + "tests/integration/spend/test_daily_activity_key_owner_traffic.py::test_owner_is_reported_on_every_route_while_a_burst_of_requests_waits_on_the_provider": [ + "quota_management.spend_tracking.key_attribution.every_route_under_provider_burst" ] }, "browser": { diff --git a/tests/integration/spend/test_daily_activity_key_alias_probes.py b/tests/integration/spend/test_daily_activity_key_alias_probes.py new file mode 100644 index 000000000000..19f641f185c5 --- /dev/null +++ b/tests/integration/spend/test_daily_activity_key_alias_probes.py @@ -0,0 +1,505 @@ +import time +import uuid +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from hashlib import sha256 +from pathlib import Path +from typing import Final + +import httpx +import pytest +from integration._support.client import Gateway, eventually, object_value +from integration._support.daily_activity import ( + AGGREGATED_USER_ACTIVITY, + DAY, + ROUTES, + SPEND_LOGS_TABLE, + USER_SPEND, + Route, + SpendLogRow, + activity_of_key, + assert_key_reported, + daily_rows, + digest_no_key_table_holds, + key_metadata, + locked_table, + named_row, + nameless_rows, + records_of_key, + seeded_metrics, + seeded_row, + spend_logs_of_key, + started_at, + user_row, + user_with_an_email, +) +from integration._support.database import read_rows, scratch_database +from integration._support.process import OwnedProxy, owned_proxy_process +from pydantic import JsonValue + +DAY_OUTSIDE_THE_WINDOW: Final = "2026-02-10" +GIVES_UP_WITHIN_SECONDS: Final = 10 +CONCURRENT_READS: Final = 20 +CACHED_MISS_CLEARS_WITHIN_SECONDS: Final = 45 +ALIAS_OF_ONE_SPEND_LOG: Final = ( + "SELECT metadata->>'user_api_key_alias' AS alias FROM \"LiteLLM_SpendLogs\" WHERE request_id = %s" +) + + +def _alias() -> str: + return f"integration-alias-{uuid.uuid4().hex}" + + +def _named_between_fifty_and_fifty(alias: str) -> tuple[SpendLogRow, ...]: + return (*nameless_rows(50), named_row(50, alias), *nameless_rows(50, 51)) + + +def _oldest_named(alias: str) -> tuple[SpendLogRow, ...]: + return (named_row(0, alias), *nameless_rows(150, 1)) + + +def _newest_named(alias: str) -> tuple[SpendLogRow, ...]: + return (*nameless_rows(150), named_row(150, alias)) + + +def _both_edges_named(alias: str) -> tuple[SpendLogRow, ...]: + return (named_row(0, alias), *nameless_rows(150, 1), named_row(151, alias)) + + +def _named_after_one_hundred(alias: str) -> tuple[SpendLogRow, ...]: + return (*nameless_rows(100), named_row(100, alias), *nameless_rows(99, 101)) + + +def _named_after_ninety_nine(alias: str) -> tuple[SpendLogRow, ...]: + return (*nameless_rows(99), named_row(99, alias), *nameless_rows(100, 100)) + + +def _named_only_in_the_middle(alias: str) -> tuple[SpendLogRow, ...]: + return (*nameless_rows(100), named_row(100, alias), *nameless_rows(100, 101)) + + +def _renamed_and_renamed_back(alias: str, other: str) -> tuple[SpendLogRow, ...]: + return ( + named_row(0, alias), + *nameless_rows(100, 1), + named_row(101, other), + *nameless_rows(100, 102), + named_row(202, alias), + ) + + +def _team_in_the_column(team: str) -> SpendLogRow: + return SpendLogRow(started_at(0), {}, team_id=team) + + +def _team_in_the_metadata(team: str) -> SpendLogRow: + return SpendLogRow(started_at(0), {"user_api_key_team_id": team}) + + +def _user_in_the_column(user: str) -> SpendLogRow: + return SpendLogRow(started_at(0), {}, user=user) + + +def _user_in_the_metadata(user: str) -> SpendLogRow: + return SpendLogRow(started_at(0), {"user_api_key_user_id": user}) + + +def _activity_on_route(gateway: Gateway, route: Route, api_key: str, entity: str) -> httpx.Response: + filters: Final = {} if route.entity_filter is None else {route.entity_filter: entity} + return activity_of_key(gateway, route.path, api_key, **filters) + + +def _reported_aliases(response: httpx.Response, api_key: str) -> tuple[JsonValue, ...]: + if response.status_code != 200: + return () + return tuple( + object_value(object_value(record)["metadata"])["key_alias"] + for record in records_of_key(object_value(response.json()), api_key) + ) + + +def _names_the_key(api_key: str, alias: str) -> Callable[[httpx.Response], bool]: + def names(response: httpx.Response) -> bool: + reported: Final = _reported_aliases(response, api_key) + return bool(reported) and frozenset(reported) == frozenset((alias,)) + + return names + + +@contextmanager +def _proxy_on(gateway: Gateway, directory: Path, database_url: str, *, workers: int = 1) -> Iterator[OwnedProxy]: + with owned_proxy_process( + gateway, + directory, + {"DATABASE_URL": database_url}, + remove_environment=("DATABASE_URL_READ_REPLICA",), + workers=workers, + ) as owned: + yield owned + + +def _owner_on(candidate: Gateway) -> tuple[str, str]: + owner: Final = f"integration-{uuid.uuid4().hex}" + email: Final = f"{owner}@example.com" + candidate.post("/user/new", {"user_id": owner, "user_email": email, "auto_create_key": False}) + return owner, email + + +@pytest.mark.parametrize("route", ROUTES, ids=lambda route: route.path.strip("/").replace("/", "_")) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.every_daily_activity_route") +def test_alias_named_only_by_a_spend_log_is_reported_on_every_daily_activity_route( + gateway: Gateway, route: Route +) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + entity: Final = f"integration-entity-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + entity_rows: Final = ( + () if route.table == USER_SPEND else (seeded_row(route.table, route.entity_column, entity, api_key, DAY),) + ) + filters: Final = {} if route.entity_filter is None else {route.entity_filter: entity} + with ( + daily_rows((user_row(owner, api_key, DAY), *entity_rows)), + spend_logs_of_key(api_key, (named_row(0, alias),)), + ): + assert_key_reported( + activity_of_key(gateway, route.path, api_key, **filters), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + "layout", + ( + pytest.param(_named_between_fifty_and_fifty, id="named_between_50_and_50_nameless"), + pytest.param(_oldest_named, id="oldest_named_150_nameless_newer"), + pytest.param(_newest_named, id="newest_named_150_nameless_older"), + pytest.param(_both_edges_named, id="both_edges_named_150_nameless_between"), + pytest.param(_named_after_one_hundred, id="100_nameless_named_99_nameless"), + pytest.param(_named_after_ninety_nine, id="99_nameless_named_100_nameless"), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.window_edge_reported") +def test_alias_on_an_edge_of_the_window_is_reported_whatever_surrounds_it( + gateway: Gateway, layout: Callable[[str], tuple[SpendLogRow, ...]] +) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, layout(alias)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.middle_of_nameless_rows_not_picked_up") +def test_alias_named_only_in_the_middle_of_two_hundred_nameless_rows_is_not_picked_up(gateway: Gateway) -> None: + api_key: Final = digest_no_key_table_holds() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with ( + daily_rows((user_row(owner, api_key, DAY),)), + spend_logs_of_key(api_key, _named_only_in_the_middle(_alias())), + ): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.rename_and_rename_back_both_edges") +def test_key_renamed_and_renamed_back_is_reported_with_the_alias_on_both_edges(gateway: Gateway) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + rows: Final = _renamed_and_renamed_back(alias, _alias()) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, rows): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + "spend_log_of_team", + ( + pytest.param(_team_in_the_column, id="team_id_column"), + pytest.param(_team_in_the_metadata, id="team_id_in_metadata"), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.team_next_to_daily_owner") +def test_team_named_only_by_a_spend_log_is_reported_next_to_the_daily_owner( + gateway: Gateway, spend_log_of_team: Callable[[str], SpendLogRow] +) -> None: + api_key: Final = digest_no_key_table_holds() + team: Final = f"integration-team-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, (spend_log_of_team(team),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(team=team, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + "spend_log_of_user", + ( + pytest.param(_user_in_the_column, id="user_column"), + pytest.param(_user_in_the_metadata, id="user_id_in_metadata"), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.user_beats_daily_owner") +def test_user_named_by_a_spend_log_beats_the_owner_the_daily_rows_name( + gateway: Gateway, spend_log_of_user: Callable[[str], SpendLogRow] +) -> None: + api_key: Final = digest_no_key_table_holds() + with gateway.scenario() as scenario: + daily_owner, _ = user_with_an_email(scenario) + log_user, log_email = user_with_an_email(scenario) + with ( + daily_rows((user_row(daily_owner, api_key, DAY),)), + spend_logs_of_key(api_key, (spend_log_of_user(log_user),)), + ): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=log_user, email=log_email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.hashed_jwt_digest") +def test_hashed_jwt_digest_is_named_by_its_spend_log(gateway: Gateway) -> None: + api_key: Final = f"hashed-jwt-{sha256(uuid.uuid4().bytes).hexdigest()}" + alias: Final = _alias() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, (named_row(0, alias),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + ("started", "inside_the_window"), + ( + pytest.param("2026-02-01 23:59:59", False, id="second_before_the_window"), + pytest.param("2026-02-02 00:00:00", True, id="first_second_of_the_window"), + pytest.param("2026-02-04 23:59:59", True, id="last_second_of_the_window"), + pytest.param("2026-02-05 00:00:00", False, id="first_second_after_the_window"), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.lookup_window_bounds") +def test_spend_log_names_the_key_only_from_one_day_before_to_two_days_after_the_read( + gateway: Gateway, started: str, inside_the_window: bool +) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + row: Final = SpendLogRow(started, {"user_api_key_alias": alias}) + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, (row,)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias if inside_the_window else None, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.two_edge_aliases_unnamed") +def test_two_aliases_on_the_two_edges_leave_the_key_unnamed(gateway: Gateway) -> None: + api_key: Final = digest_no_key_table_holds() + rows: Final = (named_row(0, _alias()), *nameless_rows(150, 1), named_row(151, _alias())) + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, rows): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + "unnamed_rows", + ( + pytest.param((SpendLogRow(started_at(0), {"user_api_key_alias": ""}),), id="empty_string_alias"), + pytest.param( + (SpendLogRow(started_at(0), ["x"]), SpendLogRow(started_at(1), "x")), id="array_then_string_metadata" + ), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.unusable_rows_do_not_hide_named_row") +def test_rows_without_a_usable_alias_do_not_hide_the_named_row_after_them( + gateway: Gateway, unnamed_rows: tuple[SpendLogRow, ...] +) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + rows: Final = (*unnamed_rows, named_row(len(unnamed_rows), alias)) + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, rows): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.parametrize( + "stored_alias", + ( + pytest.param(123, id="json_int"), + pytest.param(["a"], id="json_list"), + pytest.param("a" * 5000, id="five_kb_string"), + ), +) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.unexpected_shape_as_postgres_renders") +def test_alias_of_an_unexpected_shape_is_reported_as_postgres_renders_it( + gateway: Gateway, stored_alias: JsonValue +) -> None: + api_key: Final = digest_no_key_table_holds() + row: Final = SpendLogRow(started_at(0), {"user_api_key_alias": stored_alias}) + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)), spend_logs_of_key(api_key, (row,)) as request_ids: + rendered: Final = read_rows(ALIAS_OF_ONE_SPEND_LOG, (request_ids[0],))[0]["alias"] + assert isinstance(rendered, str) and rendered, rendered + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=rendered, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.cache_per_window") +def test_alias_found_once_is_served_from_the_cache_for_the_same_window_only(gateway: Gateway, tmp_path: Path) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + with scratch_database() as database_url, _proxy_on(gateway, tmp_path, database_url) as owned: + owner, email = _owner_on(owned.gateway) + rows: Final = (user_row(owner, api_key, DAY), user_row(owner, api_key, DAY_OUTSIDE_THE_WINDOW)) + with daily_rows(rows, database_url=database_url): + with spend_logs_of_key(api_key, (named_row(0, alias),), database_url=database_url): + first: Final = activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key) + cached: Final = activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key) + other_window: Final = owned.gateway.request( + "GET", + AGGREGATED_USER_ACTIVITY, + params={"start_date": DAY_OUTSIDE_THE_WINDOW, "end_date": DAY_OUTSIDE_THE_WINDOW, "api_key": api_key}, + ) + named: Final = key_metadata(alias=alias, user=owner, email=email) + assert_key_reported(first, api_key, DAY, named, seeded_metrics(1)) + assert_key_reported(cached, api_key, DAY, named, seeded_metrics(1)) + assert_key_reported( + other_window, api_key, DAY_OUTSIDE_THE_WINDOW, key_metadata(user=owner, email=email), seeded_metrics(1) + ) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.cached_miss_expires") +def test_alias_logged_after_a_cached_miss_shows_once_the_miss_expires(gateway: Gateway, tmp_path: Path) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + with scratch_database() as database_url, _proxy_on(gateway, tmp_path, database_url) as owned: + owner, email = _owner_on(owned.gateway) + with daily_rows((user_row(owner, api_key, DAY),), database_url=database_url): + missed: Final = activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key) + with spend_logs_of_key(api_key, (named_row(0, alias),), database_url=database_url): + named: Final = eventually( + lambda: activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key), + _names_the_key(api_key, alias), + seconds=CACHED_MISS_CLEARS_WITHIN_SECONDS, + ) + assert_key_reported(missed, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) + assert_key_reported(named, api_key, DAY, key_metadata(alias=alias, user=owner, email=email), seeded_metrics(1)) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.gives_up_while_locked") +def test_alias_lookup_gives_up_while_spend_logs_are_locked_and_answers_once_they_are_not( + gateway: Gateway, tmp_path: Path +) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + with scratch_database() as database_url, _proxy_on(gateway, tmp_path, database_url, workers=2) as owned: + owner, email = _owner_on(owned.gateway) + with ( + daily_rows((user_row(owner, api_key, DAY),), database_url=database_url), + spend_logs_of_key(api_key, (named_row(0, alias),), database_url=database_url), + ): + with locked_table(SPEND_LOGS_TABLE, database_url=database_url): + started: Final = time.monotonic() + locked: Final = activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key) + waited: Final = time.monotonic() - started + unlocked: Final = eventually( + lambda: activity_of_key(owned.gateway, AGGREGATED_USER_ACTIVITY, api_key), + _names_the_key(api_key, alias), + seconds=CACHED_MISS_CLEARS_WITHIN_SECONDS, + ) + assert waited < GIVES_UP_WITHIN_SECONDS, waited + assert_key_reported(locked, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) + assert_key_reported(unlocked, api_key, DAY, key_metadata(alias=alias, user=owner, email=email), seeded_metrics(1)) + + +@pytest.mark.covers("quota_management.spend_tracking.spend_log_alias.concurrent_reads_name_fresh_key") +def test_concurrent_reads_over_every_route_all_name_a_fresh_key(gateway: Gateway) -> None: + api_key: Final = digest_no_key_table_holds() + alias: Final = _alias() + entity: Final = f"integration-entity-{uuid.uuid4().hex}" + entity_columns: Final = {route.table: route.entity_column for route in ROUTES if route.table != USER_SPEND} + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + rows: Final = ( + user_row(owner, api_key, DAY), + *(seeded_row(table, column, entity, api_key, DAY) for table, column in entity_columns.items()), + ) + with ( + daily_rows(rows), + spend_logs_of_key(api_key, (named_row(0, alias),)), + ThreadPoolExecutor(CONCURRENT_READS) as pool, + ): + reads: Final = tuple( + pool.submit(_activity_on_route, gateway, ROUTES[index % len(ROUTES)], api_key, entity) + for index in range(CONCURRENT_READS) + ) + responses: Final = tuple(read.result() for read in reads) + for response in responses: + assert_key_reported( + response, api_key, DAY, key_metadata(alias=alias, user=owner, email=email), seeded_metrics(1) + ) diff --git a/tests/integration/spend/test_daily_activity_key_owner.py b/tests/integration/spend/test_daily_activity_key_owner.py new file mode 100644 index 000000000000..0e005ec7e467 --- /dev/null +++ b/tests/integration/spend/test_daily_activity_key_owner.py @@ -0,0 +1,206 @@ +import uuid +from hashlib import sha256 +from typing import Final + +import pytest +from integration._support.client import Gateway, Scenario, string_value +from integration._support.daily_activity import ( + AGGREGATED_USER_ACTIVITY, + DAY, + ROUTES, + USER_SPEND, + Route, + activity_of_key, + assert_key_reported, + daily_rows, + key_metadata, + key_no_key_table_holds, + seeded_metrics, + seeded_row, + spend_log_naming_only_an_alias, + user_row, + user_with_an_email, +) + + +@pytest.mark.parametrize("route", ROUTES, ids=lambda route: route.path.strip("/").replace("/", "_")) +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.missing_key_one_user") +def test_key_missing_from_the_key_tables_is_reported_with_the_one_user_its_daily_spend_names( + gateway: Gateway, route: Route +) -> None: + api_key: Final = key_no_key_table_holds() + entity: Final = f"integration-entity-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + entity_rows: Final = ( + () if route.table == USER_SPEND else (seeded_row(route.table, route.entity_column, entity, api_key, DAY),) + ) + filters: Final = {} if route.entity_filter is None else {route.entity_filter: entity} + with daily_rows((user_row(owner, api_key, DAY), *entity_rows)): + assert_key_reported( + activity_of_key(gateway, route.path, api_key, **filters), + api_key, + DAY, + key_metadata(user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.two_users_no_owner") +def test_key_whose_daily_spend_names_two_users_is_reported_with_no_owner(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + first, _ = user_with_an_email(scenario) + second, _ = user_with_an_email(scenario) + with daily_rows((user_row(first, api_key, DAY), user_row(second, api_key, DAY))): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(), + seeded_metrics(2), + ) + + +@pytest.mark.parametrize("unnamed", ["", None], ids=["blank_user", "null_user"]) +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.unnamed_rows_do_not_hide_one_user") +def test_daily_spend_rows_naming_no_user_do_not_hide_the_one_user_the_others_name( + gateway: Gateway, unnamed: str | None +) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY), user_row(unnamed, api_key, DAY))): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=owner, email=email), + seeded_metrics(2), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.no_user_no_owner") +def test_key_whose_daily_spend_names_no_user_at_all_is_reported_with_no_owner(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with daily_rows((user_row("", api_key, DAY), user_row(None, api_key, DAY))): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(), + seeded_metrics(2), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.unknown_user_id_no_email") +def test_owner_the_user_table_does_not_hold_is_reported_by_id_with_no_email(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + owner: Final = f"integration-departed-{uuid.uuid4().hex}" + with daily_rows((user_row(owner, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=owner), + seeded_metrics(1), + ) + + +def _stored_form(token: str) -> str: + return sha256(token.encode()).hexdigest() + + +def _deleted_key(gateway: Gateway, scenario: Scenario, alias: str, **fields: str) -> str: + token: Final = string_value(gateway.post("/key/generate", {"key_alias": alias, **fields})["key"]) + scenario.delete_key(token) + return _stored_form(token) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.live_key_keeps_own_user") +def test_live_key_keeps_its_own_user_when_its_daily_spend_names_another(gateway: Gateway) -> None: + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + other, _ = user_with_an_email(scenario) + api_key: Final = _stored_form(scenario.key(user_id=owner, key_alias=alias)) + with daily_rows((user_row(other, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email, exists=True), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.live_key_without_user_not_given_one") +def test_live_key_with_no_user_is_not_given_the_user_its_daily_spend_names(gateway: Gateway) -> None: + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + spender, _ = user_with_an_email(scenario) + api_key: Final = _stored_form(scenario.key(key_alias=alias)) + with daily_rows((user_row(spender, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, exists=True), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.deleted_key_keeps_own_user") +def test_deleted_key_keeps_its_own_user_when_its_daily_spend_names_another(gateway: Gateway) -> None: + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + other, _ = user_with_an_email(scenario) + api_key: Final = _deleted_key(gateway, scenario, alias, user_id=owner) + with daily_rows((user_row(other, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.deleted_key_without_user_gains_one") +def test_deleted_key_with_no_user_keeps_its_alias_and_gains_the_one_user_its_daily_spend_names( + gateway: Gateway, +) -> None: + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + api_key: Final = _deleted_key(gateway, scenario, alias) + with daily_rows((user_row(owner, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.spend_log_alias_gains_one_user") +def test_key_named_only_by_a_spend_log_alias_keeps_that_alias_and_gains_the_one_user_its_daily_spend_names( + gateway: Gateway, +) -> None: + api_key: Final = sha256(uuid.uuid4().bytes).hexdigest() + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with ( + spend_log_naming_only_an_alias(f"integration-{uuid.uuid4().hex}", api_key, f"{DAY} 12:00:00", alias), + daily_rows((user_row(owner, api_key, DAY),)), + ): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(alias=alias, user=owner, email=email), + seeded_metrics(1), + ) diff --git a/tests/integration/spend/test_daily_activity_key_owner_faults.py b/tests/integration/spend/test_daily_activity_key_owner_faults.py new file mode 100644 index 000000000000..aad83a8d45ce --- /dev/null +++ b/tests/integration/spend/test_daily_activity_key_owner_faults.py @@ -0,0 +1,276 @@ +import os +import signal +import time +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from itertools import chain +from pathlib import Path +from typing import Final + +import httpx +import psutil +import pytest +from integration._support.client import Gateway, eventually, object_value +from integration._support.daily_activity import ( + AGGREGATED_USER_ACTIVITY, + DAY, + TEAM_SPEND, + USER_SPEND, + activity_of_key, + assert_key_reported, + daily_rows, + insert_daily_rows, + key_metadata, + key_no_key_table_holds, + locked_table, + records_of_key, + seeded_metrics, + seeded_row, + user_row, + user_with_an_email, +) +from integration._support.database import scratch_database +from integration._support.process import OwnedProxy, group_members, owned_proxy_process + +USER_ACTIVITY: Final = "/user/daily/activity" +TEAM_ACTIVITY: Final = "/team/daily/activity" +AGGREGATED_TEAM_ACTIVITY: Final = "/team/daily/activity/aggregated" +KEYS_OF_ONE_TEAM: Final = 300 +GIVES_UP_WITHIN_SECONDS: Final = 10 +READS_AFTER_THE_WORKER_IS_REPLACED: Final = 6 + + +@contextmanager +def _proxy_on(gateway: Gateway, directory: Path, database_url: str, *, workers: int = 1) -> Iterator[OwnedProxy]: + with owned_proxy_process( + gateway, + directory, + {"DATABASE_URL": database_url}, + remove_environment=("DATABASE_URL_READ_REPLICA",), + workers=workers, + ) as owned: + yield owned + + +def _owner_on(candidate: Gateway) -> tuple[str, str]: + owner: Final = f"integration-{uuid.uuid4().hex}" + email: Final = f"{owner}@example.com" + candidate.post("/user/new", {"user_id": owner, "user_email": email, "auto_create_key": False}) + return owner, email + + +def _read_on_a_new_connection(candidate: Gateway, api_key: str) -> httpx.Response: + return candidate.request( + "GET", + AGGREGATED_USER_ACTIVITY, + params={"start_date": DAY, "end_date": DAY, "api_key": api_key}, + headers={"Connection": "close"}, + ) + + +def _running_children(owned: OwnedProxy) -> tuple[int, ...]: + return tuple( + member.pid + for member in group_members(owned.process.pid) + if member.pid != owned.process.pid and member.is_running() and member.status() != psutil.STATUS_ZOMBIE + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.shared_key_hides_other_user") +def test_user_reading_a_key_shared_with_another_user_is_shown_no_owner_and_nothing_of_the_other_user( + gateway: Gateway, +) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + reader, _ = user_with_an_email(scenario) + other, other_email = user_with_an_email(scenario) + reader_key: Final = scenario.key(user_id=reader) + with daily_rows((user_row(reader, api_key, DAY), user_row(other, api_key, DAY))): + response: Final = activity_of_key(gateway, USER_ACTIVITY, api_key, reader=reader_key) + assert_key_reported(response, api_key, DAY, key_metadata(), seeded_metrics(1)) + assert other not in response.text + assert other_email not in response.text + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.own_key_shows_self") +def test_user_reading_a_key_only_they_spent_with_is_shown_themselves_as_its_owner(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + reader, email = user_with_an_email(scenario) + reader_key: Final = scenario.key(user_id=reader) + with daily_rows((user_row(reader, api_key, DAY),)): + response: Final = activity_of_key(gateway, USER_ACTIVITY, api_key, reader=reader_key) + assert_key_reported(response, api_key, DAY, key_metadata(user=reader, email=email), seeded_metrics(1)) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.other_users_key_hidden") +def test_user_reading_a_key_only_another_user_spent_with_is_shown_nothing_of_it(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + reader, _ = user_with_an_email(scenario) + other, other_email = user_with_an_email(scenario) + reader_key: Final = scenario.key(user_id=reader) + with daily_rows((user_row(other, api_key, DAY),)): + response: Final = activity_of_key(gateway, USER_ACTIVITY, api_key, reader=reader_key) + assert response.status_code == 200, response.text + assert object_value(response.json())["results"] == [], response.text + assert other not in response.text + assert other_email not in response.text + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.invalid_key_refused") +def test_invalid_key_is_refused_without_naming_the_owner(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)): + response: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key, reader="sk-not-a-key") + assert response.status_code == 401, response.text + assert owner not in response.text + assert email not in response.text + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.five_kilobyte_key") +def test_five_kilobyte_key_is_reported_with_the_one_user_its_daily_spend_names(gateway: Gateway) -> None: + api_key: Final = f"integration-5kb-{uuid.uuid4().hex}-{'k' * 5000}" + with gateway.scenario() as scenario: + owner, email = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)): + assert_key_reported( + activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key), + api_key, + DAY, + key_metadata(user=owner, email=email), + seeded_metrics(1), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.no_daily_spend_no_activity") +def test_key_with_no_daily_spend_is_reported_as_no_activity(gateway: Gateway) -> None: + response: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, key_no_key_table_holds()) + assert response.status_code == 200, response.text + body: Final = object_value(response.json()) + assert body["results"] == [], response.text + totals: Final = object_value(body["metadata"]) + assert [totals["total_spend"], totals["total_api_requests"]] == [0.0, 0], response.text + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.every_team_key_own_user") +def test_every_key_of_a_team_is_reported_with_its_own_user(gateway: Gateway) -> None: + team: Final = f"integration-entity-{uuid.uuid4().hex}" + owners: Final = {key_no_key_table_holds(): f"integration-owner-{uuid.uuid4().hex}" for _ in range(KEYS_OF_ONE_TEAM)} + rows: Final = tuple( + chain.from_iterable( + (user_row(owner, api_key, DAY), seeded_row(TEAM_SPEND, "team_id", team, api_key, DAY)) + for api_key, owner in owners.items() + ) + ) + with daily_rows(rows): + response: Final = gateway.request( + "GET", AGGREGATED_TEAM_ACTIVITY, params={"start_date": DAY, "end_date": DAY, "team_ids": team} + ) + assert response.status_code == 200, response.text + body: Final = object_value(response.json()) + days: Final = body["results"] + assert isinstance(days, list) and len(days) == 1, response.text + reported: Final = object_value(object_value(object_value(days[0])["breakdown"])["api_keys"]) + assert {api_key: object_value(record)["metadata"] for api_key, record in reported.items()} == { + api_key: key_metadata(user=owner) for api_key, owner in owners.items() + }, response.text + totals: Final = object_value(body["metadata"]) + assert totals["total_api_requests"] == KEYS_OF_ONE_TEAM, response.text + assert totals["total_spend"] == pytest.approx(0.25 * KEYS_OF_ONE_TEAM), response.text + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.repeat_read_same_answer") +def test_reading_the_same_activity_twice_gives_the_same_answer(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + owner, _ = user_with_an_email(scenario) + with daily_rows((user_row(owner, api_key, DAY),)): + first: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key) + second: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key) + assert [first.status_code, second.status_code] == [200, 200], [first.text, second.text] + assert records_of_key(first.json(), api_key), first.text + assert first.json() == second.json(), [first.text, second.text] + + +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.second_user_drops_owner") +def test_key_stops_being_reported_with_an_owner_once_a_second_user_spends_with_it(gateway: Gateway) -> None: + api_key: Final = key_no_key_table_holds() + with gateway.scenario() as scenario: + first, email = user_with_an_email(scenario) + second, _ = user_with_an_email(scenario) + with daily_rows((user_row(first, api_key, DAY),)): + alone: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key) + with daily_rows((user_row(second, api_key, DAY),)): + shared: Final = activity_of_key(gateway, AGGREGATED_USER_ACTIVITY, api_key) + assert_key_reported(alone, api_key, DAY, key_metadata(user=first, email=email), seeded_metrics(1)) + assert_key_reported(shared, api_key, DAY, key_metadata(), seeded_metrics(2)) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.gives_up_while_locked") +def test_owner_lookup_gives_up_while_daily_user_spend_is_locked_and_answers_once_it_is_not( + gateway: Gateway, tmp_path: Path +) -> None: + api_key: Final = key_no_key_table_holds() + team: Final = f"integration-entity-{uuid.uuid4().hex}" + with scratch_database() as database_url, _proxy_on(gateway, tmp_path, database_url) as owned: + owner, email = _owner_on(owned.gateway) + rows: Final = (user_row(owner, api_key, DAY), seeded_row(TEAM_SPEND, "team_id", team, api_key, DAY)) + with daily_rows(rows, database_url=database_url): + with locked_table(USER_SPEND, database_url=database_url): + started: Final = time.monotonic() + locked: Final = activity_of_key(owned.gateway, TEAM_ACTIVITY, api_key, team_ids=team) + waited: Final = time.monotonic() - started + unlocked: Final = activity_of_key(owned.gateway, TEAM_ACTIVITY, api_key, team_ids=team) + assert waited < GIVES_UP_WITHIN_SECONDS, waited + assert_key_reported(locked, api_key, DAY, key_metadata(), seeded_metrics(1)) + assert_key_reported(unlocked, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.survives_worker_replacement") +def test_owner_is_reported_while_a_worker_is_killed_and_after_it_is_replaced(gateway: Gateway, tmp_path: Path) -> None: + api_key: Final = key_no_key_table_holds() + with scratch_database() as database_url, _proxy_on(gateway, tmp_path, database_url, workers=2) as owned: + owner, email = _owner_on(owned.gateway) + with daily_rows((user_row(owner, api_key, DAY),), database_url=database_url): + before: Final = _read_on_a_new_connection(owned.gateway, api_key) + members: Final = tuple( + member for member in group_members(owned.process.pid) if member.pid != owned.process.pid + ) + children: Final = tuple(member.pid for member in members) + workers: Final = tuple( + member.pid for member in members if any("spawn_main" in part for part in member.cmdline()) + ) + assert len(workers) >= 2, workers + os.kill(workers[0], signal.SIGKILL) + during: Final = _read_on_a_new_connection(owned.gateway, api_key) + eventually( + lambda: _running_children(owned), + lambda pids: len(pids) >= len(children) and any(pid not in children for pid in pids), + seconds=30, + ) + after: Final = tuple( + _read_on_a_new_connection(owned.gateway, api_key) for _ in range(READS_AFTER_THE_WORKER_IS_REPLACED) + ) + for response in (before, during, *after): + assert_key_reported(response, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.daily_spend_owner.survives_proxy_restart") +def test_owner_is_reported_again_after_the_proxy_restarts(gateway: Gateway, tmp_path: Path) -> None: + api_key: Final = key_no_key_table_holds() + with scratch_database() as database_url: + with _proxy_on(gateway, tmp_path, database_url) as first: + owner, email = _owner_on(first.gateway) + insert_daily_rows((user_row(owner, api_key, DAY),), database_url=database_url) + before: Final = activity_of_key(first.gateway, AGGREGATED_USER_ACTIVITY, api_key) + with _proxy_on(gateway, tmp_path, database_url) as second: + after: Final = activity_of_key(second.gateway, AGGREGATED_USER_ACTIVITY, api_key) + for response in (before, after): + assert_key_reported(response, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) diff --git a/tests/integration/spend/test_daily_activity_key_owner_traffic.py b/tests/integration/spend/test_daily_activity_key_owner_traffic.py new file mode 100644 index 000000000000..0fc2b24343c0 --- /dev/null +++ b/tests/integration/spend/test_daily_activity_key_owner_traffic.py @@ -0,0 +1,448 @@ +import json +import os +import threading +import uuid +from collections.abc import Iterable +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime, timedelta +from hashlib import sha256 +from pathlib import Path +from queue import SimpleQueue +from typing import Final + +import httpx +import pytest +from integration._support.client import Gateway, Scenario, eventually, string_value +from integration._support.daily_activity import ( + AGGREGATED_USER_ACTIVITY, + DAY, + ROUTES, + USER_SPEND, + Route, + activity_of_key, + assert_key_owner_and_totals, + assert_key_reported, + daily_rows, + key_metadata, + key_no_key_table_holds, + purge_key_from_the_key_tables, + seeded_metrics, + seeded_row, + user_row, + user_with_an_email, +) +from integration._support.database import read_rows, scratch_database +from integration._support.process import owned_proxy +from integration._support.wire import Reply, Request, wire_server +from pydantic import JsonValue + +from litellm.proxy._types import LiteLLM_UserTable +from litellm.proxy.auth.auth_checks import ExperimentalUIJWTToken + +REQUESTS_OF_KEY: Final = ( + 'SELECT COALESCE(SUM(api_requests), 0)::int AS requests FROM "LiteLLM_DailyUserSpend" ' + "WHERE api_key=%s AND user_id=%s" +) +NAMED_SPEND_LOGS_OF_KEY: Final = ( + 'SELECT COUNT(*)::int AS named FROM "LiteLLM_SpendLogs" ' + "WHERE api_key=%s AND NULLIF(metadata->>'user_api_key_alias', '') IS NOT NULL" +) +UNIFIED_ENDPOINTS: Final = ("/v1/chat/completions", "/v1/messages", "/v1/responses") +REQUESTS_OF_A_BURST: Final = 21 +READS_DURING_A_BURST: Final = 30 +TOKEN_LIMIT_DISCOVERY: Final = ("GET", "/v1/models") +TOOL_CALL: Final = "call_integration_usage" +ANSWER: Final = "One request cost $0.25" +SUMMARY_OF_ONE_SEEDED_ROW: Final = "\n".join( + ( + "Total Spend: $0.2500", + "Total Requests: 1", + "Successful: 1 | Failed: 0", + "Total Tokens: 15", + "", + "Top Models by Spend:", + " - gpt-4o-mini: $0.2500 (1 reqs, 15 tokens)", + "", + "Top Providers by Spend:", + " - openai: $0.2500 (1 reqs)", + ) +) + + +def _chat_completion() -> dict[str, JsonValue]: + return { + "id": f"chatcmpl-{uuid.uuid4().hex}", + "object": "chat.completion", + "created": 1, + "model": "gpt-4o-mini", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + } + + +def _response() -> dict[str, JsonValue]: + return { + "id": f"resp_{uuid.uuid4().hex}", + "object": "response", + "created_at": 1, + "status": "completed", + "model": "gpt-4o-mini", + "output": [ + { + "type": "message", + "id": f"msg_{uuid.uuid4().hex}", + "status": "completed", + "role": "assistant", + "content": [{"type": "output_text", "text": "ok", "annotations": []}], + } + ], + "usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}, + } + + +def _provider(request: Request) -> Reply: + body: Final = _response() if request.target.endswith("/responses") else _chat_completion() + return Reply(body=json.dumps(body).encode()) + + +def _usage_tool_call() -> dict[str, JsonValue]: + call: Final[dict[str, JsonValue]] = { + "id": TOOL_CALL, + "type": "function", + "function": { + "name": "get_usage_data", + "arguments": json.dumps({"start_date": DAY, "end_date": DAY}), + }, + } + return { + "id": f"chatcmpl-{uuid.uuid4().hex}", + "object": "chat.completion", + "created": 1, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": None, "tool_calls": [call]}, + "finish_reason": "tool_calls", + } + ], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + } + + +def _streamed_chunk(delta: dict[str, JsonValue], finish_reason: str | None) -> bytes: + chunk: Final = { + "id": "chatcmpl-integration-usage", + "object": "chat.completion.chunk", + "created": 1, + "model": "gpt-4o-mini", + "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}], + } + return f"data: {json.dumps(chunk)}\n\n".encode() + + +def _usage_analyst(request: Request) -> Reply: + if json.loads(request.body).get("stream"): + return Reply( + chunks=( + _streamed_chunk({"role": "assistant", "content": ANSWER}, None), + _streamed_chunk({}, "stop"), + b"data: [DONE]\n\n", + ), + content_type="text/event-stream", + ) + return Reply(body=json.dumps(_usage_tool_call()).encode()) + + +def _sent_for_callers(requests: Iterable[Request]) -> tuple[Request, ...]: + return tuple(request for request in requests if (request.method, request.target) != TOKEN_LIMIT_DISCOVERY) + + +def _priced_model(scenario: Scenario, provider_url: str) -> str: + return scenario.model( + api_base=f"{provider_url}/v1", input_cost_per_token=0.001, output_cost_per_token=0.002, num_retries=0 + ) + + +def _request_body(endpoint: str, model: str, prompt: str) -> dict[str, JsonValue]: + if endpoint == "/v1/chat/completions": + return {"model": model, "messages": [{"role": "user", "content": prompt}]} + if endpoint == "/v1/messages": + return {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": prompt}]} + return {"model": model, "input": prompt} + + +def _activity_on_route(gateway: Gateway, route: Route, api_key: str, entity: str) -> httpx.Response: + filters: Final = {} if route.entity_filter is None else {route.entity_filter: entity} + return activity_of_key(gateway, route.path, api_key, **filters) + + +def _prompt() -> str: + return f"daily activity owner {uuid.uuid4().hex}" + + +def _totals_of_requests(requests: int) -> dict[str, float]: + return { + "total_spend": 0.02 * requests, + "total_prompt_tokens": 10 * requests, + "total_completion_tokens": 5 * requests, + "total_tokens": 15 * requests, + "total_api_requests": requests, + "total_successful_requests": requests, + "total_failed_requests": 0, + } + + +def _activity_around_today(gateway: Gateway, api_key: str) -> httpx.Response: + today: Final = datetime.now(UTC).date() + return gateway.request( + "GET", + AGGREGATED_USER_ACTIVITY, + params={ + "start_date": str(today - timedelta(days=1)), + "end_date": str(today + timedelta(days=1)), + "timezone": "0", + "api_key": api_key, + }, + ) + + +def _wait_for_requests(api_key: str, user: str, requests: int) -> None: + eventually( + lambda: read_rows(REQUESTS_OF_KEY, (api_key, user)), + lambda rows: rows[0]["requests"] == requests, + seconds=70, + ) + + +def _wait_for_named_spend_logs(api_key: str, requests: int) -> None: + eventually( + lambda: read_rows(NAMED_SPEND_LOGS_OF_KEY, (api_key,)), + lambda rows: rows[0]["named"] == requests, + seconds=70, + ) + + +def _cli_session_token(user: str, team: str) -> str: + cli_user: Final = LiteLLM_UserTable(user_id=user, user_role="internal_user", teams=[team], models=[]) + return ExperimentalUIJWTToken.get_cli_jwt_auth_token(user_info=cli_user, team_id=team, team_alias="cli-team") + + +@pytest.mark.covers("quota_management.spend_tracking.key_attribution.every_unified_endpoint") +def test_key_used_on_every_unified_endpoint_is_reported_with_its_own_alias_and_user(gateway: Gateway) -> None: + chat_prompt, messages_prompt, responses_prompt = _prompt(), _prompt(), _prompt() + with wire_server(_provider) as wire, gateway.scenario() as scenario: + model: Final = _priced_model(scenario, wire.url) + owner, email = user_with_an_email(scenario) + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + key: Final = scenario.key(user_id=owner, key_alias=alias, models=[model]) + stored: Final = sha256(key.encode()).hexdigest() + prompts: Final = (chat_prompt, messages_prompt, responses_prompt) + answers: Final = tuple( + gateway.request("POST", endpoint, _request_body(endpoint, model, prompt), key=key) + for endpoint, prompt in zip(UNIFIED_ENDPOINTS, prompts, strict=True) + ) + assert [answer.status_code for answer in answers] == [200, 200, 200], [answer.text for answer in answers] + received: Final = _sent_for_callers(wire.drain()) + assert [request.target for request in received] == ["/v1/chat/completions", "/v1/responses", "/v1/responses"] + assert [json.loads(request.body)["model"] for request in received] == ["gpt-4o-mini"] * 3 + assert json.loads(received[0].body)["messages"] == [{"role": "user", "content": chat_prompt}] + assert messages_prompt in received[1].body.decode() + assert json.loads(received[2].body)["input"] == responses_prompt + _wait_for_requests(stored, owner, 3) + assert_key_owner_and_totals( + _activity_around_today(gateway, stored), + stored, + key_metadata(alias=alias, user=owner, email=email, exists=True), + _totals_of_requests(3), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.key_attribution.purged_key_named_by_spend_logs") +def test_key_purged_from_the_key_tables_is_reported_with_the_alias_its_spend_logs_name(gateway: Gateway) -> None: + prompts: Final = (_prompt(), _prompt(), _prompt()) + with wire_server(_provider) as wire, gateway.scenario() as scenario: + model: Final = _priced_model(scenario, wire.url) + owner, email = user_with_an_email(scenario) + alias: Final = f"integration-alias-{uuid.uuid4().hex}" + generated: Final = gateway.post("/key/generate", {"user_id": owner, "key_alias": alias, "models": [model]}) + key: Final = string_value(generated["key"]) + stored: Final = sha256(key.encode()).hexdigest() + try: + answers: Final = tuple( + gateway.request("POST", endpoint, _request_body(endpoint, model, prompt), key=key) + for endpoint, prompt in zip(UNIFIED_ENDPOINTS, prompts, strict=True) + ) + assert [answer.status_code for answer in answers] == [200, 200, 200], [answer.text for answer in answers] + received: Final = _sent_for_callers(wire.drain()) + assert [request.target for request in received] == [ + "/v1/chat/completions", + "/v1/responses", + "/v1/responses", + ] + _wait_for_requests(stored, owner, 3) + _wait_for_named_spend_logs(stored, 3) + finally: + purge_key_from_the_key_tables(stored) + assert_key_owner_and_totals( + _activity_around_today(gateway, stored), + stored, + key_metadata(alias=alias, user=owner, email=email, exists=False), + _totals_of_requests(3), + ) + + +@pytest.mark.covers("quota_management.spend_tracking.key_attribution.cli_session_user_and_team") +def test_cli_session_spend_is_reported_with_the_user_and_team_of_the_session( + gateway: Gateway, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("LITELLM_SALT_KEY", os.environ.get("LITELLM_SALT_KEY", "sk-integration-salt")) + prompt: Final = _prompt() + with wire_server(_provider) as wire, gateway.scenario() as scenario: + model: Final = _priced_model(scenario, wire.url) + owner, email = user_with_an_email(scenario) + team: Final = scenario.team(models=[model], members_with_roles=[{"role": "user", "user_id": owner}]) + answer: Final = gateway.request( + "POST", + "/v1/chat/completions", + {"model": model, "messages": [{"role": "user", "content": prompt}]}, + key=_cli_session_token(owner, team), + ) + assert answer.status_code == 200, answer.text + received: Final = _sent_for_callers(wire.drain()) + assert [request.target for request in received] == ["/v1/chat/completions"] + assert json.loads(received[0].body) == { + "model": "gpt-4o-mini", + "messages": [{"role": "user", "content": prompt}], + } + stored: Final = f"cli-session-{owner}" + _wait_for_requests(stored, owner, 1) + assert_key_owner_and_totals( + _activity_around_today(gateway, stored), + stored, + key_metadata(alias=stored, team=team, user=owner, email=email), + _totals_of_requests(1), + ) + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.key_attribution.usage_ai_chat_without_key_owner") +def test_usage_ai_chat_hands_the_model_the_usage_summary_without_any_key_owner( + gateway: Gateway, tmp_path: Path +) -> None: + question: Final = f"what did we spend {uuid.uuid4().hex}" + owner: Final = f"integration-{uuid.uuid4().hex}" + ownerless_key: Final = f"integration-ownerless-{uuid.uuid4().hex}" + with ( + scratch_database() as scratch_url, + wire_server(_usage_analyst) as wire, + owned_proxy( + gateway, + tmp_path, + { + "DATABASE_URL": scratch_url, + "OPENAI_API_BASE": f"{wire.url}/v1", + "OPENAI_BASE_URL": f"{wire.url}/v1", + "OPENAI_API_KEY": "integration-provider-key", + }, + remove_environment=("DATABASE_URL_READ_REPLICA",), + ) as candidate, + ): + candidate.post("/user/new", {"user_id": owner, "user_email": f"{owner}@example.com", "auto_create_key": False}) + with daily_rows((user_row(owner, ownerless_key, DAY),), database_url=scratch_url): + answer: Final = candidate.request( + "POST", + "/usage/ai/chat", + {"messages": [{"role": "user", "content": question}], "model": "openai/gpt-4o-mini"}, + ) + assert answer.status_code == 200, answer.text + tool_call: Final = { + "type": "tool_call", + "tool_name": "get_usage_data", + "tool_label": "global usage data", + "arguments": {"start_date": DAY, "end_date": DAY}, + } + events: Final = [ + json.loads(line.removeprefix("data: ")) for line in answer.text.splitlines() if line.startswith("data: ") + ] + assert events == [ + {"type": "status", "message": "Thinking..."}, + {**tool_call, "status": "running"}, + {**tool_call, "status": "complete"}, + {"type": "status", "message": "Analyzing results..."}, + {"type": "chunk", "content": ANSWER}, + {"type": "done"}, + ], answer.text + asked, analysed = wire.drain() + assert [asked.target, analysed.target] == ["/v1/chat/completions", "/v1/chat/completions"] + assert json.loads(asked.body)["messages"][-1] == {"role": "user", "content": question} + assert json.loads(analysed.body)["messages"][-1] == { + "role": "tool", + "tool_call_id": TOOL_CALL, + "content": SUMMARY_OF_ONE_SEEDED_ROW, + } + assert owner not in analysed.body.decode() + assert ownerless_key not in analysed.body.decode() + + +@pytest.mark.timeout(300) +@pytest.mark.covers("quota_management.spend_tracking.key_attribution.every_route_under_provider_burst") +def test_owner_is_reported_on_every_route_while_a_burst_of_requests_waits_on_the_provider(gateway: Gateway) -> None: + released: Final = threading.Event() + held: Final[SimpleQueue[str]] = SimpleQueue() + + def held_provider(request: Request) -> Reply: + if (request.method, request.target) == TOKEN_LIMIT_DISCOVERY: + return _provider(request) + held.put(request.target) + assert released.wait(timeout=120), "The burst was never released" + return _provider(request) + + api_key: Final = key_no_key_table_holds() + entity: Final = f"integration-entity-{uuid.uuid4().hex}" + prompts: Final = tuple(_prompt() for _ in range(REQUESTS_OF_A_BURST)) + entity_columns: Final = {route.table: route.entity_column for route in ROUTES if route.table != USER_SPEND} + with ( + wire_server(held_provider) as wire, + gateway.scenario() as scenario, + httpx.Client(base_url=gateway.client.base_url, timeout=180, trust_env=False) as patient, + ThreadPoolExecutor(max_workers=REQUESTS_OF_A_BURST) as traffic, + ThreadPoolExecutor(max_workers=READS_DURING_A_BURST) as readers, + ): + model: Final = _priced_model(scenario, wire.url) + owner, email = user_with_an_email(scenario) + key: Final = scenario.key(models=[model]) + rows: Final = ( + user_row(owner, api_key, DAY), + *(seeded_row(table, column, entity, api_key, DAY) for table, column in entity_columns.items()), + ) + try: + with daily_rows(rows): + burst: Final = tuple( + traffic.submit( + patient.post, + UNIFIED_ENDPOINTS[index % len(UNIFIED_ENDPOINTS)], + json=_request_body(UNIFIED_ENDPOINTS[index % len(UNIFIED_ENDPOINTS)], model, prompt), + headers={"Authorization": f"Bearer {key}"}, + ) + for index, prompt in enumerate(prompts) + ) + eventually(held.qsize, lambda waiting: waiting >= REQUESTS_OF_A_BURST, seconds=60) + reads: Final = tuple( + readers.submit(_activity_on_route, gateway, ROUTES[index % len(ROUTES)], api_key, entity) + for index in range(READS_DURING_A_BURST) + ) + activity: Final = tuple(read.result() for read in reads) + still_waiting: Final = [call.done() for call in burst] + finally: + released.set() + answers: Final = tuple(call.result() for call in burst) + received: Final = tuple(request.body.decode() for request in _sent_for_callers(wire.drain())) + assert still_waiting == [False] * REQUESTS_OF_A_BURST + assert [answer.status_code for answer in answers] == [200] * REQUESTS_OF_A_BURST, [ + answer.text for answer in answers + ] + assert [sum(prompt in body for body in received) for prompt in prompts] == [1] * REQUESTS_OF_A_BURST + assert len(received) == REQUESTS_OF_A_BURST, len(received) + for response in activity: + assert_key_reported(response, api_key, DAY, key_metadata(user=owner, email=email), seeded_metrics(1)) diff --git a/tests/proxy_unit_tests/test_check_batch_cost.py b/tests/proxy_unit_tests/test_check_batch_cost.py index 6417c7c8aa67..4e7effad3bf5 100644 --- a/tests/proxy_unit_tests/test_check_batch_cost.py +++ b/tests/proxy_unit_tests/test_check_batch_cost.py @@ -2620,6 +2620,27 @@ async def test_key_alias_lookup_failure_does_not_break_attribution(self): assert metadata["user_api_key"] == "hash-alice" assert metadata.get("user_api_key_alias") is None + @pytest.mark.asyncio + async def test_cli_session_batch_keeps_its_alias_without_a_key_row(self): + instance = self._instance(key_row=None) + + metadata = await instance._build_creator_attribution_metadata( + self._job(api_key="cli-session-alice"), "batch-1" + ) + + assert metadata["user_api_key"] == "cli-session-alice" + assert metadata["user_api_key_alias"] == "cli-session-alice" + + @pytest.mark.asyncio + async def test_raw_cli_session_token_on_a_legacy_batch_row_is_not_treated_as_the_alias(self): + instance = self._instance(key_row=None) + + metadata = await instance._build_creator_attribution_metadata( + self._job(api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa"), "batch-1" + ) + + assert metadata.get("user_api_key_alias") is None + @pytest.mark.asyncio async def test_unnamed_key_keeps_the_creating_user_alias(self): """Regression: a key generated without key_alias resolves to no alias, and the diff --git a/tests/test_litellm/integrations/test_prometheus_labels.py b/tests/test_litellm/integrations/test_prometheus_labels.py index 200f8e65addf..deca7a629119 100644 --- a/tests/test_litellm/integrations/test_prometheus_labels.py +++ b/tests/test_litellm/integrations/test_prometheus_labels.py @@ -716,6 +716,29 @@ async def test_failure_hook_emits_api_provider_value_on_failed_requests_metric() _clear_prometheus_registry() +@pytest.mark.asyncio +async def test_failure_hook_labels_a_cli_session_with_the_per_user_alias_not_the_login_token(): + from litellm.integrations.prometheus import PrometheusLogger + from litellm.proxy._types import UserAPIKeyAuth + + _clear_prometheus_registry() + try: + await PrometheusLogger().async_post_call_failure_hook( + request_data={"model": "gpt-4o-mini", "metadata": {}}, + original_exception=Exception("boom"), + user_api_key_dict=UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + user_id="alice", + key_alias="cli-session-alice", + is_session_token=True, + ), + ) + hashed_keys = {s.labels.get("hashed_api_key") for s in _collected_samples("litellm_proxy_failed_requests_metric_total")} + assert hashed_keys == {"cli-session-alice"}, hashed_keys + finally: + _clear_prometheus_registry() + + async def _failed_requests_api_provider_labels( request_data: dict[str, object], original_exception: Exception, diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_interception_handler.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_interception_handler.py index f39f41a6d124..64bb9f3a154b 100644 --- a/tests/test_litellm/integrations/websearch_interception/test_websearch_interception_handler.py +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_interception_handler.py @@ -230,6 +230,39 @@ async def test_execute_search_passes_selected_search_tool_litellm_params(monkeyp assert forwarded_kwargs["max_retries"] == 2 +@pytest.mark.asyncio +async def test_execute_search_attributes_cli_session_spend_to_the_per_user_alias_not_the_login_token(monkeypatch): + import litellm + from litellm.proxy import proxy_server + + logger = WebSearchInterceptionLogger(enabled_providers=["bedrock"], search_tool_name="perplexity-sonar-pro") + router = MagicMock() + router.search_tools = [ + { + "search_tool_name": "perplexity-sonar-pro", + "litellm_params": {"search_provider": "perplexity", "api_key": "fake-key"}, + } + ] + mock_asearch = AsyncMock(return_value=SearchResponse(object="search", results=[])) + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + user_id="alice", + key_alias="cli-session-alice", + is_session_token=True, + ) + monkeypatch.setattr(proxy_server, "llm_router", router) + monkeypatch.setattr(litellm, "asearch", mock_asearch) + + await logger._execute_search( + "what is litellm", + kwargs={"litellm_params": {"metadata": {"user_api_key_auth": session}}}, + ) + + forwarded_metadata = mock_asearch.await_args.kwargs["litellm_metadata"] + assert forwarded_metadata["user_api_key"] == "cli-session-alice" + assert forwarded_metadata["user_api_key_hash"] == "cli-session-alice" + + @pytest.mark.asyncio async def test_execute_search_attributes_spend_to_the_calling_key(monkeypatch): """An intercepted search is billed and logged against the key that made the LLM request. diff --git a/tests/test_litellm/llms/litellm_proxy/skills/test_skill_search.py b/tests/test_litellm/llms/litellm_proxy/skills/test_skill_search.py index 3f1fe0d5d68d..e28e927cf617 100644 --- a/tests/test_litellm/llms/litellm_proxy/skills/test_skill_search.py +++ b/tests/test_litellm/llms/litellm_proxy/skills/test_skill_search.py @@ -304,6 +304,29 @@ async def test_embedding_spend_is_attributed_to_the_calling_key(self) -> None: assert metadata["user_api_key_team_id"] == "team-1" assert metadata["user_api_key_user_id"] == "user-1" + @pytest.mark.asyncio + async def test_cli_session_embedding_spend_is_attributed_to_the_per_user_alias_not_the_login_token(self) -> None: + router = _embedding_router() + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + user_id="alice", + key_alias="cli-session-alice", + is_session_token=True, + ) + await search_skills( + "language translation", + SKILLS, + 1, + router=router, + embedding_model="text-embedding-3-small", + index=SkillSearchIndex(), + user_api_key_dict=session, + proxy_logging_obj=_pass_through_key_limits(), + ) + metadata = router.aembedding.await_args.kwargs["metadata"] + assert metadata["user_api_key"] == "cli-session-alice" + assert metadata["user_api_key_hash"] == "cli-session-alice" + @pytest.mark.asyncio async def test_key_limits_are_checked_against_the_real_embedding_call_before_it_runs(self) -> None: router = _embedding_router() diff --git a/tests/test_litellm/proxy/batches_endpoints/test_litellm_executed_batches.py b/tests/test_litellm/proxy/batches_endpoints/test_litellm_executed_batches.py index 6f2341a578ca..cae92ce18bb5 100644 --- a/tests/test_litellm/proxy/batches_endpoints/test_litellm_executed_batches.py +++ b/tests/test_litellm/proxy/batches_endpoints/test_litellm_executed_batches.py @@ -378,6 +378,7 @@ def make_runner( general_settings: Mapping[str, object] = MappingProxyType({}), heartbeat_seconds: float = 30.0, completion_window_seconds: float = 24 * 60 * 60, + user: UserAPIKeyAuth | None = None, ) -> Harness: store = store_factory({INPUT_FILE_ID: managed_input_file()} if files is None else files) router = FakeRouter() @@ -385,7 +386,7 @@ def make_runner( storage = FakeStorageBackend({STORAGE_URL: content}) storage_factory = FakeStorageBackendFactory(storage, storage_error) prisma = FakePrismaClient(store.objects) - user = UserAPIKeyAuth( + user = user or UserAPIKeyAuth( api_key="sk-batch-key", user_id="user-1", team_id="team-1", key_alias="alias-1", user_email="user@example.com" ) runner = LiteLLMExecutedBatchRunner( @@ -668,6 +669,20 @@ async def test_create_dispatches_each_row_with_the_batch_model_and_the_key_metad assert metadata["user_api_key_user_email"] == "user@example.com" +async def test_create_dispatches_cli_session_rows_under_the_per_user_alias_not_the_login_token() -> None: + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + user_id="alice", + key_alias="cli-session-alice", + is_session_token=True, + ) + harness = make_runner(user=session) + await harness.create_and_finish() + + logged_keys = {call.kwargs["metadata"]["user_api_key"] for call in harness.router.acompletion.await_args_list} + assert logged_keys == {"cli-session-alice"} + + async def test_create_uploads_one_output_line_per_row_with_the_router_response() -> None: harness = make_runner() replies = {"hi 1": chat_response("hi 1"), "hi 2": chat_response("hi 2")} diff --git a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter.py b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter.py index 0e2683dcbfd6..a83ddc69863c 100644 --- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter.py +++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter.py @@ -7,6 +7,7 @@ import pytest from litellm.caching.caching import DualCache +from litellm.proxy._types import UserAPIKeyAuth from litellm.proxy.hooks.parallel_request_limiter import ( _PROXY_MaxParallelRequestsHandler, ) @@ -14,6 +15,28 @@ from litellm.types.utils import EmbeddingResponse, TextCompletionResponse, Usage +@pytest.mark.asyncio +async def test_pre_call_hook_counts_a_cli_session_under_the_per_user_alias_not_the_login_token(): + handler = _PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(DualCache())) + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + user_id="alice", + key_alias="cli-session-alice", + is_session_token=True, + max_parallel_requests=5, + ) + + await handler.async_pre_call_hook( + user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion" + ) + + precise_minute = datetime.now().strftime("%Y-%m-%d-%H-%M") + counted = await handler.internal_usage_cache.async_get_cache( + key=f"cli-session-alice::{precise_minute}::request_count", litellm_parent_otel_span=None + ) + assert counted == {"current_requests": 1, "current_tpm": 0, "current_rpm": 1}, counted + + @pytest.mark.parametrize( "response_obj", [ diff --git a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py index 1884011411df..60f458eb1d17 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py +++ b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py @@ -1,3 +1,4 @@ +from collections.abc import Sequence from datetime import datetime, timedelta, timezone from types import SimpleNamespace from typing import Final @@ -19,6 +20,7 @@ get_daily_activity_aggregated, update_metrics, ) +from litellm.proxy.utils import hash_token from litellm.types.proxy.management_endpoints.common_daily_activity import ( DailySpendMetadata, SpendMetrics, @@ -503,6 +505,7 @@ async def test_get_api_key_metadata_permanent_miss_never_pages_tokens_or_reads_s mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[]) mock_prisma.db.litellm_usertable.find_many = AsyncMock(return_value=[]) mock_prisma.db.query_raw = AsyncMock(return_value=[]) + recovery_query_raw = _recovery_transaction(mock_prisma) result = await get_api_key_metadata( prisma_client=mock_prisma, @@ -510,9 +513,10 @@ async def test_get_api_key_metadata_permanent_miss_never_pages_tokens_or_reads_s ) assert double_hashed not in result - issued_sql = [call.args[0] for call in mock_prisma.db.query_raw.call_args_list] - assert len(issued_sql) == 2 - assert not any("LiteLLM_SpendLogs" in sql for sql in issued_sql) + assert mock_prisma.db.query_raw.await_count == 2 + ((owner_sql, owner_keys),) = [call.args for call in recovery_query_raw.call_args_list] + assert _DAILY_USER_SPEND in owner_sql + assert owner_keys == [double_hashed] token_lookups = ( mock_prisma.db.litellm_verificationtoken.find_many.call_args_list + mock_prisma.db.litellm_deletedverificationtoken.find_many.call_args_list @@ -520,14 +524,29 @@ async def test_get_api_key_metadata_permanent_miss_never_pages_tokens_or_reads_s assert all("take" not in call.kwargs and "skip" not in call.kwargs for call in token_lookups) -def _spend_log_transaction(mock_prisma: MagicMock, rows: list[dict[str, str | None]]) -> AsyncMock: +_DAILY_USER_SPEND: Final = '"LiteLLM_DailyUserSpend"' +_SPEND_LOGS: Final = '"LiteLLM_SpendLogs"' + + +def _recovery_transaction( + mock_prisma: MagicMock, + spend_log_rows: Sequence[dict[str, str | None]] = (), + daily_spend_owner_rows: Sequence[dict[str, str | None]] = (), +) -> AsyncMock: + async def query_raw(sql: str, *_: object) -> Sequence[dict[str, str | None]]: + return daily_spend_owner_rows if _DAILY_USER_SPEND in sql else spend_log_rows + transaction = MagicMock() transaction.execute_raw = AsyncMock(return_value=0) - transaction.query_raw = AsyncMock(return_value=rows) + transaction.query_raw = AsyncMock(side_effect=query_raw) mock_prisma.db.tx.return_value.__aenter__.return_value = transaction return transaction.query_raw +def _calls_reading(query_raw: AsyncMock, table: str) -> tuple[tuple[object, ...], ...]: + return tuple(call.args for call in query_raw.call_args_list if table in call.args[0]) + + def _spend_log_row(digest: str, key_alias: str, user_id: str) -> dict[str, str | None]: return { "digest": digest, @@ -551,15 +570,17 @@ async def test_get_api_key_metadata_permanent_miss_with_a_window_reads_spend_log mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[]) mock_prisma.db.litellm_usertable.find_many = AsyncMock(return_value=[]) mock_prisma.db.query_raw = AsyncMock(return_value=[]) - spend_log_query_raw = _spend_log_transaction(mock_prisma, []) + recovery_query_raw = _recovery_transaction(mock_prisma) result = await get_api_key_metadata(prisma_client=mock_prisma, api_keys={double_hashed}, spend_logs_window=window) assert double_hashed not in result assert mock_prisma.db.query_raw.await_count == 2 - ((_, digests, start, end),) = [call.args for call in spend_log_query_raw.call_args_list] + ((_, digests, start, end),) = _calls_reading(recovery_query_raw, _SPEND_LOGS) assert digests == [double_hashed] assert (start, end) == window + ((_, owner_keys),) = _calls_reading(recovery_query_raw, _DAILY_USER_SPEND) + assert owner_keys == [double_hashed] @pytest.mark.asyncio @@ -581,7 +602,7 @@ async def test_get_daily_activity_recovers_a_session_key_alias_from_spend_logs_a ) mock_prisma.db.query_raw = AsyncMock(return_value=[]) - spend_log_query_raw = _spend_log_transaction( + spend_log_query_raw = _recovery_transaction( mock_prisma, [_spend_log_row(session_digest, "cli-session-alias", "session-user")] ) @@ -2370,7 +2391,7 @@ async def test_get_api_key_metadata_resolves_session_key_via_spend_log_window(): ) mock_prisma.db.query_raw = AsyncMock(return_value=[]) - spend_log_query_raw = _spend_log_transaction( + spend_log_query_raw = _recovery_transaction( mock_prisma, [_spend_log_row(session_digest, "cli-session-user-42", "user-42")] ) @@ -2400,3 +2421,107 @@ def test_spend_logs_window_is_none_when_no_date_parses(): from litellm.proxy.management_endpoints.common_daily_activity import _spend_logs_window assert _spend_logs_window({"garbage", ""}) is None + + +@pytest.mark.asyncio +async def test_get_api_key_metadata_resolves_cli_session_keys_from_the_key_itself(): + mock_prisma = MagicMock() + mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.query_raw = AsyncMock(side_effect=AssertionError("no reverse-hash or spend-log scan expected")) + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="alice", user_email="alice@example.com", teams=["team-a"])] + ) + + result = await get_api_key_metadata(prisma_client=mock_prisma, api_keys={"cli-session-alice"}) + + assert result["cli-session-alice"]["key_alias"] == "cli-session-alice" + assert result["cli-session-alice"]["user_email"] == "alice@example.com" + assert result["cli-session-alice"]["team_id"] == "team-a" + + +@pytest.mark.asyncio +async def test_get_api_key_metadata_recovers_legacy_hashed_jwt_owner_from_daily_spend(): + api_key: Final = f"hashed-jwt-{hash_token('legacy-cli-session-daily-spend-owner')}" + user_id: Final = "legacy-owner" + mock_prisma: Final = MagicMock() + mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id=user_id, user_email="legacy-owner@example.com", teams=[])] + ) + recovery_query_raw: Final = _recovery_transaction( + mock_prisma, + daily_spend_owner_rows=[{"api_key": api_key, "first_owner": user_id, "last_owner": user_id}], + ) + + result: Final = await get_api_key_metadata( + prisma_client=mock_prisma, + api_keys={api_key}, + spend_logs_window=(datetime(2026, 9, 7), datetime(2026, 9, 10)), + ) + + assert result.get(api_key, {}).get("user_id") == user_id + assert result.get(api_key, {}).get("user_email") == "legacy-owner@example.com" + assert len(_calls_reading(recovery_query_raw, _SPEND_LOGS)) == 1 + assert len(_calls_reading(recovery_query_raw, _DAILY_USER_SPEND)) == 1 + + +@pytest.mark.asyncio +async def test_get_api_key_metadata_preserves_deleted_key_metadata_when_recovering_daily_spend_owner(): + api_key: Final = f"hashed-jwt-{hash_token('legacy-cli-session-daily-spend-metadata')}" + user_id: Final = "legacy-owner" + mock_prisma: Final = MagicMock() + deleted_key: Final = MagicMock() + deleted_key.token = api_key + deleted_key.key_alias = "legacy-cli-key" + deleted_key.team_id = "team-legacy" + deleted_key.user_id = None + mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[deleted_key]) + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id=user_id, user_email="legacy-owner@example.com", teams=[])] + ) + recovery_query_raw: Final = _recovery_transaction( + mock_prisma, + daily_spend_owner_rows=[{"api_key": api_key, "first_owner": user_id, "last_owner": user_id}], + ) + + result: Final = await get_api_key_metadata(prisma_client=mock_prisma, api_keys={api_key}) + + recovered_metadata: Final = result[api_key] + assert recovered_metadata.get("key_alias") == "legacy-cli-key" + assert recovered_metadata.get("team_id") == "team-legacy" + assert recovered_metadata.get("user_id") == user_id + assert recovered_metadata.get("user_email") == "legacy-owner@example.com" + recovery_query_raw.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_get_api_key_metadata_does_not_recover_daily_spend_owner_for_active_keys(): + api_key: Final = "active-token-value" + mock_prisma: Final = MagicMock() + active_key: Final = MagicMock() + active_key.token = api_key + active_key.key_alias = "active-key-alias" + active_key.team_id = "active-team" + active_key.user_id = "active-owner" + mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[active_key]) + mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[]) + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="active-owner", user_email="active-owner@example.com", teams=[])] + ) + recovery_query_raw: Final = _recovery_transaction( + mock_prisma, + daily_spend_owner_rows=[{"api_key": api_key, "first_owner": "other-owner", "last_owner": "other-owner"}], + ) + + result: Final = await get_api_key_metadata(prisma_client=mock_prisma, api_keys={api_key}) + + active_metadata: Final = result[api_key] + assert active_metadata.get("key_alias") == "active-key-alias" + assert active_metadata.get("team_id") == "active-team" + assert active_metadata.get("user_id") == "active-owner" + assert active_metadata.get("user_email") == "active-owner@example.com" + assert active_metadata.get("key_exists") is True + recovery_query_raw.assert_not_awaited() diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py index fb89e3a6973b..f26b978e0fae 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py @@ -1446,6 +1446,7 @@ async def test_pass_through_request_contains_proxy_server_request_in_kwargs(): mock_user_api_key_dict = MagicMock() mock_user_api_key_dict.api_key = "test-api-key" mock_user_api_key_dict.key_alias = "test-alias" + mock_user_api_key_dict.is_session_token = False mock_user_api_key_dict.user_email = "test@example.com" mock_user_api_key_dict.user_id = "test-user-id" mock_user_api_key_dict.team_id = "test-team-id" @@ -6522,3 +6523,32 @@ async def fake_add_litellm_data_to_request(**kwargs: object) -> object: record = next(r for r in caplog.records if "Exception occured" in r.getMessage()) assert record.litellm_call_id == call_id assert call_id in record.getMessage() + + +def test_passthrough_attributes_a_cli_session_to_its_alias_not_the_login_token(): + from litellm.proxy.spend_tracking.spend_tracking_utils import _get_spend_logs_metadata + + mock_request = MagicMock(spec=Request) + mock_request.method = "POST" + mock_request.url = "http://0.0.0.0:4000/anthropic/v1/messages" + mock_request.headers = Headers({}) + mock_request.scope = {} + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + key_alias="cli-session-alice", + user_id="alice", + is_session_token=True, + ) + + kwargs = HttpPassThroughEndpointHelpers._init_kwargs_for_pass_through_endpoint( + request=mock_request, + user_api_key_dict=session, + passthrough_logging_payload=MagicMock(), + logging_obj=MagicMock(), + _parsed_body={}, + litellm_call_id="lit-6852-passthrough-call-id", + ) + + metadata = kwargs["litellm_params"]["metadata"] + assert metadata["user_api_key"] == "cli-session-alice" + assert _get_spend_logs_metadata(metadata)["user_api_key"] == "cli-session-alice" diff --git a/tests/test_litellm/proxy/spend_tracking/test_key_metadata_recovery.py b/tests/test_litellm/proxy/spend_tracking/test_key_metadata_recovery.py index 89be341c87b4..4d6915914c20 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_key_metadata_recovery.py +++ b/tests/test_litellm/proxy/spend_tracking/test_key_metadata_recovery.py @@ -1,23 +1,35 @@ import asyncio +import re import time -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from datetime import datetime, timedelta +from pathlib import Path from types import SimpleNamespace +from typing import Final from unittest.mock import AsyncMock, MagicMock +import litellm_proxy_extras +import psycopg import pytest from prisma.errors import PrismaError +from psycopg.rows import dict_row +from psycopg.types.json import Jsonb +from pytest_postgresql import factories from litellm.caching.in_memory_cache import InMemoryCache from litellm.constants import ( SPEND_LOG_KEY_METADATA_CACHE_TTL, SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL, SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS, + SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE, ) from litellm.proxy.spend_tracking.key_metadata_recovery import ( + attach_user_details, fill_missing_api_key_aliases, + recover_cli_session_key_metadata, recover_double_hashed_key_metadata, recover_key_metadata_from_spend_logs, + recover_key_owner_from_daily_spend, ) from litellm.proxy.utils import hash_token @@ -584,7 +596,471 @@ async def test_recover_key_metadata_from_spend_logs_bounds_the_scan_with_a_state await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=InMemoryCache()) - assert calls == [f"SET LOCAL statement_timeout = {SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS}", "scan"] + assert calls == [ + f"SET LOCAL statement_timeout = {SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS}", + "SET LOCAL enable_bitmapscan = off", + "scan", + ] + assert mock_prisma.db.tx.call_args.kwargs["timeout"] == timedelta( + milliseconds=2 * SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS + ) + + +_spend_logs_postgresql_proc: Final = factories.postgresql_proc() +_spend_logs_postgresql: Final = factories.postgresql("_spend_logs_postgresql_proc") + +_SPEND_LOGS_DDL: Final = """ + CREATE TABLE "LiteLLM_SpendLogs" ( + request_id TEXT PRIMARY KEY, + api_key TEXT NOT NULL DEFAULT '', + "startTime" TIMESTAMP(3) NOT NULL, + "user" TEXT DEFAULT '', + team_id TEXT, + metadata JSONB DEFAULT '{}' + ) +""" + +_API_KEY_START_TIME_INDEX_MIGRATION: Final = ( + Path(litellm_proxy_extras.__file__).parent + / "migrations" + / "20260823000000_add_spend_logs_api_key_starttime_index" + / "migration.sql" +) + +_SPEND_LOG_ROWS_READ_IN_THIS_TRANSACTION_SQL: Final = """ + SELECT COALESCE(seq_tup_read, 0) + COALESCE(idx_tup_fetch, 0) AS rows_read + FROM pg_stat_xact_user_tables + WHERE relname = 'LiteLLM_SpendLogs' +""" + + +def _create_spend_logs_table(conn: psycopg.Connection) -> None: + conn.execute(_SPEND_LOGS_DDL) # pyright: ignore[reportArgumentType] # DDL literal + conn.execute(_API_KEY_START_TIME_INDEX_MIGRATION.read_text()) # pyright: ignore[reportArgumentType] # migration file + + +def _psycopg_prisma(conn: psycopg.Connection) -> MagicMock: + async def query_raw(sql: str, *params: object) -> list[dict[str, object]]: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + re.sub(r"\$(\d+)", r"%(p\1)s", sql), # pyright: ignore[reportArgumentType] # proxy SQL is not a literal + {f"p{i}": v for i, v in enumerate(params, start=1)}, + ) + return cur.fetchall() + + async def execute_raw(sql: str) -> int: + conn.execute(sql) # pyright: ignore[reportArgumentType] # proxy SQL is not a literal + return 0 + + mock_prisma: Final = MagicMock() + transaction: Final = MagicMock() + transaction.query_raw = AsyncMock(side_effect=query_raw) + transaction.execute_raw = AsyncMock(side_effect=execute_raw) + mock_prisma.db.tx.return_value.__aenter__.return_value = transaction + return mock_prisma + + +def _commit_and_vacuum(conn: psycopg.Connection) -> None: + conn.commit() + conn.set_autocommit(True) + conn.execute('VACUUM (ANALYZE) "LiteLLM_SpendLogs"') + conn.set_autocommit(False) + + +def _insert_nameless_spend_logs(conn: psycopg.Connection, digest: str, rows: int) -> None: + conn.execute( + """ + INSERT INTO "LiteLLM_SpendLogs" (request_id, api_key, "startTime") + SELECT %(digest)s || '-' || g, %(digest)s, %(start)s + g * interval '1 minute' + FROM generate_series(1, %(rows)s) g + """, + {"digest": digest, "start": datetime(2026, 9, 7), "rows": rows}, + ) + + +def _named_spend_log( + digest: str, logged_at: datetime, alias: str | None, user: str | None, team: str | None = None +) -> tuple[str, str, datetime, str, str | None, Jsonb]: + return ( + f"{digest}-{logged_at.isoformat()}", + digest, + logged_at, + user or "", + team, + Jsonb({"user_api_key_alias": alias} if alias else {}), + ) + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_names_a_key_by_its_oldest_and_newest_named_rows_in_the_window( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + unnamed_edges, owner_logged_late, reowned, outside_window, never_named = ( + hash_token(f"cli-session-{name}") for name in ("edges", "late", "reowned", "window", "never") + ) + with conn.cursor() as cur: + cur.executemany( + 'INSERT INTO "LiteLLM_SpendLogs" (request_id, api_key, "startTime", "user", team_id, metadata)' + " VALUES (%s, %s, %s, %s, %s, %s)", + ( + _named_spend_log(unnamed_edges, datetime(2026, 9, 7, 1), None, None), + _named_spend_log(unnamed_edges, datetime(2026, 9, 8), "cli-a", "alice", "team-a"), + _named_spend_log(unnamed_edges, datetime(2026, 9, 9), "cli-a", "alice", "team-a"), + _named_spend_log(unnamed_edges, datetime(2026, 9, 9, 23), None, None), + _named_spend_log(owner_logged_late, datetime(2026, 9, 7, 1), "cli-b", None), + _named_spend_log(owner_logged_late, datetime(2026, 9, 9), "cli-b", "bob"), + _named_spend_log(reowned, datetime(2026, 9, 7, 1), "cli-c", "carol"), + _named_spend_log(reowned, datetime(2026, 9, 9), "cli-c", "dave"), + _named_spend_log(outside_window, datetime(2026, 9, 6), "stale-alias", "erin"), + _named_spend_log(outside_window, datetime(2026, 9, 8), "cli-d", "erin"), + _named_spend_log(outside_window, datetime(2026, 9, 10), "later-alias", "erin"), + _named_spend_log(never_named, datetime(2026, 9, 8), None, None), + ), + ) + conn.commit() + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), + {unnamed_edges, owner_logged_late, reowned, outside_window, never_named}, + (datetime(2026, 9, 7), datetime(2026, 9, 10)), + cache=InMemoryCache(), + ) + + assert dict(result) == { + unnamed_edges: {"key_alias": "cli-a", "team_id": "team-a", "user_id": "alice"}, + owner_logged_late: {"key_alias": "cli-b", "team_id": None, "user_id": "bob"}, + reowned: {"key_alias": "cli-c", "team_id": None, "user_id": None}, + outside_window: {"key_alias": "cli-d", "team_id": None, "user_id": "erin"}, + } + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_reads_two_rows_per_key_however_many_the_key_logged( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + owners: Final[Mapping[str, str]] = {hash_token(f"cli-session-busy-{i}"): f"user-{i}" for i in range(5)} + for digest, owner in owners.items(): + conn.execute( + """ + INSERT INTO "LiteLLM_SpendLogs" (request_id, api_key, "startTime", "user", metadata) + SELECT %(digest)s || '-' || g, %(digest)s, %(start)s + g * interval '1 minute', %(owner)s, + jsonb_build_object('user_api_key_alias', 'cli-session-' || %(owner)s) + FROM generate_series(1, 2000) g + """, + {"digest": digest, "owner": owner, "start": datetime(2026, 9, 7)}, + ) + conn.execute('ANALYZE "LiteLLM_SpendLogs"') + conn.commit() + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), frozenset(owners), (datetime(2026, 9, 7), datetime(2026, 9, 10)), cache=InMemoryCache() + ) + + assert {digest: meta.get("user_id") for digest, meta in result.items()} == owners + rows_read: Final = conn.execute(_SPEND_LOG_ROWS_READ_IN_THIS_TRANSACTION_SQL).fetchone() # pyright: ignore[reportArgumentType] # SQL literal + assert rows_read is not None and rows_read[0] <= 2 * len(owners) + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_walks_a_bounded_number_of_nameless_rows_per_key( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + named_late: Final[Mapping[str, str]] = {hash_token(f"cli-session-late-{i}"): f"user-{i}" for i in range(3)} + never_named: Final = frozenset(hash_token(f"cli-session-never-{i}") for i in range(3)) + for digest in (*named_late, *never_named): + _insert_nameless_spend_logs(conn, digest, 3 * SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE) + for digest, owner in named_late.items(): + conn.execute( + """ + INSERT INTO "LiteLLM_SpendLogs" (request_id, api_key, "startTime", "user", metadata) + VALUES (%(digest)s || '-newest', %(digest)s, %(logged_at)s, %(owner)s, + jsonb_build_object('user_api_key_alias', 'cli-session-' || %(owner)s)) + """, + {"digest": digest, "owner": owner, "logged_at": datetime(2026, 9, 9)}, + ) + conn.execute('ANALYZE "LiteLLM_SpendLogs"') + conn.commit() + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), + frozenset(named_late) | never_named, + (datetime(2026, 9, 7), datetime(2026, 9, 10)), + cache=InMemoryCache(), + ) + + assert {digest: meta.get("user_id") for digest, meta in result.items()} == named_late + rows_read: Final = conn.execute(_SPEND_LOG_ROWS_READ_IN_THIS_TRANSACTION_SQL).fetchone() # pyright: ignore[reportArgumentType] # SQL literal + assert rows_read is not None + assert rows_read[0] <= 3 * SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE * (len(named_late) + len(never_named)) + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_reads_a_short_nameless_key_once( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + rows_per_key: Final = SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE // 2 + never_named: Final = frozenset(hash_token(f"cli-session-short-{i}") for i in range(20)) + for digest in never_named: + _insert_nameless_spend_logs(conn, digest, rows_per_key) + _commit_and_vacuum(conn) + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), never_named, (datetime(2026, 9, 7), datetime(2026, 9, 10)), cache=InMemoryCache() + ) + + assert dict(result) == {} + rows_read: Final = conn.execute(_SPEND_LOG_ROWS_READ_IN_THIS_TRANSACTION_SQL).fetchone() # pyright: ignore[reportArgumentType] # SQL literal + assert rows_read is not None + assert rows_read[0] <= rows_per_key * len(never_named) + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_bounds_a_busy_nameless_key_among_short_keys_before_any_vacuum( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + busy: Final = frozenset(hash_token(f"cli-session-busy-nameless-{i}") for i in range(3)) + for short_key in range(200): + _insert_nameless_spend_logs( + conn, hash_token(f"cli-session-short-{short_key}"), SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE // 5 + ) + for digest in busy: + _insert_nameless_spend_logs(conn, digest, 30 * SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE) + conn.execute('ANALYZE "LiteLLM_SpendLogs"') + conn.commit() + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), busy, (datetime(2026, 9, 7), datetime(2026, 9, 10)), cache=InMemoryCache() + ) + + assert dict(result) == {} + rows_read: Final = conn.execute(_SPEND_LOG_ROWS_READ_IN_THIS_TRANSACTION_SQL).fetchone() # pyright: ignore[reportArgumentType] # SQL literal + assert rows_read is not None + assert rows_read[0] <= 3 * SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE * len(busy) + + +@pytest.mark.asyncio +async def test_recover_key_metadata_from_spend_logs_finds_a_name_logged_where_the_oldest_probe_stopped( + _spend_logs_postgresql: psycopg.Connection, +): + conn: Final = _spend_logs_postgresql + _create_spend_logs_table(conn) + start: Final = datetime(2026, 9, 7) + past_the_stop, tied_with_the_stop = (hash_token(f"cli-session-{name}") for name in ("past", "tied")) + same_millisecond: Final = tuple( + start + timedelta(minutes=SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE, microseconds=n) for n in (100, 200, 300) + ) + with conn.cursor() as cur: + cur.executemany( + 'INSERT INTO "LiteLLM_SpendLogs" (request_id, api_key, "startTime", "user", team_id, metadata)' + " VALUES (%s, %s, %s, %s, %s, %s)", + ( + *( + _named_spend_log(past_the_stop, start + timedelta(minutes=minute), None, None) + for minute in range(1, SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE + 20) + ), + _named_spend_log( + past_the_stop, + start + timedelta(minutes=SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE + 20), + "cli-p", + "pat", + ), + *( + _named_spend_log(past_the_stop, start + timedelta(minutes=minute), None, None) + for minute in range( + SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE + 21, SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE + 51 + ) + ), + *( + _named_spend_log(tied_with_the_stop, start + timedelta(minutes=minute), None, None) + for minute in range(1, SPEND_LOG_KEY_METADATA_ROWS_PER_PROBE) + ), + _named_spend_log(tied_with_the_stop, same_millisecond[0], None, None), + _named_spend_log(tied_with_the_stop, same_millisecond[1], None, None), + _named_spend_log(tied_with_the_stop, same_millisecond[2], "cli-t", "tess"), + ), + ) + conn.commit() + + result = await recover_key_metadata_from_spend_logs( + _psycopg_prisma(conn), + {past_the_stop, tied_with_the_stop}, + (start, datetime(2026, 9, 10)), + cache=InMemoryCache(), + ) + + assert dict(result) == { + past_the_stop: {"key_alias": "cli-p", "team_id": None, "user_id": "pat"}, + tied_with_the_stop: {"key_alias": "cli-t", "team_id": None, "user_id": "tess"}, + } + + +@pytest.mark.asyncio +async def test_recover_cli_session_key_metadata_names_the_owner_only_when_the_suffix_is_a_real_user(): + mock_prisma = MagicMock() + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="alice", user_email="alice@example.com", teams=[])] + ) + raw_login_token = "cli-session-Qm7xJ2kP9sLw4vT1nR8yAa" + + result = await recover_cli_session_key_metadata( + mock_prisma, {"cli-session-alice", raw_login_token, hash_token("sk-other"), "cli-session-", "sk-raw"} + ) + + assert dict(result) == {"cli-session-alice": {"key_alias": "cli-session-alice", "user_id": "alice"}} + assert sorted(mock_prisma.db.litellm_usertable.find_many.call_args.kwargs["where"]["user_id"]["in"]) == [ + "Qm7xJ2kP9sLw4vT1nR8yAa", + "alice", + ] + + +@pytest.mark.asyncio +async def test_fill_missing_api_key_aliases_resolves_cli_session_keys_without_a_digest_lookup(): + mock_prisma = MagicMock() + mock_prisma.db.query_raw = AsyncMock(side_effect=AssertionError("no reverse-hash lookup expected")) + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="alice", user_email="alice@example.com", teams=["team-a"])] + ) + rows = ({"api_key": "cli-session-alice", "api_key_alias": None, "team_id": None, "user_email": None, "spend": 2.0},) + + filled = await fill_missing_api_key_aliases(mock_prisma, rows) + + assert filled[0]["api_key_alias"] == "cli-session-alice" + assert filled[0]["user_email"] == "alice@example.com" + assert filled[0]["team_id"] == "team-a" + assert filled[0]["spend"] == 2.0 + assert mock_prisma.db.litellm_usertable.find_many.call_args.kwargs["where"] == {"user_id": {"in": ["alice"]}} + + +@pytest.mark.asyncio +async def test_attach_user_details_gives_the_login_team_only_to_cli_session_keys(): + mock_prisma = MagicMock() + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="alice", user_email="alice@example.com", teams=["team-a"])] + ) + personal_key = hash_token("sk-personal") + + attached = await attach_user_details( + mock_prisma, + { + "cli-session-alice": {"key_alias": "cli-session-alice", "user_id": "alice"}, + personal_key: {"key_alias": "personal", "user_id": "alice"}, + }, + ) + + assert attached["cli-session-alice"]["team_id"] == "team-a" + assert attached["cli-session-alice"]["user_email"] == "alice@example.com" + assert "team_id" not in attached[personal_key] + assert attached[personal_key]["user_email"] == "alice@example.com" + + +@pytest.mark.asyncio +async def test_attach_user_details_claims_no_team_for_a_multi_team_user_session_key(): + mock_prisma = MagicMock() + mock_prisma.db.litellm_usertable.find_many = AsyncMock( + return_value=[SimpleNamespace(user_id="bob", user_email="bob@example.com", teams=["team-a", "team-b"])] + ) + + attached = await attach_user_details( + mock_prisma, {"cli-session-bob": {"key_alias": "cli-session-bob", "user_id": "bob"}} + ) + + assert "team_id" not in attached["cli-session-bob"] + assert attached["cli-session-bob"]["user_email"] == "bob@example.com" + + +def _daily_spend_owner_row(api_key: str, first_owner: str, last_owner: str) -> dict[str, str]: + return {"api_key": api_key, "first_owner": first_owner, "last_owner": last_owner} + + +def _daily_spend_transaction(mock_prisma: MagicMock, query_raw: AsyncMock) -> MagicMock: + transaction: Final = MagicMock() + transaction.execute_raw = AsyncMock(return_value=0) + transaction.query_raw = query_raw + mock_prisma.db.tx.return_value.__aenter__.return_value = transaction + return transaction + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_keeps_a_unanimous_owner(): + key: Final = "hashed-jwt-digest-a" + mock_prisma: Final = MagicMock() + _daily_spend_transaction(mock_prisma, AsyncMock(return_value=[_daily_spend_owner_row(key, "owner-a", "owner-a")])) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, {key}) + + assert dict(result) == {key: "owner-a"} + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_drops_conflicting_owners(): + key: Final = "hashed-jwt-digest-b" + mock_prisma: Final = MagicMock() + _daily_spend_transaction(mock_prisma, AsyncMock(return_value=[_daily_spend_owner_row(key, "owner-a", "owner-b")])) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, {key}) + + assert dict(result) == {} + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_skips_empty_input(): + mock_prisma: Final = MagicMock() + transaction: Final = _daily_spend_transaction(mock_prisma, AsyncMock(return_value=[])) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, frozenset()) + + assert dict(result) == {} + transaction.query_raw.assert_not_awaited() + mock_prisma.db.tx.assert_not_called() + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_returns_empty_on_prisma_error(): + mock_prisma: Final = MagicMock() + _daily_spend_transaction(mock_prisma, AsyncMock(side_effect=PrismaError("db down"))) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, {"hashed-jwt-digest-c"}) + + assert dict(result) == {} + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_names_no_owner_when_the_lookup_hits_the_statement_timeout(): + mock_prisma: Final = MagicMock() + _daily_spend_transaction( + mock_prisma, AsyncMock(side_effect=PrismaError("canceling statement due to statement timeout")) + ) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, {"hashed-jwt-digest-d"}) + + assert dict(result) == {} + + +@pytest.mark.asyncio +async def test_recover_key_owner_from_daily_spend_bounds_the_lookup_with_a_statement_timeout(): + key: Final = "hashed-jwt-digest-e" + mock_prisma: Final = MagicMock() + transaction: Final = _daily_spend_transaction( + mock_prisma, AsyncMock(return_value=[_daily_spend_owner_row(key, "owner-a", "owner-a")]) + ) + + result: Final = await recover_key_owner_from_daily_spend(mock_prisma, {key}) + + assert dict(result) == {key: "owner-a"} + assert [name for name, _, _ in transaction.mock_calls] == ["execute_raw", "query_raw"] + transaction.execute_raw.assert_awaited_once_with( + f"SET LOCAL statement_timeout = {SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS}" + ) assert mock_prisma.db.tx.call_args.kwargs["timeout"] == timedelta( milliseconds=2 * SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS ) diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py index 9de6679472e9..4b43acbc7df0 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py +++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py @@ -6889,6 +6889,33 @@ def test_key_spend_report_scopes_to_caller_key(client, monkeypatch): app.dependency_overrides.pop(ps.user_api_key_auth, None) +def test_key_spend_report_scopes_a_cli_session_to_the_per_user_alias_not_the_login_token(client, monkeypatch): + mock_prisma = _spend_report_mock_prisma( + query_raw_returns=[{"api_key": "cli-session-alice", "total_cost": 1.5}] + ) + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma) + monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True) + app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth( + user_role=LitellmUserRoles.INTERNAL_USER, + user_id="alice", + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + key_alias="cli-session-alice", + is_session_token=True, + ) + try: + response = client.get( + "/key/spend/report", + params={"start_date": "2026-07-01", "end_date": "2026-07-31", "api_key": "cli-session-alice"}, + headers={"Authorization": "Bearer sk-test"}, + ) + assert response.status_code == 200, response.text + assert response.json() == [{"api_key": "cli-session-alice", "total_cost": 1.5}] + args, _ = mock_prisma.db.query_raw.await_args + assert args[3] == "cli-session-alice" + finally: + app.dependency_overrides.pop(ps.user_api_key_auth, None) + + def test_key_spend_report_non_admin_override_403(client, monkeypatch): mock_prisma = _spend_report_mock_prisma() monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma) diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py index f471e3f8fbb1..2f284447dd6b 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py +++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py @@ -5156,6 +5156,64 @@ def test_spend_log_request_id_is_the_response_id_a_bridged_messages_caller_recei ) +_CLI_SESSION_ALIAS: Final = "cli-session-alice" +_CLI_SESSION_TOKEN: Final = "cli-session-Qm7xJ2kP9sLw4vT1nR8yAa" + + +def _cli_session_request_metadata(logged_key: str) -> dict[str, str]: + return { + "user_api_key": logged_key, + "user_api_key_hash": logged_key, + "user_api_key_alias": _CLI_SESSION_ALIAS, + "user_api_key_user_id": "alice", + } + + +@pytest.mark.parametrize("call_type", ["acompletion", "anthropic_messages", "aresponses"]) +def test_get_logging_payload_attributes_a_cli_session_to_its_alias(call_type: str): + payload = get_logging_payload( + kwargs={ + "call_type": call_type, + "model": "gpt-5.4-nano", + "response_cost": 0.00001, + "litellm_params": {"metadata": _cli_session_request_metadata(_CLI_SESSION_ALIAS)}, + }, + response_obj=litellm.ModelResponse(id=f"{call_type}-1", choices=[], usage=litellm.Usage()), + start_time=datetime.datetime.now(timezone.utc), + end_time=datetime.datetime.now(timezone.utc), + ) + + assert payload["api_key"] == _CLI_SESSION_ALIAS + assert json.loads(payload["metadata"])["user_api_key"] == _CLI_SESSION_ALIAS + assert json.loads(payload["metadata"])["user_api_key_alias"] == _CLI_SESSION_ALIAS + + +@pytest.mark.parametrize("call_type", ["acompletion", "anthropic_messages", "aresponses"]) +def test_get_logging_payload_never_lands_a_raw_cli_session_token(call_type: str): + payload = get_logging_payload( + kwargs={ + "call_type": call_type, + "model": "gpt-5.4-nano", + "litellm_params": {"metadata": _cli_session_request_metadata(_CLI_SESSION_TOKEN)}, + }, + response_obj=litellm.ModelResponse(id=f"{call_type}-2", choices=[], usage=litellm.Usage()), + start_time=datetime.datetime.now(timezone.utc), + end_time=datetime.datetime.now(timezone.utc), + ) + + assert payload["api_key"] == hash_token(_CLI_SESSION_TOKEN) + assert json.loads(payload["metadata"])["user_api_key"] == hash_token(_CLI_SESSION_TOKEN) + + +def test_redact_logged_api_key_cli_session_alias_needs_alias_provenance(): + assert _redact_logged_api_key(_CLI_SESSION_ALIAS, already_redacted=True, key_alias=_CLI_SESSION_ALIAS) == ( + _CLI_SESSION_ALIAS + ) + assert _redact_logged_api_key(_CLI_SESSION_ALIAS, already_redacted=True) == hash_token(_CLI_SESSION_ALIAS) + assert _redact_logged_api_key(_CLI_SESSION_ALIAS, key_alias=_CLI_SESSION_ALIAS) == hash_token(_CLI_SESSION_ALIAS) + assert _redact_logged_api_key("alice", already_redacted=True, key_alias="alice") == hash_token("alice") + + def test_azure_spillover_stamped_from_response_headers(): """Raw provider response headers on the logging kwargs mark the request as spilled.""" kwargs: Final = { diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py index 88d38d74f498..cad2d237689d 100644 --- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py +++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py @@ -8176,3 +8176,37 @@ def test_default_team_settings_bool_turn_off_message_logging_redacts(): ) is True ) + + +def test_add_user_api_key_auth_to_request_metadata_attributes_a_cli_session_to_its_alias(): + data = {"model": "gpt-5.4-nano", "messages": [{"role": "user", "content": "hi"}], "litellm_metadata": {}} + session = UserAPIKeyAuth( + api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa", + key_alias="cli-session-alice", + user_id="alice", + is_session_token=True, + ) + + metadata = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata( + data=data, user_api_key_dict=session, _metadata_variable_name="litellm_metadata" + )["litellm_metadata"] + + assert metadata["user_api_key"] == "cli-session-alice" + assert metadata["user_api_key_hash"] == "cli-session-alice" + assert metadata["user_api_key_alias"] == "cli-session-alice" + assert "Qm7xJ2kP9sLw4vT1nR8yAa" not in (metadata["user_api_key"], metadata["user_api_key_hash"]) + + +def test_add_user_api_key_auth_to_request_metadata_keeps_the_hashed_token_for_virtual_keys(): + from litellm.proxy._types import hash_token + + data = {"model": "gpt-5.4-nano", "messages": [], "litellm_metadata": {}} + hashed = hash_token("sk-virtual-key") + virtual_key = UserAPIKeyAuth(api_key=hashed, key_alias="cli-session-alice", user_id="alice") + + metadata = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata( + data=data, user_api_key_dict=virtual_key, _metadata_variable_name="litellm_metadata" + )["litellm_metadata"] + + assert metadata["user_api_key"] == hashed + assert metadata["user_api_key_hash"] == hashed diff --git a/ui/litellm-dashboard/src/components/UsagePage/types.ts b/ui/litellm-dashboard/src/components/UsagePage/types.ts index d53db68bb9f6..6d0e0642ba24 100644 --- a/ui/litellm-dashboard/src/components/UsagePage/types.ts +++ b/ui/litellm-dashboard/src/components/UsagePage/types.ts @@ -58,6 +58,7 @@ export interface TopApiKeyData { api_key: string; key_alias: string | null; team_id: string | null; + user: string | null; spend: number; requests: number; tokens: number; diff --git a/ui/litellm-dashboard/src/components/activity_metrics.test.tsx b/ui/litellm-dashboard/src/components/activity_metrics.test.tsx index 1bd7655b5e3b..569f69adb56c 100644 --- a/ui/litellm-dashboard/src/components/activity_metrics.test.tsx +++ b/ui/litellm-dashboard/src/components/activity_metrics.test.tsx @@ -258,10 +258,20 @@ describe("ActivityMetrics", () => { api_key: "key-123", key_alias: "Test Key", team_id: "team1", + user: "owner@example.com", spend: 50.25, requests: 25, tokens: 12500, }, + { + api_key: "key-456", + key_alias: "Owner Alias", + team_id: null, + user: "Owner Alias", + spend: 40.25, + requests: 20, + tokens: 10000, + }, ], }, }; @@ -269,6 +279,9 @@ describe("ActivityMetrics", () => { render(); expect(screen.getByText("Top Virtual Keys by Spend")).toBeInTheDocument(); expect(screen.getByText("Test Key")).toBeInTheDocument(); + expect(screen.getByText("User: owner@example.com")).toBeInTheDocument(); + expect(screen.getByText("Owner Alias")).toBeInTheDocument(); + expect(screen.queryByText("User: Owner Alias")).not.toBeInTheDocument(); }); it("should display API key hash when alias is missing", () => { @@ -280,6 +293,7 @@ describe("ActivityMetrics", () => { api_key: "key-1234567890", key_alias: null, team_id: null, + user: null, spend: 50.25, requests: 25, tokens: 12500, @@ -301,6 +315,7 @@ describe("ActivityMetrics", () => { api_key: "key-123", key_alias: "Test Key", team_id: "team1", + user: null, spend: 50.25, requests: 25, tokens: 12500, @@ -1056,6 +1071,8 @@ describe("processActivityData", () => { metadata: { key_alias: "test-key-1", team_id: "team1", + user_id: "owner-id-1", + user_email: "owner-1@example.com", }, }, "key-2": { @@ -1073,6 +1090,7 @@ describe("processActivityData", () => { metadata: { key_alias: "test-key-2", team_id: "team2", + user_id: "owner-id-2", }, }, }, @@ -1094,6 +1112,10 @@ describe("processActivityData", () => { expect(result["gpt-4"].top_api_keys[0].spend).toBe(60.0); expect(result["gpt-4"].top_api_keys[0].api_key).toBe("key-1"); expect(result["gpt-4"].top_api_keys[1].spend).toBe(40.5); + expect(result["gpt-4"].top_api_keys.map(({ api_key, user }) => [api_key, user])).toEqual([ + ["key-1", "owner-1@example.com"], + ["key-2", "owner-id-2"], + ]); }); it("should limit top_api_keys to 5 entries", () => { diff --git a/ui/litellm-dashboard/src/components/activity_metrics.tsx b/ui/litellm-dashboard/src/components/activity_metrics.tsx index 95315f8ec27e..5ddb89703ea0 100644 --- a/ui/litellm-dashboard/src/components/activity_metrics.tsx +++ b/ui/litellm-dashboard/src/components/activity_metrics.tsx @@ -102,20 +102,26 @@ const ModelSection = ({

Top Virtual Keys by Spend

- {metrics.top_api_keys.map((keyData) => ( -
-
-

{keyData.key_alias || `${keyData.api_key.substring(0, 10)}...`}

- {keyData.team_id &&

Team: {keyData.team_id}

} + {metrics.top_api_keys.map((keyData) => { + const keyLabel = keyData.key_alias || `${keyData.api_key.substring(0, 10)}...`; + return ( +
+
+

{keyLabel}

+ {keyData.team_id &&

Team: {keyData.team_id}

} + {keyData.user && keyData.user !== keyLabel && ( +

User: {keyData.user}

+ )} +
+
+

${formatNumberWithCommas(keyData.spend, 2)}

+

+ {keyData.requests.toLocaleString()} requests | {keyData.tokens.toLocaleString()} tokens +

+
-
-

${formatNumberWithCommas(keyData.spend, 2)}

-

- {keyData.requests.toLocaleString()} requests | {keyData.tokens.toLocaleString()} tokens -

-
-
- ))} + ); + })}
@@ -585,6 +591,7 @@ export const processActivityData = ( api_key: apiKey, key_alias: keyActivityLabel(keyData.metadata, "") || null, team_id: keyData.metadata.team_id, + user: keyData.metadata.user_email ?? keyData.metadata.user_id ?? null, spend: 0, requests: 0, tokens: 0, diff --git a/uv.lock b/uv.lock index bb3a37518abb..7c4ef19940ea 100644 --- a/uv.lock +++ b/uv.lock @@ -4509,7 +4509,7 @@ wheels = [ [[package]] name = "litellm" -version = "1.103.1" +version = "1.103.2" source = { editable = "." } dependencies = [ { name = "aiohttp" }, @@ -4942,7 +4942,7 @@ proxy-dev = [ [[package]] name = "litellm-enterprise" -version = "0.1.69" +version = "0.1.69.post1" source = { editable = "enterprise" } [[package]]