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(spend): charge a batch once when an older proxy left its cost row at $0
mateo-berri0fb3951b2cad
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.pyindex 48312c025dd..ae3bc5663eb 100644--- a/litellm/proxy/db/db_spend_update_writer.py+++ b/litellm/proxy/db/db_spend_update_writer.py@@ -14,6 +14,7 @@ import timeimport tracebackfrom collections.abc import Mapping, Sequencefrom datetime import datetime, timedelta, timezone+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Literal, Protocol, cast, overloadimport litellm@@ -379,9 +380,44 @@ class DBSpendUpdateWriter:if existing.spend > 0:verbose_proxy_logger.debug("Cost tracking skipped: spend row %s already charged this batch", request_id)return False- verbose_proxy_logger.debug(- "Spend row %s charged nothing for this batch, so this retrieve charges it", request_id- )+ return await self._take_over_uncharged_batch_cost_row(payload=payload, prisma_client=prisma_client)++ async def _take_over_uncharged_batch_cost_row(+ self, payload: SpendLogsPayload, prisma_client: "PrismaClient"+ ) -> bool:+ """Take the batch's cost row over from the poll that left it charging nothing.++ A pre-upgrade proxy wrote that row every time it polled the batch while it was still+ running, so the charge is still to be made and the row still has to end up carrying+ it. The row stops matching the moment it carries a charge, so it is one retrieve that+ takes it over and charges, and every later one reads the charge and charges nothing.+ """+ from litellm.repositories.table_repositories import SpendLogsRepository++ request_id: Final = payload["request_id"]+ if payload["spend"] <= 0:+ verbose_proxy_logger.debug(+ "Cost tracking skipped: this batch costs nothing and spend row %s says so", request_id+ )+ return False+ try:+ taken_over: Final = await SpendLogsRepository(prisma_client).table.update_many(+ data=prisma_client.jsonify_object(+ MappingProxyType({field: value for field, value in payload.items() if field != "request_id"})+ ),+ where={ # mutable-ok: prisma where clause+ "request_id": request_id,+ "call_type": CallTypes.aretrieve_batch.value,+ "status": "success",+ "spend": 0.0,+ },+ )+ except Exception as e: # noqa: BLE001 # prisma raises its own hierarchy; a row it cannot take over charges the batch+ verbose_proxy_logger.warning("Could not take over spend row %s for a batch's cost: %s", request_id, e)+ return True+ if taken_over == 0:+ verbose_proxy_logger.debug("Cost tracking skipped: spend row %s already charged this batch", request_id)+ return Falsereturn Trueasync def _enqueue_tool_usage_transaction(diff --git a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py b/tests/test_litellm/proxy/db/test_db_spend_update_writer.pyindex 41f2be08545..33b7af06e1a 100644--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py@@ -2969,16 +2969,21 @@ def _batch_cost_payload() -> dict:}-def _spend_logs_prisma(inserted: int, existing: object) -> MagicMock:+def _spend_logs_prisma(inserted: int, existing: object, taken_over: int = 1) -> MagicMock:prisma = _tool_usage_prisma()prisma.jsonify_object = lambda data: dict(data)prisma.db.litellm_spendlogs.create_many = AsyncMock(return_value=inserted)prisma.db.litellm_spendlogs.find_unique = AsyncMock(return_value=existing)+ prisma.db.litellm_spendlogs.update_many = AsyncMock(return_value=taken_over)return prismaasync def _update_database_with(- db_writer: DBSpendUpdateWriter, prisma: MagicMock, payload: dict, disable_spend_logs: bool = False+ db_writer: DBSpendUpdateWriter,+ prisma: MagicMock,+ payload: dict,+ disable_spend_logs: bool = False,+ response_cost: float = 0.25,) -> bool:with (patch( # test-quality-ok: update_database reads this proxy_server global at call time, no seam@@ -3005,7 +3010,7 @@ async def _update_database_with(completion_response=None,start_time=datetime.now(timezone.utc),end_time=datetime.now(timezone.utc),- response_cost=0.25,+ response_cost=response_cost,)await asyncio.sleep(0)return charged@@ -3054,6 +3059,71 @@ async def test_update_database_charges_a_batch_only_from_the_retrieve_that_wroteassert db_writer._batch_database_updates.await_count == (1 if charged else 0)+ ("taken_over", "charged"),+ [(1, True), (0, False)],+ ids=["this_retrieve_takes_it_over", "another_one_got_there_first"],+)+async def test_update_database_charges_a_batch_whose_row_a_pre_upgrade_poll_left_at_zero(+ taken_over: int, charged: bool+):+ """+ A proxy without this fix wrote the batch's row at $0 on every poll of a running batch,+ and the row outlives the upgrade, so the charge has to land on the row itself. Charging+ without writing it there would charge again on every later retrieve (LIT-7048).+ """+ db_writer = DBSpendUpdateWriter()+ db_writer._batch_database_updates = AsyncMock()+ existing = SimpleNamespace(call_type="aretrieve_batch", status="success", spend=0.0)+ prisma = _spend_logs_prisma(0, existing, taken_over)++ assert await _update_database_with(db_writer, prisma, _batch_cost_payload()) is charged++ taken = prisma.db.litellm_spendlogs.update_many.await_args.kwargs+ assert taken["where"] == {+ "request_id": "batch_abc_batch_cost",+ "call_type": "aretrieve_batch",+ "status": "success",+ "spend": 0.0,+ }+ assert taken["data"]["spend"] == 0.25+ assert "request_id" not in taken["data"]+ assert db_writer._batch_database_updates.await_count == (1 if charged else 0)+++async def test_update_database_charges_a_batch_whose_zero_row_it_could_not_take_over():+ """A DB that refuses the takeover must not swallow the batch's cost."""+ db_writer = DBSpendUpdateWriter()+ db_writer._batch_database_updates = AsyncMock()+ existing = SimpleNamespace(call_type="aretrieve_batch", status="success", spend=0.0)+ prisma = _spend_logs_prisma(0, existing)+ prisma.db.litellm_spendlogs.update_many = AsyncMock(side_effect=RuntimeError("db unreachable"))++ assert await _update_database_with(db_writer, prisma, _batch_cost_payload()) is True++ assert db_writer._batch_database_updates.await_count == 1+++async def test_update_database_leaves_a_batch_that_cost_nothing_to_the_retrieve_that_wrote_its_row():+ """+ A batch every line of which failed costs $0, so its row reads $0 for the honest reason+ and the retrieve that wrote it is still the one that accounted it. Taking that row over+ on every later retrieve would count one batch as many requests.+ """+ db_writer = DBSpendUpdateWriter()+ db_writer._batch_database_updates = AsyncMock()+ existing = SimpleNamespace(call_type="aretrieve_batch", status="success", spend=0.0)+ prisma = _spend_logs_prisma(0, existing)++ assert await _update_database_with(db_writer, prisma, _batch_cost_payload(), response_cost=0.0) is False++ prisma.db.litellm_spendlogs.update_many.assert_not_called()+ assert db_writer._batch_database_updates.await_count == 0++@pytest.mark.asyncio@pytest.mark.parametrize(("inserted", "existing", "charged"),