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(litellm_internal_staging): reconcile batch observability with per-line resilience

mubashir1osmani65af77c43bd7
diff --cc enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py
index 95eb384360e,76e92538aaa..071e18abfe4
--- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py
+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py
@@@ -741,14 -790,23 +788,25 @@@ class CheckBatchCost
optional_params={},
)
- await logging_obj.async_success_handler(
- result=response,
- batch_cost=batch_result.cost,
- batch_usage=batch_result.usage,
- batch_models=batch_result.models,
- batch_successful_requests=batch_result.successful_requests,
- batch_failed_requests=batch_result.failed_requests,
- )
+ if not await self._claim_job_for_costing(job):
+ verbose_proxy_logger.info(
+ f"CheckBatchCost: batch {batch_id} (job {job.id}) was claimed by another pod "
+ "in this window, so its cost is already being tracked there"
+ )
+ return None
+
+ try:
+ await logging_obj.async_success_handler(
+ result=response,
- batch_cost=batch_cost,
- batch_usage=batch_usage,
- batch_models=batch_models,
++ batch_cost=batch_result.cost,
++ batch_usage=batch_result.usage,
++ batch_models=batch_result.models,
++ batch_successful_requests=batch_result.successful_requests,
++ batch_failed_requests=batch_result.failed_requests,
+ )
+ except Exception:
+ await self._release_job_claim(job)
+ raise
# Record batch duration (completed_at - created_at)
if prom_logger and response.completed_at and response.created_at:
diff --cc litellm/batches/batch_utils.py
index 4e62c4a0130,6eb13d2cba7..7320b90c801
--- a/litellm/batches/batch_utils.py
+++ b/litellm/batches/batch_utils.py
@@@ -1,7 -1,6 +1,8 @@@
import json
- from collections.abc import Iterable, Iterator
+ from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
+from dataclasses import replace as dataclasses_replace
++from enum import Enum
from typing import Any, Final, Literal
import litellm
@@@ -83,43 -72,28 +84,50 @@@ async def _handle_completed_batch
# The generic retrieval helper keeps raising for callers that explicitly ask
# for a missing output file.
if batch.output_file_id is None:
- return 0.0, Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0), []
+ return BatchCostUsageResult(
+ cost=0.0,
+ usage=Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
+ models=[], # mutable-ok: no output file means no model was ever priced; BatchCostUsageResult.models requires list[str]
+ successful_requests=0,
+ failed_requests=await _count_error_file_failed_requests(
+ batch, custom_llm_provider=custom_llm_provider, litellm_params=litellm_params
+ ),
+ )
file_content = await _fetch_batch_output_file_content(batch, custom_llm_provider, litellm_params=litellm_params)
+ error_file_failed_requests: Final = await _count_error_file_failed_requests(
+ batch, custom_llm_provider=custom_llm_provider, litellm_params=litellm_params
+ )
- if (
- custom_llm_provider == "vertex_ai"
- and model_name
- and getattr(litellm, "disable_vertex_batch_output_transformation", False)
- ):
- batch_cost, batch_usage = calculate_vertex_ai_batch_cost_and_usage(
- _get_file_content_as_dictionary(file_content), model_name
+ output_file_result: Final = (
+ calculate_vertex_ai_batch_cost_and_usage(_get_file_content_as_dictionary(file_content), model_name)
+ if (
+ custom_llm_provider == "vertex_ai"
+ and model_name
+ and getattr(litellm, "disable_vertex_batch_output_transformation", False)
+ )
+ else _aggregate_batch_cost_usage_models(
- entries=_iter_batch_input_entries(file_content),
++ entries=_iter_batch_output_entries(file_content),
+ custom_llm_provider=custom_llm_provider,
+ model_name=model_name,
+ model_info=model_info,
)
- return batch_cost, batch_usage, [model_name]
+ )
- return _aggregate_batch_cost_usage_models(
- entries=_iter_batch_output_entries(file_content),
- custom_llm_provider=custom_llm_provider,
- model_name=model_name,
- model_info=model_info,
+ if not error_file_failed_requests:
+ return output_file_result
+ return dataclasses_replace(
+ output_file_result, failed_requests=output_file_result.failed_requests + error_file_failed_requests
)
++class _LineOutcome(Enum):
++ """A batch output line that yielded no billable stats."""
++
++ PROVIDER_FAILED = "provider_failed"
++ UNCOSTABLE = "uncostable"
++
++
@dataclass(frozen=True, slots=True)
class _BatchOutputLineStats:
cost: float
@@@ -137,50 -110,92 +145,99 @@@ def _classify_output_line_stats
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "bedrock"],
model_name: str | None,
model_info: ModelInfo | None,
- ) -> Iterator[_BatchOutputLineStats | None]:
- """Classify every output line in a single pass: yields stats for a
- successful line, ``None`` for a failed one (per ``_batch_response_was_successful``).
- Counting failures this way avoids a second pass over a potentially huge output file."""
- from litellm.cost_calculator import batch_cost_calculator
-
-) -> Iterator[_BatchOutputLineStats]:
++) -> Iterator[_BatchOutputLineStats | _LineOutcome]:
++ """Classify every output line in a single pass, so counting failures never needs
++ a second read of a potentially huge output file. A line the provider reported as
++ failed yields ``PROVIDER_FAILED``; a successful line litellm could not price
++ yields ``UNCOSTABLE`` and still counts as a successful request billed at $0, so
++ the counts stay reconcilable with the provider's own ``request_counts``."""
for entry in entries:
+ if not _batch_response_was_successful(entry, custom_llm_provider):
- yield None
++ yield _LineOutcome.PROVIDER_FAILED
+ continue
- response_body = _get_response_from_batch_job_output_file(entry, custom_llm_provider)
- usage = _get_batch_job_usage_from_response_body(response_body, custom_llm_provider)
- prompt_details = parse_prompt_tokens_details(usage)
- raw_model = response_body.get("model")
- response_model = raw_model if isinstance(raw_model, str) and raw_model else None
- if model_info is not None or custom_llm_provider in ("anthropic", "bedrock"):
- if custom_llm_provider == "bedrock" and model_name:
- cost_model = model_name
- else:
- cost_model = response_model or model_name or ""
- prompt_cost, completion_cost = batch_cost_calculator(
- usage=usage,
- model=cost_model,
- custom_llm_provider=custom_llm_provider,
- model_info=model_info,
- )
- line_cost = prompt_cost + completion_cost
- else:
- line_cost = litellm.completion_cost(
- completion_response=response_body,
- custom_llm_provider=custom_llm_provider,
- call_type=CallTypes.aretrieve_batch.value,
- )
- reasoning_tokens = usage.completion_tokens_details.reasoning_tokens if usage.completion_tokens_details else None
- yield _BatchOutputLineStats(
- cost=line_cost,
- prompt_tokens=usage.prompt_tokens,
- completion_tokens=usage.completion_tokens,
- total_tokens=usage.total_tokens,
- cache_read_tokens=prompt_details["cache_hit_tokens"],
- cache_creation_tokens=prompt_details["cache_creation_tokens"],
- reasoning_tokens=reasoning_tokens or 0,
- model=response_model,
+ stats = _safe_output_line_stats(entry, custom_llm_provider, model_name, model_info)
- if stats is not None:
- yield stats
++ yield stats if stats is not None else _LineOutcome.UNCOSTABLE
+
+
+ def _safe_output_line_stats(
+ entry: Mapping[str, Any],
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "bedrock"],
+ model_name: str | None,
+ model_info: ModelInfo | None,
+ ) -> _BatchOutputLineStats | None:
- """Return the stats for one batch output line, or None for a line that is
- unsuccessful or cannot be costed, so a single bad line never aborts the
- whole batch's cost accounting."""
++ """Return the stats for one provider-successful batch output line, or None when
++ it cannot be costed, so a single bad line never aborts the whole batch's cost
++ accounting."""
+ custom_id: Final = entry.get("custom_id") if isinstance(entry, dict) else None
+ try:
- if not _batch_response_was_successful(entry, custom_llm_provider):
- return None
+ return _compute_output_line_stats(entry, custom_llm_provider, model_name, model_info)
+ except Exception as e: # noqa: BLE001 # any single line's costing failure must not abort the whole batch
+ verbose_logger.warning(
+ "batch output line could not be costed, so it is billed at $0 and the rest of the batch "
+ "is still billed. custom_id=%s error=%s",
+ custom_id,
+ str(e),
)
+ return None
+
+
+ def _compute_output_line_stats(
+ entry: Mapping[str, Any],
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "bedrock"],
+ model_name: str | None,
+ model_info: ModelInfo | None,
+ ) -> _BatchOutputLineStats:
+ response_body: Final = _get_response_from_batch_job_output_file(entry, custom_llm_provider)
+ usage: Final = _get_batch_job_usage_from_response_body(response_body, custom_llm_provider)
+ prompt_details: Final = parse_prompt_tokens_details(usage)
+ raw_model: Final = response_body.get("model")
+ response_model: Final = raw_model if isinstance(raw_model, str) and raw_model else None
++ completion_details: Final = usage.completion_tokens_details
+ return _BatchOutputLineStats(
+ cost=_output_line_cost(
+ response_body=response_body,
+ usage=usage,
+ custom_llm_provider=custom_llm_provider,
+ model_name=model_name,
+ response_model=response_model,
+ model_info=model_info,
+ ),
+ prompt_tokens=usage.prompt_tokens,
+ completion_tokens=usage.completion_tokens,
+ total_tokens=usage.total_tokens,
+ cache_read_tokens=prompt_details["cache_hit_tokens"],
+ cache_creation_tokens=prompt_details["cache_creation_tokens"],
++ reasoning_tokens=(completion_details.reasoning_tokens if completion_details else None) or 0,
+ model=response_model,
+ )
+
+
+ def _output_line_cost(
+ response_body: Mapping[str, Any],
+ usage: Usage,
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "bedrock"],
+ model_name: str | None,
+ response_model: str | None,
+ model_info: ModelInfo | None,
+ ) -> float:
+ from litellm.cost_calculator import batch_cost_calculator
+
+ if model_info is None and custom_llm_provider not in ("anthropic", "bedrock"):
+ return litellm.completion_cost(
+ completion_response=response_body,
+ custom_llm_provider=custom_llm_provider,
+ call_type=CallTypes.aretrieve_batch.value,
+ )
+ cost_model: Final = (
+ model_name if custom_llm_provider == "bedrock" and model_name else response_model or model_name or ""
+ )
+ prompt_cost, completion_cost = batch_cost_calculator(
+ usage=usage,
+ model=cost_model,
+ custom_llm_provider=custom_llm_provider,
+ model_info=model_info,
+ )
+ return prompt_cost + completion_cost
def _aggregate_batch_cost_usage_models(
@@@ -188,14 -203,10 +245,14 @@@
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "bedrock"],
model_name: str | None = None,
model_info: ModelInfo | None = None,
-) -> tuple[float, Usage, list[str]]:
- """Aggregate cost, usage, and models from batch output entries in a single
- pass, holding one small stats record per line instead of the parsed file."""
- line_stats: Final = tuple(_iter_successful_output_line_stats(entries, custom_llm_provider, model_name, model_info))
+) -> BatchCostUsageResult:
+ """Aggregate cost, usage, models, and pass/fail counts from batch output
+ entries in a single pass, holding one small stats record per line instead
+ of the parsed file."""
+ all_results: Final = tuple(_classify_output_line_stats(entries, custom_llm_provider, model_name, model_info))
- line_stats: Final = tuple(stats for stats in all_results if stats is not None)
- successful_requests: Final = len(line_stats)
- failed_requests: Final = len(all_results) - successful_requests
++ line_stats: Final = tuple(result for result in all_results if isinstance(result, _BatchOutputLineStats))
++ failed_requests: Final = sum(1 for result in all_results if result is _LineOutcome.PROVIDER_FAILED)
++ successful_requests: Final = len(all_results) - failed_requests
cache_token_params: Final = {
key: tokens
@@@ -315,8 -296,34 +372,34 @@@ def calculate_vertex_ai_batch_cost_and_
)
+ def _provider_output_file_id(output_file_id: str) -> str:
+ """
+ Resolve the file id the provider actually knows: unified ids yield their embedded
+ llm_output_file_id, model-encoded ids decode to the raw provider id, raw ids pass through.
+ """
+ from litellm.proxy.openai_files_endpoints.common_utils import (
+ _is_base64_encoded_unified_file_id,
+ get_original_file_id,
+ )
+
+ unified_file_id: Final = _is_base64_encoded_unified_file_id(output_file_id)
+ if not unified_file_id:
+ return get_original_file_id(output_file_id)
+ try:
+ extracted: Final = unified_file_id.split("llm_output_file_id,")[1].split(";")[0]
+ except (IndexError, AttributeError) as e:
+ verbose_logger.error(
+ "Failed to extract LLM output file ID from unified file ID: %s, error: %s",
+ output_file_id,
+ e,
+ )
+ return output_file_id
+ verbose_logger.debug("Extracted LLM output file ID from unified file ID: %s", extracted)
+ return extracted
+
+
-async def _fetch_batch_output_file_content(
- batch: Batch,
+async def _fetch_batch_managed_file_content(
+ file_id: str,
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai",
litellm_params: dict | None = None,
) -> bytes:
@@@ -330,22 -337,15 +413,10 @@@
Required for Azure and other providers that need authentication
"""
from litellm.files.main import afile_content
- from litellm.proxy.openai_files_endpoints.common_utils import (
- _is_base64_encoded_unified_file_id,
- )
-
- resolved_file_id = file_id
- is_base64_unified_file_id: Final = _is_base64_encoded_unified_file_id(file_id)
- if is_base64_unified_file_id:
- try:
- resolved_file_id = is_base64_unified_file_id.split("llm_output_file_id,")[1].split(";")[0]
- verbose_logger.debug("Extracted LLM output file ID from unified file ID: %s", resolved_file_id)
- except (IndexError, AttributeError) as e:
- verbose_logger.error("Failed to extract LLM output file ID from unified file ID: %s, error: %s", file_id, e)
- if batch.output_file_id is None:
- raise ValueError("Output file id is None cannot retrieve file content")
-
- file_id: Final = _provider_output_file_id(batch.output_file_id)
-
# Build kwargs for afile_content with credentials from litellm_params
file_content_kwargs: Final = {
- "file_id": resolved_file_id,
- "file_id": file_id,
++ "file_id": _provider_output_file_id(file_id),
"custom_llm_provider": custom_llm_provider,
}
diff --cc litellm/proxy/spend_tracking/spend_tracking_utils.py
index f08236adab2,b6f695db512..27f9b7dcc2e
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@@ -127,13 -142,14 +146,16 @@@ def _get_spend_logs_metadata
# Filter the metadata dictionary to include only the specified keys
clean_metadata: Final = SpendLogsMetadata(**{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__})
- raw_user_api_key: Final = clean_metadata.get("user_api_key")
- if raw_user_api_key is not None and isinstance(raw_user_api_key, str):
- clean_metadata["user_api_key"] = _hash_api_key_for_spend_log(raw_user_api_key)
+ _raw_key: Final = clean_metadata.get("user_api_key")
+ _trusted_hash: Final = metadata.get("user_api_key_hash")
+ _already_redacted: Final = (
+ isinstance(_trusted_hash, str) and _is_non_secret_key_value(_trusted_hash) and _trusted_hash == _raw_key
+ )
+ clean_metadata["user_api_key"] = _redact_logged_api_key(_raw_key, already_redacted=_already_redacted)
clean_metadata["applied_guardrails"] = applied_guardrails
clean_metadata["batch_models"] = batch_models
+ clean_metadata["batch_successful_requests"] = batch_successful_requests
+ clean_metadata["batch_failed_requests"] = batch_failed_requests
clean_metadata["mcp_tool_call_metadata"] = mcp_tool_call_metadata
clean_metadata["vector_store_request_metadata"] = _get_vector_store_request_for_spend_logs_payload(
vector_store_request_metadata
diff --cc tests/proxy_unit_tests/test_check_batch_cost.py
index 39e6c9d3e50,a1864c5e480..1c77933c701
--- a/tests/proxy_unit_tests/test_check_batch_cost.py
+++ b/tests/proxy_unit_tests/test_check_batch_cost.py
@@@ -6,37 -6,19 +6,43 @@@ Vertex (raw gs:// input_file_id) and Be
ARN unified_object_id) batches with no managed unified id.
"""
+ import asyncio
+ import json
+ from contextlib import contextmanager
+from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+ from fastapi import HTTPException
+if TYPE_CHECKING:
+ from litellm.batches.batch_utils import BatchCostUsageResult
+
_IS_B64 = "litellm.proxy.openai_files_endpoints.common_utils._is_base64_encoded_unified_file_id"
+ _CLAIM_UNIFIED_BATCH_ID = "dW5pZmllZF9iYXRjaF9pZA=="
+ _CLAIM_OUTPUT_FILE_ID = "file-output-123"
+def _batch_cost_result(
+ cost: float,
+ usage: dict,
+ models: list[str],
+ successful_requests: int = 1,
+ failed_requests: int = 0,
+) -> "BatchCostUsageResult":
+ """Build the BatchCostUsageResult calculate_batch_cost_and_usage now returns,
+ for mocking it in tests that only care about cost/usage/models."""
+ from litellm.batches.batch_utils import BatchCostUsageResult
+
+ return BatchCostUsageResult(
+ cost=cost,
+ usage=usage,
+ models=models,
+ successful_requests=successful_requests,
+ failed_requests=failed_requests,
+ )
+
+
def _unmanaged_vertex_file_object(
input_file_id="gs://bucket/litellm-vertex-files/publishers/google/models/gemini-2.5-flash/abc.jsonl",
status="validating",
@@@ -553,7 -535,7 +559,9 @@@ class TestCheckBatchCost
patch(
"litellm.batches.batch_utils.calculate_batch_cost_and_usage",
new_callable=AsyncMock,
-- return_value=(0.0052, {"prompt_tokens": 1400, "completion_tokens": 600}, ["claude-haiku-4-5"]),
++ return_value=_batch_cost_result(
++ 0.0052, {"prompt_tokens": 1400, "completion_tokens": 600}, ["claude-haiku-4-5"]
++ ),
) as mock_calculate,
patch(
"litellm.litellm_core_utils.get_llm_provider_logic.get_llm_provider",
@@@ -2601,3 -2652,353 +2678,353 @@@ class TestPollPageStarvation
await self._instance(prisma, llm_router).check_batch_cost()
prisma.db.litellm_managedobjecttable.update.assert_not_awaited()
+
+ class _FakeManagedObjectRow:
+ """One managed batch row the provider has finished but nothing has costed yet."""
+
+ def __init__(self):
+ self.id = "job-claim-1"
+ self.unified_object_id = _CLAIM_UNIFIED_BATCH_ID
+ self.model_object_id = "batch-456"
+ self.file_purpose = "batch"
+ self.status = "in_progress"
+ self.batch_processed = False
+ self.created_by = "user-1"
+ self.team_id = None
+ self.api_key = None
+ self.request_tags = None
+ self.created_at = 1700000000
+ self.file_object = json.dumps(
+ {"id": "batch-456", "status": "in_progress", "input_file_id": "file-input-1",
+ "output_file_id": _CLAIM_OUTPUT_FILE_ID}
+ )
+
+
+ class _FakeManagedObjectTable:
+ """A LiteLLM_ManagedObjectTable double backed by one real, mutable row.
+
+ It honours the batch_processed and status filters, so the poller's compare-and-swap
+ and the managed-files deletion guard both read the same state a shared Postgres row
+ would give them. Staleness sweeps (the only queries scoped by created_at) never match.
+ """
+
+ def __init__(self, row: _FakeManagedObjectRow, journal: list):
+ self.row = row
+ self.journal = journal
+ self.update_many = AsyncMock(side_effect=self._update_many)
+ self.update = AsyncMock(side_effect=self._update)
+ self.find_many = AsyncMock(side_effect=self._find_many)
+ self.find_first = AsyncMock(return_value=None)
+
+ def _matches(self, where: dict) -> bool:
+ for key, value in where.items():
+ if key == "created_at":
+ return False
+ if key == "status":
+ if self.row.status in value.get("not_in", []):
+ return False
+ if "in" in value and self.row.status not in value["in"]:
+ return False
+ elif getattr(self.row, key) != value:
+ return False
+ return True
+
+ async def _update_many(self, *, where: dict, data: dict) -> int:
+ if not self._matches(where):
+ return 0
+ if "batch_processed" in where:
+ self.journal.append("claim" if data.get("batch_processed") else "release")
+ for key, value in data.items():
+ setattr(self.row, key, value)
+ return 1
+
+ async def _update(self, *, where: dict, data: dict) -> None:
+ self.journal.append("finalize")
+ for key, value in data.items():
+ setattr(self.row, key, value)
+
+ async def _find_many(self, *, where: dict, take=None, order=None) -> list:
+ return [self.row] if self._matches(where) else []
+
+
+ class TestMultiPodBatchCostClaim:
+ """LIT-4827 regression: every pod and uvicorn worker schedules its own poller against
+ the shared LiteLLM_ManagedObjectTable, so a completed batch must be claimed atomically
+ before its cost is logged. Without the claim two pods select the same row in one window
+ and both write an aretrieve_batch spend log for it, double counting the spend.
+
+ The claim sits immediately before the spend-log write rather than before the results
+ fetch, because batch_processed is also what keeps an unbilled row selectable by later
+ poll cycles and what blocks deletion of the files the fetch reads."""
+
+ @staticmethod
+ def _instance(prisma, llm_router):
+ from litellm_enterprise.proxy.common_utils.check_batch_cost import CheckBatchCost
+
+ proxy_logging_obj = MagicMock()
+ proxy_logging_obj.get_proxy_hook.return_value = None
+ return CheckBatchCost(
+ proxy_logging_obj=proxy_logging_obj,
+ prisma_client=prisma,
+ llm_router=llm_router,
+ )
+
+ @staticmethod
+ def _prisma(row: _FakeManagedObjectRow, journal: list):
+ prisma = MagicMock()
+ prisma.db.litellm_managedobjecttable = _FakeManagedObjectTable(row, journal)
+ prisma.db.litellm_managedfiletable.find_many = AsyncMock(return_value=[])
+ prisma.db.litellm_managedfiletable.find_first = AsyncMock(return_value=None)
+ prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=None)
+ prisma.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
+ return prisma
+
+ @staticmethod
+ def _router():
+ response = MagicMock()
+ response.status = "completed"
+ response.output_file_id = _CLAIM_OUTPUT_FILE_ID
+ response.error_file_id = None
+ response.created_at = 1
+ response.completed_at = 2
+ response.model_dump_json.return_value = '{"id":"batch-456","status":"completed"}'
+
+ deployment = MagicMock()
+ deployment.litellm_params.custom_llm_provider = "openai"
+ deployment.litellm_params.model = "gpt-4"
+ deployment.model_info.model_dump.return_value = {}
+
+ router = MagicMock()
+ router.aretrieve_batch = AsyncMock(return_value=response)
+ router.get_deployment_credentials_with_provider = MagicMock(
+ return_value={"api_key": "sk-test"}
+ )
+ router.get_deployment = MagicMock(return_value=deployment)
+ return router
+
+ @staticmethod
+ @contextmanager
+ def _billing_patches(journal: list, during_fetch=None, bill_error=None):
+ """Patch the cost path a batch runs through, journalling the results fetch and the
+ spend-log write. during_fetch runs while the output file is being read, which is
+ the window an interrupted worker or a concurrent file deletion lands in."""
+ file_content = MagicMock()
+ file_content.content = b'{"id":"req-1"}'
+
+ async def _afile_content(**kwargs):
+ journal.append("fetch")
+ if during_fetch is not None:
+ await during_fetch()
+ return file_content
+
+ async def _bill(**kwargs):
+ journal.append("bill")
+ if bill_error is not None:
+ raise bill_error
+
+ def _is_b64(file_id):
+ if file_id == _CLAIM_UNIFIED_BATCH_ID:
+ return "llm_model_id,model-123;llm_batch_id,batch-456;"
+ return False
+
+ logging_obj = MagicMock()
+ logging_obj.async_success_handler = AsyncMock(side_effect=_bill)
+
+ with (
+ patch(_IS_B64, side_effect=_is_b64),
+ 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=AsyncMock(side_effect=_afile_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"]),
++ return_value=_batch_cost_result(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("litellm.litellm_core_utils.litellm_logging.Logging", return_value=logging_obj),
+ ):
+ yield logging_obj
+
+ @staticmethod
+ def _claim_calls(prisma) -> list:
+ return [
+ call.kwargs
+ for call in prisma.db.litellm_managedobjecttable.update_many.call_args_list
+ if "id" in call.kwargs["where"]
+ ]
+
+ @staticmethod
+ async def _run_deletion_guard(prisma, file_id: str) -> None:
+ """Run the real managed-files deletion guard against the row the poller is costing."""
+ from litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles
+
+ cache = MagicMock()
+ cache.async_get_cache = AsyncMock(return_value=None)
+ cache.async_set_cache = AsyncMock()
+ guard = _PROXY_LiteLLMManagedFiles(internal_usage_cache=cache, prisma_client=prisma)
+
+ scheduler = MagicMock()
+ scheduler.get_job.return_value = MagicMock()
+ with patch("litellm.proxy.proxy_server.scheduler", scheduler):
+ await guard._check_file_deletion_allowed(file_id)
+
+ @pytest.mark.asyncio
+ async def test_winning_pod_claims_the_row_between_fetching_and_billing(self):
+ """The claim flips batch_processed false -> true after the results are in hand and
+ before the spend log is written, so a concurrent pod's claim finds no matching row."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+
+ with self._billing_patches(journal) as logging_obj:
+ await self._instance(prisma, self._router()).check_batch_cost()
+
+ assert journal == ["fetch", "claim", "bill", "finalize"]
+ assert self._claim_calls(prisma) == [
+ {
+ "where": {"id": "job-claim-1", "batch_processed": False},
+ "data": {"batch_processed": True},
+ }
+ ]
+ logging_obj.async_success_handler.assert_awaited_once()
+ assert row.batch_processed is True
+
+ @pytest.mark.asyncio
+ async def test_a_pod_that_loses_the_claim_after_fetching_does_not_bill(self):
+ """Both pods select the row and fetch its results in the same window. The one whose
+ compare-and-swap finds the row already taken must not write a second spend log."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+
+ async def _other_pod_wins_the_row():
+ row.batch_processed = True
+
+ with self._billing_patches(journal, during_fetch=_other_pod_wins_the_row) as logging_obj:
+ await self._instance(prisma, self._router()).check_batch_cost()
+
+ assert journal == ["fetch"]
+ logging_obj.async_success_handler.assert_not_awaited()
+ assert self._claim_calls(prisma) == [
+ {
+ "where": {"id": "job-claim-1", "batch_processed": False},
+ "data": {"batch_processed": True},
+ }
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_failed_spend_log_write_releases_the_claim(self):
+ """A transient failure while billing a claimed batch must hand the row back, or its
+ spend is silently lost instead of being retried on the next cycle."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+
+ with self._billing_patches(journal, bill_error=Exception("spend log write failed")):
+ await self._instance(prisma, self._router()).check_batch_cost()
+
+ assert journal == ["fetch", "claim", "bill", "release"]
+ assert row.batch_processed is False
+ assert self._claim_calls(prisma)[-1] == {
+ "where": {"id": "job-claim-1", "batch_processed": True},
+ "data": {"batch_processed": False},
+ }
+
+ @pytest.mark.asyncio
+ async def test_a_worker_interrupted_mid_costing_leaves_the_batch_billable(self):
+ """A pod killed while reading a batch's results must leave the row for a later
+ cycle. Claiming before the fetch marked the batch processed for good, so the pod
+ that died took that batch's spend with it and no other pod ever selected it."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+ reached_fetch = asyncio.Event()
+
+ async def _never_returns():
+ reached_fetch.set()
+ await asyncio.Event().wait()
+
+ with self._billing_patches(journal, during_fetch=_never_returns) as logging_obj:
+ interrupted = asyncio.create_task(
+ self._instance(prisma, self._router()).check_batch_cost()
+ )
+ await asyncio.wait_for(reached_fetch.wait(), timeout=5)
+ assert row.batch_processed is False, "an in-flight costing must not mark the row processed"
+ interrupted.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await interrupted
+
+ assert journal == ["fetch"]
+ logging_obj.async_success_handler.assert_not_awaited()
+
+ survivor_journal = []
+ survivor_prisma = self._prisma(row, survivor_journal)
+ with self._billing_patches(survivor_journal) as survivor_logging:
+ await self._instance(survivor_prisma, self._router()).check_batch_cost()
+
+ assert survivor_journal == ["fetch", "claim", "bill", "finalize"]
+ survivor_logging.async_success_handler.assert_awaited_once()
+ assert row.batch_processed is True
+
+ @pytest.mark.asyncio
+ async def test_costing_in_flight_keeps_the_referenced_file_undeletable(self):
+ """The deletion guard only holds files whose batch still has batch_processed false,
+ so claiming the row before the fetch let a concurrent delete remove the very output
+ file the in-flight costing was about to read."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+ reached_fetch = asyncio.Event()
+ finish_fetch = asyncio.Event()
+
+ async def _wait_for_the_delete_attempt():
+ reached_fetch.set()
+ await finish_fetch.wait()
+
+ with self._billing_patches(journal, during_fetch=_wait_for_the_delete_attempt):
+ costing = asyncio.create_task(
+ self._instance(prisma, self._router()).check_batch_cost()
+ )
+ await asyncio.wait_for(reached_fetch.wait(), timeout=5)
+
+ with pytest.raises(HTTPException) as blocked:
+ await self._run_deletion_guard(prisma, _CLAIM_OUTPUT_FILE_ID)
+ assert blocked.value.status_code == 400
+ assert _CLAIM_OUTPUT_FILE_ID in blocked.value.detail
+
+ finish_fetch.set()
+ await asyncio.wait_for(costing, timeout=5)
+
+ assert journal == ["fetch", "claim", "bill", "finalize"]
+ assert row.batch_processed is True
+ await self._run_deletion_guard(prisma, _CLAIM_OUTPUT_FILE_ID)
+
+ @pytest.mark.asyncio
+ async def test_schema_without_batch_processed_still_bills(self):
+ """Older schemas have no column to claim, so they keep the pre-fix behavior instead
+ of losing every batch's cost."""
+ row = _FakeManagedObjectRow()
+ journal = []
+ prisma = self._prisma(row, journal)
+ instance = self._instance(prisma, self._router())
+ instance._has_batch_processed_column = False
+
+ with self._billing_patches(journal) as logging_obj:
+ await instance.check_batch_cost()
+
+ assert self._claim_calls(prisma) == []
+ assert journal == ["fetch", "bill", "finalize"]
+ logging_obj.async_success_handler.assert_awaited_once()
diff --cc tests/test_litellm/batches/test_batch_utils.py
index f7067053acb,41b4bb8cf76..1540a587349
--- a/tests/test_litellm/batches/test_batch_utils.py
+++ b/tests/test_litellm/batches/test_batch_utils.py
@@@ -522,14 -465,31 +522,39 @@@ def test_cost_from_content_completion_c
_success_row(usage=_usage(20, 10)),
]
- total, _, _ = bu._aggregate_batch_cost_usage_models(entries=rows, custom_llm_provider="openai")
+ result = bu._aggregate_batch_cost_usage_models(entries=rows, custom_llm_provider="openai")
- assert total == 1.0 # 2 successful * 0.5
+ assert result.cost == 1.0 # 2 successful * 0.5
assert len(calls) == 2 # failed row not costed
+ assert result.successful_requests == 2
+ assert result.failed_requests == 1
+ def test_empty_body_line_does_not_zero_whole_batch():
+ """A status-200 row with an empty body makes litellm.completion_cost raise;
- that line must be skipped instead of zeroing the whole batch."""
++ that line must be skipped from pricing instead of zeroing the whole batch.
++
++ The provider still reported it as a success, so it stays in
++ successful_requests and out of failed_requests - otherwise the counts stop
++ reconciling with the provider's own request_counts over a litellm-side
++ pricing gap the customer never caused."""
+ rows = [
+ _success_row(usage=_usage(10, 5)),
+ {
+ "custom_id": "request-poison-empty",
+ "response": {"status_code": 200, "request_id": "inject-empty-body", "body": {}},
+ },
+ _success_row(usage=_usage(20, 10)),
+ ]
+
- cost, usage, models = bu._aggregate_batch_cost_usage_models(entries=rows, custom_llm_provider="openai")
++ result = bu._aggregate_batch_cost_usage_models(entries=rows, custom_llm_provider="openai")
+
- assert cost > 0.0
- assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (30, 15, 45)
- assert models == ["gpt-4o", "gpt-4o"]
++ assert result.cost > 0.0
++ assert (result.usage.prompt_tokens, result.usage.completion_tokens, result.usage.total_tokens) == (30, 15, 45)
++ assert result.models == ["gpt-4o", "gpt-4o"]
++ assert (result.successful_requests, result.failed_requests) == (3, 0)
+
+
def test_cost_from_content_model_info_path(monkeypatch):
# model_info set -> batch_cost_calculator(prompt_cost, completion_cost).
import litellm.cost_calculator as cc
diff --cc tests/test_litellm/batches/test_responses_batch_cost.py
index 00000000000,7ce026bd103..b634f5f73db
mode 000000,100644..100644
--- a/tests/test_litellm/batches/test_responses_batch_cost.py
+++ b/tests/test_litellm/batches/test_responses_batch_cost.py
@@@ -1,0 -1,119 +1,119 @@@
+ """Token and spend reconciliation for /v1/responses batches.
+
+ Regression guard for https://github.com/BerriAI/litellm/issues/35363: a batch
+ output line built by the Responses API reports ``input_tokens`` /
+ ``output_tokens`` where a chat line reports ``prompt_tokens`` /
+ ``completion_tokens``. The usage object was constructed straight from the raw
+ dict, which accepts the unrecognized names without raising and yields zeros, so
+ a completed Responses batch reconciled to 0 tokens and $0.00 spend with no
+ error, and per-key budgets were never charged for it.
+
+ Line shape decides the parse, not the batch's declared endpoint, so an output
+ file mixing Responses-shaped and chat-shaped lines sums across both.
+ """
+
+ from typing import Literal, get_args, get_type_hints
+
+ import pytest
+
+ import litellm
+ import litellm.batches.batch_utils as bu
+ from litellm.types.llms.openai import CreateBatchRequest
+
+ MODEL = "gpt-5.6"
+
+
+ def _responses_line(input_tokens: int, output_tokens: int) -> dict:
+ return {
+ "response": {
+ "status_code": 200,
+ "body": {
+ "model": MODEL,
+ "usage": {
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": input_tokens + output_tokens,
+ },
+ },
+ }
+ }
+
+
+ def _chat_line(prompt_tokens: int, completion_tokens: int) -> dict:
+ return {
+ "response": {
+ "status_code": 200,
+ "body": {
+ "model": MODEL,
+ "usage": {
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": completion_tokens,
+ "total_tokens": prompt_tokens + completion_tokens,
+ },
+ },
+ }
+ }
+
+
+ def test_responses_shaped_usage_maps_onto_prompt_and_completion_tokens():
+ """The Responses names land on the chat-shaped counters instead of being
+ dropped for unrecognized keys."""
+ usage = bu._get_batch_job_usage_from_response_body(
+ {"usage": {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150}}
+ )
+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (100, 50, 150)
+
+
+ async def test_responses_batch_reconciles_to_real_tokens_and_spend(local_model_cost_map):
+ """A completed Responses batch records the provider's token counts and a
+ non-zero spend at the model's batch rates."""
+ model_info = litellm.get_model_info(model=MODEL, custom_llm_provider="openai")
+ input_tokens = 33
+ output_tokens = 57
+
- cost, usage, models = await bu.calculate_batch_cost_and_usage(
++ result = await bu.calculate_batch_cost_and_usage(
+ file_content_dictionary=[_responses_line(input_tokens, output_tokens)],
+ custom_llm_provider="openai",
+ model_name=MODEL,
+ model_info=model_info,
+ )
+
- assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (
++ assert (result.usage.prompt_tokens, result.usage.completion_tokens, result.usage.total_tokens) == (
+ input_tokens,
+ output_tokens,
+ input_tokens + output_tokens,
+ )
- assert models == [MODEL]
- assert cost == pytest.approx(
++ assert result.models == [MODEL]
++ assert result.cost == pytest.approx(
+ input_tokens * model_info["input_cost_per_token_batches"]
+ + output_tokens * model_info["output_cost_per_token_batches"]
+ )
- assert cost > 0.0
++ assert result.cost > 0.0
+
+
+ async def test_mixed_shape_batch_output_sums_across_both_line_shapes(local_model_cost_map):
+ """An output file carrying both line shapes sums both. A fix keyed off the
+ batch's declared endpoint rather than each line's shape would miss this."""
+ model_info = litellm.get_model_info(model=MODEL, custom_llm_provider="openai")
+
- cost, usage, _ = await bu.calculate_batch_cost_and_usage(
++ result = await bu.calculate_batch_cost_and_usage(
+ file_content_dictionary=[_responses_line(100, 50), _chat_line(33, 57)],
+ custom_llm_provider="openai",
+ model_name=MODEL,
+ model_info=model_info,
+ )
+
- assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (133, 107, 240)
- assert cost == pytest.approx(
++ assert (result.usage.prompt_tokens, result.usage.completion_tokens, result.usage.total_tokens) == (133, 107, 240)
++ assert result.cost == pytest.approx(
+ 133 * model_info["input_cost_per_token_batches"] + 107 * model_info["output_cost_per_token_batches"]
+ )
+
+
+ def test_create_batch_endpoint_accepts_v1_responses():
+ """A type-checked caller can pass endpoint="/v1/responses", which the runtime
+ already forwarded correctly."""
+ endpoint_annotation = get_type_hints(CreateBatchRequest)["endpoint"]
+ assert "/v1/responses" in get_args(endpoint_annotation)
+
+ for create_fn in (litellm.create_batch, litellm.acreate_batch):
+ assert "/v1/responses" in get_args(get_type_hints(create_fn)["endpoint"])