Skip to content

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

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

mateo-berri7e51fbc8193c
diff --cc tests/proxy_unit_tests/test_check_batch_cost.py
index 59dfb67c486,9a6ab08e9b6..9ce91a8aee4
--- a/tests/proxy_unit_tests/test_check_batch_cost.py
+++ b/tests/proxy_unit_tests/test_check_batch_cost.py
@@@ -2553,85 -2554,48 +2554,127 @@@ class TestBatchCostAttribution
assert metadata["user_api_key_alias"] == "prod-key"
+ @pytest.mark.asyncio
+ async def test_org_id_snapshotted_on_the_row_wins(self):
+ """The org_id column captures the creating key's organization at submission time,
+ like team_id, so a key later moved to another org still bills the original one."""
+ from types import SimpleNamespace
+
+ instance = self._instance(
+ key_row=SimpleNamespace(key_alias="prod-key", org_id="org-moved-to"),
+ team_row=SimpleNamespace(team_alias="Team Alpha", organization_id="org-team"),
+ )
+
+ metadata = await instance._build_creator_attribution_metadata(
+ self._job(org_id="org-at-creation"), "batch-1"
+ )
+
+ assert metadata["user_api_key_org_id"] == "org-at-creation"
+
+ @pytest.mark.asyncio
+ async def test_org_id_comes_from_the_creating_key(self):
+ """The spend update writer increments organization spend from user_api_key_org_id.
+ A legacy row without the org_id column falls back to the creating key's org."""
+ from types import SimpleNamespace
+
+ instance = self._instance(
+ key_row=SimpleNamespace(key_alias="prod-key", org_id="org-42"),
+ team_row=SimpleNamespace(team_alias="Team Alpha", organization_id="org-team"),
+ )
+
+ metadata = await instance._build_creator_attribution_metadata(self._job(), "batch-1")
+
+ assert metadata["user_api_key_org_id"] == "org-42"
+
+ @pytest.mark.asyncio
+ async def test_org_id_falls_back_to_the_team_organization(self):
+ """A key with no org of its own still books batch spend against its team's
+ organization, matching how the request path resolves org attribution."""
+ from types import SimpleNamespace
+
+ instance = self._instance(
+ key_row=SimpleNamespace(key_alias="prod-key", org_id=None),
+ team_row=SimpleNamespace(team_alias="Team Alpha", organization_id="org-team"),
+ )
+
+ metadata = await instance._build_creator_attribution_metadata(self._job(), "batch-1")
+
+ assert metadata["user_api_key_org_id"] == "org-team"
+
+ @pytest.mark.asyncio
+ async def test_key_lookup_failure_still_bills_the_team_org(self):
+ """A key-table error while resolving a legacy row's org must not drop the team's
+ organization: the two lookups fail independently, so org spend still lands."""
+ from types import SimpleNamespace
+
+ instance = self._instance(
+ team_row=SimpleNamespace(team_alias="Team Alpha", organization_id="org-team"),
+ )
+ instance.prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ side_effect=Exception("db down")
+ )
+
+ metadata = await instance._build_creator_attribution_metadata(self._job(), "batch-1")
+
+ assert metadata["user_api_key_org_id"] == "org-team"
+
+ @pytest.mark.asyncio
+ async def test_no_org_leaves_the_key_unset(self):
+ """Without any org the key is absent entirely, so the spend writer's org update
+ stays skipped instead of matching an empty-string organization."""
+ from types import SimpleNamespace
+
+ instance = self._instance(
+ key_row=SimpleNamespace(key_alias="prod-key", org_id=None),
+ team_row=SimpleNamespace(team_alias="Team Alpha", organization_id=None),
+ )
+
+ metadata = await instance._build_creator_attribution_metadata(self._job(), "batch-1")
+
+ assert "user_api_key_org_id" not in metadata
+
+ @pytest.mark.asyncio
+ async def test_metadata_provenance_keeps_spend_log_api_key_joinable(self):
+ """
+ CheckBatchCost stores the VerificationToken hash on the managed object. The
+ spend-log writer must receive matching user_api_key_hash provenance so it
+ does not re-hash that value; otherwise DailyUserSpend.api_key no longer joins
+ VerificationToken and Usage shows key-hash-... with a null alias/email.
+ """
+ from datetime import datetime, timezone
+ from types import SimpleNamespace
+
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+ from litellm.proxy.utils import hash_token
+
+ token_hash = hash_token("sk-batch-creator-key")
+ instance = self._instance(
+ key_row=SimpleNamespace(key_alias="prod-key"),
+ user_row=SimpleNamespace(user_email="[email protected]", user_alias=None),
+ )
+ metadata = await instance._build_creator_attribution_metadata(
+ self._job(api_key=token_hash), "batch-1"
+ )
+
+ assert metadata["user_api_key"] == token_hash
+ assert metadata["user_api_key_hash"] == token_hash
+
+ payload = get_logging_payload(
+ kwargs={
+ "model": "gpt-4o",
+ "call_type": "aretrieve_batch",
+ "litellm_params": {"metadata": metadata},
+ },
+ response_obj={
+ "id": "batch_123",
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ start_time=datetime.now(timezone.utc),
+ end_time=datetime.now(timezone.utc),
+ )
+ assert payload["api_key"] == token_hash
+ assert payload["api_key"] != hash_token(token_hash)
+
class TestPollPageStarvation:
"""LIT-5462 regression: a row that can never be costed used to keep its slot in the