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(batches): account a managed batch's cost exactly once
Marty Sullivan5649098e1b47
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex e442cefa360..d5bc4ac0116 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -24,6 +24,7 @@ from litellm.proxy.common_utils.openai_endpoint_utils import (from litellm.proxy.openai_files_endpoints.common_utils import (_is_base64_encoded_unified_file_id,apply_team_provider_credentials,+ batch_cost_poller_is_active,decode_model_from_file_id,encode_batch_response_ids,encode_file_id_with_model,@@ -496,6 +497,12 @@ async def retrieve_batch("Batch %s is in non-terminal state %s, syncing with provider", batch_id, response.status)+ if unified_batch_id and batch_cost_poller_is_active():+ data["litellm_metadata"] = {+ **(data.get("litellm_metadata") or {}),+ "batch_ignore_default_logging": True,+ }+# Retrieve from provider (for non-terminal states or if DB lookup failed)# SCENARIO 1: Batch ID is encoded with model infoif model_from_id is not None:diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.pyindex 56e986c89cf..b8c250e718b 100644--- a/litellm/proxy/openai_files_endpoints/common_utils.py+++ b/litellm/proxy/openai_files_endpoints/common_utils.py@@ -1231,6 +1231,29 @@ async def get_batch_from_database(return None, None+def batch_cost_poller_is_active() -> bool:+ """+ Whether the CheckBatchCost poller is running and will therefore account for a+ managed batch's cost itself.++ False whenever the poller cannot be relied on: polling disabled by config, or the+ job absent from the scheduler because the enterprise import failed.+ """+ from litellm.constants import PROXY_BATCH_POLLING_ENABLED++ if not PROXY_BATCH_POLLING_ENABLED:+ return False+ try:+ import litellm.proxy.proxy_server as proxy_server_module++ scheduler = getattr(proxy_server_module, "scheduler", None)+ if scheduler is None:+ return False+ return scheduler.get_job("check_batch_cost_job") is not None+ except Exception: # noqa: BLE001 # scheduler backends raise varied types from get_job; an unreadable scheduler means the poller cannot be relied on+ return False++async def update_batch_in_database(batch_id: str,unified_batch_id: str | Literal[False],@@ -1304,15 +1327,7 @@ async def update_batch_in_database("updated_at": litellm.utils.get_utc_datetime(),}- # When a batch reaches completion, also mark batch_processed=True.- # The cost callback is enqueued asynchronously during the- # aretrieve_batch call that detected completion (via the @client- # decorator). It is not awaited, so there is a theoretical window- # where the callback hasn't executed yet. In practice the callback- # completes reliably. Setting the flag here unblocks file deletion- # which queries batch_processed=False. CheckBatchCost acts as a- # safety net for the rare case where the callback fails.- if db_status == "complete":+ if db_status == "complete" and not batch_cost_poller_is_active():update_data["batch_processed"] = Truetry:diff --git a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.pyindex a80c19f0708..6d00e56030f 100644--- a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py@@ -2406,3 +2406,47 @@ async def test_cancel__unified_batch_id_allowed_when_managed_files_required(cancawait call_cancel(cancel_harness, _unified_batch_id())assert cancel_harness.router_acancel.call_count == 1+++# =========================================================================== #+# Retrieve - who accounts for a managed batch's cost. Retrieving a batch and+# the CheckBatchCost poller both computed it, so whichever observed completion+# first won and the other either double counted or was locked out.+# =========================================================================== #+++async def test_retrieve__managed_batch_defers_cost_to_the_poller_when_it_is_running(retrieve_harness):+ """With the poller running it is the single accountant, so the retrieve must not also+ record cost. Without this the same batch is billed once per retrieve, and a caller+ polling its own batch inflates spend by however many times it looked."""+ with patch.object(endpoints, "batch_cost_poller_is_active", MagicMock(return_value=True)):+ await call_retrieve(retrieve_harness, _unified_batch_id())++ assert retrieve_harness.router.aretrieve_batch.await_count == 1+ metadata = retrieve_harness.router.aretrieve_batch.await_args.kwargs.get("litellm_metadata") or {}+ assert metadata.get("batch_ignore_default_logging") is True+++async def test_retrieve__managed_batch_still_accounts_inline_without_a_poller(retrieve_harness):+ """No poller means nothing else will ever account for this batch, so the retrieve has+ to keep doing it. Suppressing here unconditionally would lose batch cost entirely on+ any proxy running with batch polling disabled."""+ with patch.object(endpoints, "batch_cost_poller_is_active", MagicMock(return_value=False)):+ await call_retrieve(retrieve_harness, _unified_batch_id())++ assert retrieve_harness.router.aretrieve_batch.await_count == 1+ metadata = retrieve_harness.router.aretrieve_batch.await_args.kwargs.get("litellm_metadata") or {}+ assert metadata.get("batch_ignore_default_logging") is None+++async def test_retrieve__raw_batch_id_is_untouched_by_the_poller_handoff(retrieve_harness):+ """An unmanaged batch has no managed object row and so no poller queue entry. It must+ keep accounting inline whatever the poller is doing."""+ with patch.object(endpoints, "batch_cost_poller_is_active", MagicMock(return_value=True)):+ await call_retrieve(retrieve_harness, "batch-raw-xyz")++ metadata = retrieve_harness.litellm_aretrieve.await_args.kwargs.get("litellm_metadata") or {}+ assert metadata.get("batch_ignore_default_logging") is Nonediff --git a/tests/test_litellm/proxy/openai_files_endpoint/test_files_common_utils.py b/tests/test_litellm/proxy/openai_files_endpoint/test_files_common_utils.pyindex 4a021627c3e..4268d9c5e3e 100644--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_common_utils.py+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_common_utils.py@@ -95,3 +95,114 @@ def test_apply_unified_file_ids_swaps_all_three_ids():"unified-out","unified-err",)+++class _FakeScheduler:+ def __init__(self, job):+ self._job = job++ def get_job(self, job_id):+ assert job_id == "check_batch_cost_job"+ return self._job+++ "polling_enabled, job, expected",+ [+ (True, object(), True),+ (True, None, False),+ (False, object(), False),+ ],+ ids=["poller-running", "job-absent-enterprise-import-failed", "polling-disabled-by-config"],+)+def test_batch_cost_poller_is_active(monkeypatch, polling_enabled, job, expected):+ """The predicate must only claim the poller when it can actually be relied on, so a+ proxy with polling switched off or without the enterprise job keeps accounting for+ batch cost on the retrieve path."""+ import litellm.constants+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy.openai_files_endpoints.common_utils import (+ batch_cost_poller_is_active,+ )++ monkeypatch.setattr(litellm.constants, "PROXY_BATCH_POLLING_ENABLED", polling_enabled, raising=False)+ monkeypatch.setattr(proxy_server_module, "scheduler", _FakeScheduler(job), raising=False)++ assert batch_cost_poller_is_active() is expected+++def test_batch_cost_poller_is_active_is_false_when_no_scheduler_exists(monkeypatch):+ import litellm.constants+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy.openai_files_endpoints.common_utils import (+ batch_cost_poller_is_active,+ )++ monkeypatch.setattr(litellm.constants, "PROXY_BATCH_POLLING_ENABLED", True, raising=False)+ monkeypatch.setattr(proxy_server_module, "scheduler", None, raising=False)++ assert batch_cost_poller_is_active() is False+++def _completed_batch() -> LiteLLMBatch:+ return LiteLLMBatch(+ id="batch-done",+ completion_window="24h",+ created_at=1234567890,+ endpoint="/v1/chat/completions",+ input_file_id="file-in",+ object="batch",+ status="completed",+ output_file_id="file-out",+ )+++async def _run_update(monkeypatch, poller_active: bool) -> dict:+ import litellm.proxy.openai_files_endpoints.common_utils as cu++ monkeypatch.setattr(cu, "batch_cost_poller_is_active", lambda: poller_active)+ monkeypatch.setattr(cu, "ensure_batch_response_managed_file_ids", AsyncMock())++ prisma_client = MagicMock()+ update_mock = AsyncMock()+ prisma_client.db.litellm_managedobjecttable.update = update_mock++ db_batch_object = MagicMock()+ db_batch_object.status = "in_progress"++ await cu.update_batch_in_database(+ batch_id="unified-batch-id",+ unified_batch_id="unified-batch-id",+ response=_completed_batch(),+ managed_files_obj=MagicMock(),+ prisma_client=prisma_client,+ verbose_proxy_logger=MagicMock(),+ db_batch_object=db_batch_object,+ operation="retrieve",+ )++ assert update_mock.await_count == 1+ return update_mock.await_args.kwargs["data"]+++async def test_retrieving_a_completed_batch_leaves_batch_processed_to_the_cost_poller(monkeypatch):+ """batch_processed is what removes a batch from CheckBatchCost's queue, which selects+ batch_processed=False. Retrieving a batch records no cost when the poller is active, so+ setting the flag here retired the poller on behalf of work nobody had done: a cost+ callback that then failed lost the batch's cost permanently with no retry left. The+ status update must still happen so callers see the terminal state."""+ data = await _run_update(monkeypatch, poller_active=True)++ assert "batch_processed" not in data+ assert data["status"] == "complete"+++async def test_retrieving_a_completed_batch_still_marks_processed_without_a_cost_poller(monkeypatch):+ """With no poller to hand off to, this path is the only accountant, so it keeps setting+ the flag. Otherwise a proxy with polling disabled would never unblock file deletion."""+ data = await _run_update(monkeypatch, poller_active=False)++ assert data["batch_processed"] is True+ assert data["status"] == "complete"