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
fix(batch): track cost for managed batches with no attributable key/user/team
elinacse833670f7dbe3
diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.pyindex 22f9f40ecd8..0214c6cceb6 100644--- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py@@ -502,6 +502,7 @@ class CheckBatchCost:},"metadata": {"user_api_key_user_id": creator_user_id,+ "user_api_key_team_id": getattr(job, "team_id", None),**user_info,},},diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex 857429fa89f..2ff7808868d 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -34,11 +34,17 @@ from litellm.types.utils import ()from litellm.utils import get_end_user_id_for_cost_tracking-_PASS_THROUGH_CALL_TYPES: frozenset[str] = frozenset(+_UNATTRIBUTED_TRACKABLE_CALL_TYPES: frozenset[str] = frozenset({CallTypes.pass_through.value,CallTypes.llm_passthrough_route.value,CallTypes.allm_passthrough_route.value,+ # CheckBatchCost's synthetic logging_obj for a completed managed batch only ever+ # carries user_api_key_user_id (from LiteLLM_ManagedObjectTable.created_by) and+ # user_api_key_team_id (from .team_id) -- both are None for batches created with+ # the master key or a team-less key, since the table never stores the raw key+ # hash. The batch already incurred real provider cost, so track it regardless.+ CallTypes.aretrieve_batch.value,})@@ -434,6 +440,8 @@ def _should_track_cost_callback(the request with no key/user/team/end-user to attribute spend to. Thoserequests still forward real provider traffic that operators expect to seein request/usage logs, so they are tracked even when unauthenticated.+ The same reasoning applies to a completed managed batch's cost event+ (see _UNATTRIBUTED_TRACKABLE_CALL_TYPES)."""# don't run track cost callback if user opted into disabling spend@@ -442,7 +450,7 @@ def _should_track_cost_callback(if user_api_key is not None or user_id is not None or team_id is not None or end_user_id is not None:return True- return call_type in _PASS_THROUGH_CALL_TYPES+ return call_type in _UNATTRIBUTED_TRACKABLE_CALL_TYPESdef _get_budget_reservation_from_metadata(metadata: dict) -> dict | None:diff --git a/tests/proxy_unit_tests/test_check_batch_cost.py b/tests/proxy_unit_tests/test_check_batch_cost.pyindex a15abd023d8..42499f2ac55 100644--- a/tests/proxy_unit_tests/test_check_batch_cost.py+++ b/tests/proxy_unit_tests/test_check_batch_cost.py@@ -420,6 +420,134 @@ class TestCheckBatchCost:), "update() must include batch_processed=True when column is present"assert update_data["status"] == "complete"+ @pytest.mark.asyncio+ async def test_completed_batch_with_no_attributable_owner_still_writes_spend_log(+ self, check_batch_cost_instance, mock_prisma_client, mock_llm_router+ ):+ """Regression: a batch created with the master key or a team-less key has+ created_by=None and team_id=None on LiteLLM_ManagedObjectTable (the table+ never stores the raw key hash). CheckBatchCost's synthetic logging_obj for+ such a batch then carries no attributable key/user/team/end-user, and+ before the fix _should_track_cost_callback silently skipped the DB write+ with no error or warning: batch_processed still became True, but no+ LiteLLM_SpendLogs row was ever written.++ Unlike the other tests in this file, this one does NOT mock+ litellm_logging.Logging or async_success_handler -- it runs the real+ logging pipeline through to _ProxyDBLogger, which is the exact gap that+ let the original bug ship undetected.+ """+ import litellm+ from litellm.proxy.hooks.proxy_track_cost_callback import _ProxyDBLogger++ mock_prisma_client.db.litellm_managedobjecttable.update_many = AsyncMock(return_value=0)+ mock_prisma_client.db.litellm_managedobjecttable.update = AsyncMock()+ mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=None)++ mock_job = MagicMock()+ mock_job.id = "job-unattributed-1"+ mock_job.unified_object_id = "dW5pZmllZF9iYXRjaF9pZA=="+ mock_job.created_by = None+ mock_job.team_id = None++ mock_prisma_client.db.litellm_managedobjecttable.find_many = AsyncMock(return_value=[mock_job])++ # A real LiteLLMBatch (not a bare MagicMock): this test runs the real+ # litellm_logging.Logging pipeline, which type-checks the result via+ # isinstance(..., LiteLLMBatch) before it will compute/attach a cost.+ from litellm.types.utils import LiteLLMBatch++ mock_response = LiteLLMBatch(+ id="batch-1",+ completion_window="24h",+ created_at=1,+ endpoint="/v1/chat/completions",+ input_file_id="file-input-123",+ object="batch",+ status="completed",+ output_file_id="file-output-123",+ )++ mock_llm_router.aretrieve_batch = AsyncMock(return_value=mock_response)+ mock_llm_router.get_deployment_credentials_with_provider = MagicMock(return_value={"api_key": "sk-test"})++ mock_deployment = MagicMock()+ mock_deployment.litellm_params.custom_llm_provider = "openai"+ mock_deployment.litellm_params.model = "gpt-4"+ mock_deployment.model_info.model_dump.return_value = {}+ mock_llm_router.get_deployment = MagicMock(return_value=mock_deployment)++ mock_file_content = MagicMock()+ mock_file_content.content = b'{"id":"req-1"}'++ decoded_id = "llm_model_id,model-123;llm_batch_id,batch-456;"++ db_logger = _ProxyDBLogger()+ mock_update_database = AsyncMock()++ # Unlike the other tests in this file, this one runs the real+ # litellm_logging.Logging pipeline, which calls+ # _is_base64_encoded_unified_file_id an extra time (checking result.id+ # after it's reset to job.unified_object_id). Key off the argument+ # instead of a fixed-length side_effect list so the exact call count+ # doesn't matter.+ def _fake_is_base64_encoded(file_id):+ return decoded_id if file_id == mock_job.unified_object_id else None++ with (+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils._is_base64_encoded_unified_file_id",+ side_effect=_fake_is_base64_encoded,+ ),+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils.get_model_id_from_unified_batch_id",+ return_value="model-123",+ ),+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils.get_batch_id_from_unified_batch_id",+ return_value="batch-456",+ ),+ patch(+ "litellm.files.main.afile_content",+ new_callable=AsyncMock,+ return_value=mock_file_content,+ ),+ patch(+ "litellm.batches.batch_utils._get_file_content_as_dictionary",+ return_value=[{"id": "req-1"}],+ ),+ patch(+ "litellm.batches.batch_utils.calculate_batch_cost_and_usage",+ new_callable=AsyncMock,+ return_value=(+ 0.01,+ {"prompt_tokens": 10, "completion_tokens": 5},+ ["gpt-4"],+ ),+ ),+ patch(+ "litellm.litellm_core_utils.get_llm_provider_logic.get_llm_provider",+ return_value=("gpt-4", "openai", None, None),+ ),+ patch.object(litellm, "_async_success_callback", [db_logger]),+ patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ MagicMock(+ db_spend_update_writer=MagicMock(update_database=mock_update_database),+ slack_alerting_instance=MagicMock(customer_spend_alert=AsyncMock()),+ ),+ ),+ patch("litellm.proxy.proxy_server.increment_spend_counters", AsyncMock()),+ patch("litellm.proxy.proxy_server.update_cache", AsyncMock()),+ ):+ await check_batch_cost_instance.check_batch_cost()++ mock_update_database.assert_awaited_once()+ assert mock_update_database.call_args.kwargs["response_cost"] == 0.01+ assert mock_prisma_client.db.litellm_managedobjecttable.update.call_count == 1, (+ "the job must still be marked processed once cost tracking succeeds"+ )+@pytest.mark.asyncioasync def test_cost_tracking_failure_leaves_job_unprocessed(self, check_batch_cost_instance, mock_prisma_client, mock_llm_routerdiff --git a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.pyindex f289148101a..69f04ce2bbe 100644--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py@@ -1186,6 +1186,7 @@ async def test_track_cost_callback_enriches_user_id_for_mcp_style_metadata():("pass_through_endpoint", True),("llm_passthrough_route", True),("allm_passthrough_route", True),+ ("aretrieve_batch", True),("acompletion", False),("call_mcp_tool", False),(None, False),@@ -1194,7 +1195,14 @@ async def test_track_cost_callback_enriches_user_id_for_mcp_style_metadata():def test_should_track_cost_callback_pass_through_without_owner(call_type, expected):"""Regression for LIT-3782: unauthenticated pass-through requests (auth=false)carry no key/user/team/end-user, yet must still be tracked so they land in- LiteLLM_SpendLogs. Other call types with no owner stay untracked."""+ LiteLLM_SpendLogs. Other call types with no owner stay untracked.++ aretrieve_batch is included for the same reason: CheckBatchCost's synthetic+ logging_obj for a completed managed batch only ever carries+ user_api_key_user_id/user_api_key_team_id from LiteLLM_ManagedObjectTable,+ both of which are None for a batch created with the master key or a+ team-less key (the table never stores the raw key hash). Before this fix,+ such a batch's cost silently never reached LiteLLM_SpendLogs."""assert (_should_track_cost_callback(user_api_key=None,@@ -1211,6 +1219,7 @@ def test_should_track_cost_callback_pass_through_without_owner(call_type, expect"call_type, expect_spend_log",[("pass_through_endpoint", True),+ ("aretrieve_batch", True),("acompletion", False),(None, False),],@@ -1223,7 +1232,11 @@ async def test_track_cost_callback_logs_unauthenticated_pass_through_request(cost callback with no key/user/team/end-user. Before the fix the spend-logwrite was skipped and the request never appeared in request/usage logs. Itmust now be written for pass-through call types while other unauthenticated- calls remain skipped."""+ calls remain skipped.++ aretrieve_batch is included because CheckBatchCost's completed-batch cost+ event reaches this same callback with no attributable key/user/team when+ the batch was created with the master key or a team-less key."""logger = _ProxyDBLogger()kwargs = {