Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(spend): only reverse-hash export rows whose key alias join missed

Cursor Agent048499cdf559
diff --git a/litellm/proxy/spend_tracking/key_metadata_recovery.py b/litellm/proxy/spend_tracking/key_metadata_recovery.py
index 2940c9a8337..7de18521edd 100644
--- a/litellm/proxy/spend_tracking/key_metadata_recovery.py
+++ b/litellm/proxy/spend_tracking/key_metadata_recovery.py
@@ -211,9 +211,7 @@ async def fill_missing_api_key_aliases(
key
for row in rows
for key in (row.get(api_key_field),)
- if isinstance(key, str)
- and key
- and (row.get(alias_field) in (None, "") or row.get(user_email_field) in (None, ""))
+ if isinstance(key, str) and key and row.get(alias_field) in (None, "")
)
if not missing_keys:
return tuple(rows)
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 d76d355ec0e..7a80319239d 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
@@ -199,3 +199,22 @@ async def test_fill_missing_api_key_aliases_keeps_spend_user_email_when_alias_is
assert filled[0]["api_key_alias"] == "team-key"
assert filled[0]["team_id"] == "team-9"
assert filled[0]["user_email"] == "[email protected]"
+
+
+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()