The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
import asyncio
import time
from collections.abc import Awaitable, Callable, Sequence
from datetime import datetime, timedelta
from types import SimpleNamespace
from typing import Final
from unittest.mock import AsyncMock, MagicMock
import pytest
from prisma.errors import PrismaError
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,
)
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
from litellm.proxy.db.log_db_metrics import record_db_io
class _FakeClock:
def __init__(self) -> None:
self.now = 1000.0
def advance(self, seconds: float) -> None:
self.now += seconds
def __call__(self) -> float:
return self.now
def _digest_row(digest: str, key_alias: str | None, team_id: str | None, user_id: str | None) -> dict[str, str | None]:
return {"digest": digest, "key_alias": key_alias, "team_id": team_id, "user_id": user_id}
def _query_raw_spend_logs(rows: Sequence[dict[str, str | None]]) -> AsyncMock:
async def query_raw(sql: str, *params: object) -> list[dict[str, str | None]]:
if '"LiteLLM_SpendLogs"' in sql:
return list(rows)
raise AssertionError(f"unexpected query: {sql}")
return AsyncMock(side_effect=query_raw)
def _spend_log_row(digest: str, key_alias: str | None, team_id: str | None, user_id: str | None) -> dict[str, str | None]:
return {
"digest": digest,
"first_alias": key_alias,
"last_alias": key_alias,
"first_team": team_id,
"last_team": team_id,
"first_owner": user_id,
"last_owner": user_id,
}
def _spend_log_transaction(mock_prisma: MagicMock, query_raw: AsyncMock) -> AsyncMock:
transaction = MagicMock()
transaction.execute_raw = AsyncMock(return_value=0)
transaction.query_raw = query_raw
mock_prisma.db.tx.return_value.__aenter__.return_value = transaction
return query_raw
def _query_raw_by_table(
active_rows: Sequence[dict[str, str | None]],
deleted_rows: Sequence[dict[str, str | None]],
) -> AsyncMock:
async def query_raw(sql: str, *params: object) -> list[dict[str, str | None]]:
record_db_io()
if '"LiteLLM_VerificationToken"' in sql:
return list(active_rows)
if '"LiteLLM_DeletedVerificationToken"' in sql:
return list(deleted_rows)
raise AssertionError(f"unexpected query: {sql}")
return AsyncMock(side_effect=query_raw)
@pytest.mark.asyncio
async def test_recover_double_hashed_key_metadata_via_active_token_digest():
double_hashed = hash_token("a" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[_digest_row(double_hashed, "batch-worker", "team-1", "alice")],
deleted_rows=[],
)
result = await recover_double_hashed_key_metadata(mock_prisma, {double_hashed})
assert result[double_hashed]["key_alias"] == "batch-worker"
assert result[double_hashed]["team_id"] == "team-1"
assert result[double_hashed]["user_id"] == "alice"
((_, digests),) = [call.args for call in mock_prisma.db.query_raw.call_args_list]
assert digests == [double_hashed]
@pytest.mark.asyncio
async def test_recover_double_hashed_key_metadata_falls_back_to_deleted_tokens():
double_hashed = hash_token("y" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[],
deleted_rows=[_digest_row(double_hashed, "deleted-key", "team-del", "erin")],
)
result = await recover_double_hashed_key_metadata(mock_prisma, {double_hashed})
assert result[double_hashed]["key_alias"] == "deleted-key"
assert result[double_hashed]["team_id"] == "team-del"
assert result[double_hashed]["user_id"] == "erin"
assert [call.args[1] for call in mock_prisma.db.query_raw.call_args_list] == [[double_hashed], [double_hashed]]
@pytest.mark.asyncio
async def test_recover_only_asks_deleted_tokens_for_digests_active_keys_missed():
found_active = hash_token("1" * 64)
found_deleted = hash_token("2" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[_digest_row(found_active, "active-key", None, None)],
deleted_rows=[_digest_row(found_deleted, "deleted-key", None, None)],
)
result = await recover_double_hashed_key_metadata(mock_prisma, {found_active, found_deleted})
assert result[found_active]["key_alias"] == "active-key"
assert result[found_deleted]["key_alias"] == "deleted-key"
assert [call.args[1] for call in mock_prisma.db.query_raw.call_args_list] == [
sorted((found_active, found_deleted)),
[found_deleted],
]
@pytest.mark.asyncio
async def test_recover_permanent_miss_costs_two_digest_lookups_and_no_table_walk():
double_hashed = hash_token("b" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(active_rows=[], deleted_rows=[])
result = await recover_double_hashed_key_metadata(mock_prisma, {double_hashed})
assert result == {}
assert len(mock_prisma.db.query_raw.call_args_list) == 2
mock_prisma.db.litellm_verificationtoken.find_many.assert_not_called()
mock_prisma.db.litellm_deletedverificationtoken.find_many.assert_not_called()
@pytest.mark.asyncio
async def test_recover_skips_keys_that_are_not_sha256_digests():
mock_prisma = MagicMock()
mock_prisma.db.query_raw = AsyncMock(return_value=[])
result = await recover_double_hashed_key_metadata(mock_prisma, {"sk-plain-key", "key-hash-short"})
assert result == {}
mock_prisma.db.query_raw.assert_not_called()
@pytest.mark.asyncio
async def test_recover_returns_empty_when_digest_lookup_raises_prisma_error():
double_hashed = hash_token("c" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = AsyncMock(side_effect=PrismaError("db down"))
result = await recover_double_hashed_key_metadata(mock_prisma, {double_hashed})
assert result == {}
@pytest.mark.asyncio
async def test_fill_missing_api_key_aliases_updates_null_alias_and_email_rows():
double_hashed = hash_token("d" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[_digest_row(double_hashed, "recovered-alias", "team-9", "bob")],
deleted_rows=[],
)
mock_prisma.db.litellm_usertable.find_many = AsyncMock(
return_value=[SimpleNamespace(user_id="bob", user_email="[email protected]")]
)
rows = (
{
"api_key": double_hashed,
"api_key_alias": None,
"team_id": None,
"user_email": None,
"spend": 12.5,
},
{
"api_key": "already-joined-token",
"api_key_alias": "named-key",
"team_id": "team-ok",
"user_email": "[email protected]",
"spend": 1.0,
},
)
filled = await fill_missing_api_key_aliases(mock_prisma, rows)
assert filled[0]["api_key_alias"] == "recovered-alias"
assert filled[0]["team_id"] == "team-9"
assert filled[0]["user_email"] == "[email protected]"
assert filled[0]["spend"] == 12.5
assert filled[1]["api_key_alias"] == "named-key"
assert mock_prisma.db.litellm_usertable.find_many.call_args.kwargs["where"] == {"user_id": {"in": ["bob"]}}
@pytest.mark.asyncio
async def test_fill_missing_api_key_aliases_leaves_rows_untouched_when_nothing_is_missing():
mock_prisma = MagicMock()
mock_prisma.db.query_raw = AsyncMock(return_value=[])
rows = ({"api_key": hash_token("e" * 64), "api_key_alias": "named", "user_email": "[email protected]"},)
filled = await fill_missing_api_key_aliases(mock_prisma, rows)
assert filled == rows
mock_prisma.db.query_raw.assert_not_called()
@pytest.mark.asyncio
async def test_fill_missing_api_key_aliases_keeps_spend_user_email_when_alias_is_missing():
double_hashed = hash_token("f" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[_digest_row(double_hashed, "team-key", "team-9", "key-owner")],
deleted_rows=[],
)
mock_prisma.db.litellm_usertable.find_many = AsyncMock(
return_value=[SimpleNamespace(user_id="key-owner", user_email="[email protected]")]
)
rows = (
{
"api_key": double_hashed,
"api_key_alias": None,
"team_id": None,
"user_email": "[email protected]",
"spend": 4.0,
},
)
filled = await fill_missing_api_key_aliases(mock_prisma, rows)
assert filled[0]["api_key_alias"] == "team-key"
assert filled[0]["team_id"] == "team-9"
assert filled[0]["user_email"] == "[email protected]"
@pytest.mark.asyncio
async def test_fill_missing_api_key_aliases_skips_named_keys_that_have_no_email():
mock_prisma = MagicMock()
mock_prisma.db.query_raw = AsyncMock(return_value=[])
rows = (
{
"api_key": hash_token("g" * 64),
"api_key_alias": "service-key",
"team_id": "team-svc",
"user_email": None,
},
)
filled = await fill_missing_api_key_aliases(mock_prisma, rows)
assert filled == rows
mock_prisma.db.query_raw.assert_not_called()
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_resolves_session_token_from_metadata():
session_digest = hash_token("cli-session-repro-user-6852")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(
mock_prisma,
_query_raw_spend_logs(
[_spend_log_row(session_digest, "cli-session-repro-user-6852", None, "repro-user-6852")]
),
)
result = await recover_key_metadata_from_spend_logs(mock_prisma, {session_digest}, window, cache=InMemoryCache())
assert result[session_digest]["key_alias"] == "cli-session-repro-user-6852"
assert result[session_digest]["user_id"] == "repro-user-6852"
((_, digests, start, end),) = [call.args for call in query_raw.call_args_list]
assert digests == [session_digest]
assert (start, end) == window
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_skips_query_when_no_missing_keys():
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, AsyncMock(return_value=[]))
result = await recover_key_metadata_from_spend_logs(mock_prisma, set(), window, cache=InMemoryCache())
assert result == {}
query_raw.assert_not_called()
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_returns_empty_on_prisma_error():
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, AsyncMock(side_effect=PrismaError("db down")))
result = await recover_key_metadata_from_spend_logs(
mock_prisma, {hash_token("cli-session-x")}, window, cache=InMemoryCache()
)
assert result == {}
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_ignores_foreign_and_all_null_rows():
wanted = hash_token("cli-session-wanted")
all_null = hash_token("cli-session-null")
foreign = hash_token("cli-session-foreign")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(
mock_prisma,
_query_raw_spend_logs(
[
_spend_log_row(wanted, "kept-alias", None, "owner-1"),
_spend_log_row(all_null, None, None, None),
_spend_log_row(foreign, "foreign-alias", None, "owner-2"),
]
),
)
result = await recover_key_metadata_from_spend_logs(mock_prisma, {wanted, all_null}, window, cache=InMemoryCache())
assert set(result) == {wanted}
assert result[wanted]["key_alias"] == "kept-alias"
assert result[wanted]["user_id"] == "owner-1"
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_skips_non_sha256_keys():
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, AsyncMock(return_value=[]))
result = await recover_key_metadata_from_spend_logs(
mock_prisma, {"cli-session-raw-1798", "key-hash-short"}, window, cache=InMemoryCache()
)
assert result == {}
query_raw.assert_not_called()
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_accepts_hashed_jwt_digests():
jwt_digest = f"hashed-jwt-{hash_token('jwt-subject-1')}"
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(jwt_digest, None, "team-jwt", "jwt-user")]))
result = await recover_key_metadata_from_spend_logs(mock_prisma, {jwt_digest}, window, cache=InMemoryCache())
assert result[jwt_digest]["team_id"] == "team-jwt"
assert result[jwt_digest]["user_id"] == "jwt-user"
((_, digests, _, _),) = [call.args for call in query_raw.call_args_list]
assert digests == [jwt_digest]
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_serves_repeat_lookups_from_the_cache():
found = hash_token("cli-session-found")
unknown = hash_token("cli-session-unknown")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache = InMemoryCache()
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(found, "found-alias", None, "owner-1")]))
first = await recover_key_metadata_from_spend_logs(mock_prisma, {found, unknown}, window, cache=cache)
second = await recover_key_metadata_from_spend_logs(mock_prisma, {found, unknown}, window, cache=cache)
assert first == second
assert set(first) == {found}
assert first[found]["key_alias"] == "found-alias"
assert query_raw.await_count == 1
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_only_queries_digests_the_cache_has_not_seen():
cached_digest = hash_token("cli-session-cached")
new_digest = hash_token("cli-session-new")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache = InMemoryCache()
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(cached_digest, "cached-alias", None, None)]))
await recover_key_metadata_from_spend_logs(mock_prisma, {cached_digest}, window, cache=cache)
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(new_digest, "new-alias", None, None)]))
result = await recover_key_metadata_from_spend_logs(mock_prisma, {cached_digest, new_digest}, window, cache=cache)
assert result[cached_digest]["key_alias"] == "cached-alias"
assert result[new_digest]["key_alias"] == "new-alias"
((_, digests, _, _),) = [call.args for call in query_raw.call_args_list]
assert digests == [new_digest]
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_rescans_when_the_window_changes():
digest = hash_token("cli-session-windowed")
cache = InMemoryCache()
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([]))
await recover_key_metadata_from_spend_logs(
mock_prisma, {digest}, (datetime(2026, 9, 1), datetime(2026, 9, 4)), cache=cache
)
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(digest, "later-alias", None, None)]))
result = await recover_key_metadata_from_spend_logs(
mock_prisma, {digest}, (datetime(2026, 9, 7), datetime(2026, 9, 10)), cache=cache
)
assert result[digest]["key_alias"] == "later-alias"
assert query_raw.await_count == 1
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_retries_a_failed_query_only_after_the_miss_ttl() -> None:
digest: Final = hash_token("cli-session-retry")
window: Final = (datetime(2026, 9, 7), datetime(2026, 9, 10))
clock: Final = _FakeClock()
cache: Final = InMemoryCache(default_ttl=SPEND_LOG_KEY_METADATA_CACHE_TTL, clock=clock)
mock_prisma: Final = MagicMock()
query_raw: Final = _spend_log_transaction(
mock_prisma,
AsyncMock(
side_effect=[
PrismaError("statement timeout"),
[_spend_log_row(digest, "back-online", None, None)],
]
),
)
assert await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache) == {}
miss_key: Final = next(key for key in cache.ttl_dict if digest in key and not key.endswith(":missed-before"))
assert cache.ttl_dict[miss_key] == clock.now + SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL
assert await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache) == {}
assert query_raw.await_count == 1
clock.advance(SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL + 1)
result: Final = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache)
assert result[digest]["key_alias"] == "back-online"
assert query_raw.await_count == 2
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_never_caches_repeated_query_failures_as_long_as_a_hit() -> None:
digest: Final = hash_token("cli-session-repeated-failure")
window: Final = (datetime(2026, 9, 7), datetime(2026, 9, 10))
clock: Final = _FakeClock()
cache: Final = InMemoryCache(default_ttl=SPEND_LOG_KEY_METADATA_CACHE_TTL, clock=clock)
mock_prisma: Final = MagicMock()
query_raw: Final = _spend_log_transaction(
mock_prisma,
AsyncMock(
side_effect=[
PrismaError("statement timeout"),
PrismaError("statement timeout"),
[_spend_log_row(digest, "back-online", None, None)],
]
),
)
await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache)
miss_key: Final = next(key for key in cache.ttl_dict if digest in key and not key.endswith(":missed-before"))
assert cache.ttl_dict[miss_key] == clock.now + SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL
clock.advance(SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL + 1)
await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache)
assert query_raw.await_count == 2
assert cache.ttl_dict[miss_key] == clock.now + SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL
clock.advance(SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL + 1)
result: Final = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache)
assert result[digest]["key_alias"] == "back-online"
assert query_raw.await_count == 3
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_treats_a_dropped_connection_error_as_a_short_lived_miss():
digest: Final = hash_token("cli-session-dropped-connection")
window: Final = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache: Final = InMemoryCache(default_ttl=SPEND_LOG_KEY_METADATA_CACHE_TTL)
mock_prisma: Final = MagicMock()
_spend_log_transaction(
mock_prisma,
AsyncMock(
side_effect=[
AttributeError("'NoneType' object has no attribute 'get'"),
[_spend_log_row(digest, "back-online", None, None)],
]
),
)
started: Final = time.time()
assert await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache) == {}
miss_key: Final = next(key for key in cache.ttl_dict if digest in key and not key.endswith(":missed-before"))
assert cache.ttl_dict[miss_key] - started <= SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL + 1
assert f"{miss_key}:missed-before" not in cache.ttl_dict
cache.ttl_dict[miss_key] = time.time() - 1
result: Final = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache)
assert result[digest]["key_alias"] == "back-online"
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_drops_the_owner_of_a_digest_shared_by_several_users():
shared_ui_digest = hash_token("ui-token")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(
mock_prisma,
_query_raw_spend_logs(
[{**_spend_log_row(shared_ui_digest, "ui-token", "litellm-dashboard", None), "first_owner": "alice", "last_owner": "bob"}]
),
)
result = await recover_key_metadata_from_spend_logs(
mock_prisma, {shared_ui_digest}, window, cache=InMemoryCache()
)
assert result[shared_ui_digest] == {"key_alias": "ui-token", "team_id": "litellm-dashboard", "user_id": None}
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_keeps_the_owner_when_every_named_row_agrees():
digest = hash_token("cli-session-one-owner")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(
mock_prisma,
_query_raw_spend_logs(
[_spend_log_row(digest, None, None, "carol")]
),
)
result = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=InMemoryCache())
assert result[digest]["user_id"] == "carol"
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_forgets_a_miss_long_before_a_hit():
found = hash_token("cli-session-found")
unknown = hash_token("cli-session-unknown")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache = InMemoryCache(default_ttl=SPEND_LOG_KEY_METADATA_CACHE_TTL)
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(found, "found-alias", None, None)]))
started = time.time()
await recover_key_metadata_from_spend_logs(mock_prisma, {found, unknown}, window, cache=cache)
hit_expires = next(deadline for key, deadline in cache.ttl_dict.items() if found in key)
miss_expires = next(deadline for key, deadline in cache.ttl_dict.items() if unknown in key)
assert miss_expires - started <= SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL + 1
assert hit_expires - started >= SPEND_LOG_KEY_METADATA_CACHE_TTL - 1
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_runs_one_query_for_concurrent_lookups():
digest = hash_token("cli-session-shared")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache = InMemoryCache()
lock = asyncio.Lock()
mock_prisma = MagicMock()
async def slow_query_raw(sql: str, *params: object) -> list[dict[str, str | None]]:
await asyncio.sleep(0.01)
return [_spend_log_row(digest, "shared-alias", None, None)]
query_raw = _spend_log_transaction(mock_prisma, AsyncMock(side_effect=slow_query_raw))
results = await asyncio.gather(
*(
recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=cache, lock=lock)
for _ in range(9)
)
)
assert all(result[digest]["key_alias"] == "shared-alias" for result in results)
assert query_raw.await_count == 1
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_keeps_a_repeated_miss_as_long_as_a_hit():
unknown = hash_token("cli-session-never-named")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
cache = InMemoryCache(default_ttl=SPEND_LOG_KEY_METADATA_CACHE_TTL)
mock_prisma = MagicMock()
query_raw = _spend_log_transaction(mock_prisma, _query_raw_spend_logs([]))
await recover_key_metadata_from_spend_logs(mock_prisma, {unknown}, window, cache=cache)
first_miss_key = next(key for key in cache.ttl_dict if unknown in key and not key.endswith(":missed-before"))
cache.ttl_dict[first_miss_key] = time.time() - 1
started = time.time()
await recover_key_metadata_from_spend_logs(mock_prisma, {unknown}, window, cache=cache)
assert query_raw.await_count == 2
assert cache.ttl_dict[first_miss_key] - started >= SPEND_LOG_KEY_METADATA_CACHE_TTL - 1
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_keeps_the_owner_older_rows_agree_on_when_the_newest_is_nameless():
digest = hash_token("cli-session-owner-from-older-rows")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
_spend_log_transaction(mock_prisma, _query_raw_spend_logs([_spend_log_row(digest, None, "team-x", "alice")]))
result = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=InMemoryCache())
assert result[digest] == {"key_alias": None, "team_id": "team-x", "user_id": "alice"}
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_names_nothing_for_a_field_whose_rows_disagree():
digest = hash_token("cli-session-disagreeing-rows")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
_spend_log_transaction(
mock_prisma,
_query_raw_spend_logs(
[
{
**_spend_log_row(digest, None, None, "carol"),
"first_alias": "old-alias",
"last_alias": "renamed-alias",
"first_team": "team-a",
"last_team": "team-b",
}
]
),
)
result = await recover_key_metadata_from_spend_logs(mock_prisma, {digest}, window, cache=InMemoryCache())
assert result[digest] == {"key_alias": None, "team_id": None, "user_id": "carol"}
@pytest.mark.asyncio
async def test_recover_key_metadata_from_spend_logs_bounds_the_scan_with_a_statement_timeout():
digest = hash_token("cli-session-bounded-scan")
window = (datetime(2026, 9, 7), datetime(2026, 9, 10))
mock_prisma = MagicMock()
calls: list[str] = []
transaction = MagicMock()
transaction.execute_raw = AsyncMock(side_effect=lambda sql: calls.append(sql) or 0)
transaction.query_raw = AsyncMock(side_effect=lambda sql, *args: calls.append("scan") or [])
mock_prisma.db.tx.return_value.__aenter__.return_value = transaction
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}",
"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
)
@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="[email protected]", 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="[email protected]", 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"] == "[email protected]"
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="[email protected]", 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"] == "[email protected]"
assert "team_id" not in attached[personal_key]
assert attached[personal_key]["user_email"] == "[email protected]"
@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="[email protected]", 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"] == "[email protected]"
def _user_lookup_by_filter() -> AsyncMock:
async def find_many(*, where):
return [
SimpleNamespace(user_id=user_id, user_email=f"{user_id}@example.com", teams=[])
for user_id in where["user_id"]["in"]
]
return AsyncMock(side_effect=find_many)
@pytest.mark.asyncio
async def test_attach_user_details_chunks_more_than_5000_user_ids_and_merges_every_chunk():
mock_prisma = MagicMock()
mock_prisma.db.litellm_usertable.find_many = _user_lookup_by_filter()
recovered = {f"key-{n}": {"key_alias": f"alias-{n}", "user_id": f"user-{n}"} for n in range(12_001)}
attached = await attach_user_details(mock_prisma, recovered)
sent = [call.kwargs["where"]["user_id"]["in"] for call in mock_prisma.db.litellm_usertable.find_many.call_args_list]
assert [len(chunk) for chunk in sent] == [5_000, 5_000, 2_001]
assert sorted(user_id for chunk in sent for user_id in chunk) == sorted(f"user-{n}" for n in range(12_001))
assert all(attached[f"key-{n}"]["user_email"] == f"user-{n}@example.com" for n in range(12_001))
@pytest.mark.asyncio
async def test_attach_user_details_leaves_metadata_unchanged_when_a_later_chunk_fails():
mock_prisma = MagicMock()
mock_prisma.db.litellm_usertable.find_many = AsyncMock(
side_effect=[[SimpleNamespace(user_id="user-0", user_email="[email protected]", teams=[])], PrismaError()]
)
recovered = {f"key-{n}": {"key_alias": f"alias-{n}", "user_id": f"user-{n}"} for n in range(5_001)}
attached = await attach_user_details(mock_prisma, recovered)
assert mock_prisma.db.litellm_usertable.find_many.call_count == 2
assert attached == recovered
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
)
@pytest.mark.asyncio
async def test_reverse_hash_recovery_renders_a_postgres_select_span_for_the_table_it_read(
postgres_span_names: Callable[[], Awaitable[tuple[str, ...]]],
) -> None:
double_hashed = hash_token("a" * 64)
mock_prisma = MagicMock()
mock_prisma.db.query_raw = _query_raw_by_table(
active_rows=[_digest_row(double_hashed, "batch-worker", "team-1", "alice")],
deleted_rows=[],
)
await recover_double_hashed_key_metadata(mock_prisma, {double_hashed})
assert await postgres_span_names() == ("postgres.select LiteLLM_VerificationToken",)