Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 115 additions & 9 deletions litellm/proxy/hooks/proxy_track_cost_callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.batches.batch_utils import batch_cost_is_final
from litellm.caching.redis_batch import flush_post_call_redis_batches
from litellm.constants import BACKGROUND_INTERACTION_COST_POLLING_ENABLED, BILLED_RETRY_ATTEMPT_METADATA_KEY
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.core_helpers import (
Expand Down Expand Up @@ -134,6 +135,8 @@ def _batch_accounting_for(call_id: object) -> BatchAccountingOutcome | None:
)
)

FAILURE_SPEND_COUNTER_WAIT_SECONDS: Final = 1.0


_OBJECT_MAPPING: Final = TypeAdapter(ObjectMapping)

Expand Down Expand Up @@ -235,6 +238,12 @@ def _proxy_spend_writer() -> DBSpendUpdateWriter:
return proxy_logging_obj.db_spend_update_writer


def _proxy_spend_counters() -> "_IncrementSpendCounters":
from litellm.proxy.proxy_server import increment_spend_counters

return increment_spend_counters


DeploymentLookup: TypeAlias = Callable[[str], Deployment | None]


Expand Down Expand Up @@ -361,11 +370,16 @@ def __init__(
message_logging: bool = True,
spend_writer: Callable[[], DBSpendUpdateWriter] = _proxy_spend_writer,
deployment_lookup: DeploymentLookup = _proxy_deployment,
spend_counters: Callable[[], "_IncrementSpendCounters"] = _proxy_spend_counters,
failure_counter_wait_seconds: float = FAILURE_SPEND_COUNTER_WAIT_SECONDS,
) -> None:
super().__init__(turn_off_message_logging=turn_off_message_logging, message_logging=message_logging)
self.spend_event_producer = spend_event_producer
self._spend_writer: Final = spend_writer
self._deployment_lookup: Final = deployment_lookup
self._spend_counters: Final = spend_counters
self._failure_counter_wait_seconds: Final = failure_counter_wait_seconds
self._pending_increments: Final[set[asyncio.Task[None]]] = set() # mutable-ok: tasks leave when done

async def async_log_success_event(
self, kwargs: ObjectMapping, response_obj: object, start_time: datetime, end_time: datetime
Expand Down Expand Up @@ -590,9 +604,11 @@ async def _write_failure_spend_rows(
completed_cost: bool = False,
request_tags: list[str] | None = None,
) -> None:
"""One spend row (and one key/team/user spend deduction) per ``(response_cost, kwargs)`` pair."""
for row_cost, row_kwargs in spend_rows:
if completed_cost:
"""One spend row (and one key/team/user spend deduction) per ``(response_cost, kwargs)`` pair, then the
live spend counters raised by every charged row that cost something. A completed cost settles through the
success path's write, which raises the counters against the kept reservation."""
if completed_cost:
for row_cost, row_kwargs in spend_rows:
from litellm.proxy.proxy_server import increment_spend_counters, proxy_logging_obj

await _update_database_and_spend_counters(
Expand Down Expand Up @@ -623,12 +639,16 @@ async def _write_failure_spend_rows(
router=get_llm_router(),
),
)
continue
return

token: Final = LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict)
end_user_id: Final = None if litellm.disable_end_user_cost_tracking else user_api_key_dict.end_user_id
charged: Final = [
await self._spend_writer().update_database(
token=LiteLLMProxyRequestSetup.get_logged_api_key(user_api_key_dict),
token=token,
response_cost=row_cost,
user_id=user_api_key_dict.user_id,
end_user_id=None if litellm.disable_end_user_cost_tracking else user_api_key_dict.end_user_id,
end_user_id=end_user_id,
team_id=user_api_key_dict.team_id,
kwargs=dict(row_kwargs),
completion_response=original_exception,
Expand All @@ -637,6 +657,91 @@ async def _write_failure_spend_rows(
org_id=user_api_key_dict.org_id,
project_id=user_api_key_dict.project_id,
)
for row_cost, row_kwargs in spend_rows
]
counted_rows: Final = tuple(
row for row, row_charged in zip(spend_rows, charged, strict=True) if row_charged and row[0] > 0
)
if counted_rows and not ProxyUpdateSpend.disable_spend_updates():
await self._increment_failure_spend_counters(
Comment on lines +662 to +666

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Unwritten failure spend raises budgets

When a failure spend write fails, charged can still be true because update_database returns true on exceptions. The new counter update then charges a budget for spend absent from the database

Learn more

The database writer catches errors from building or enqueueing a spend log and returns True. That value normally means the caller owns the charge, but it does not prove the failed row was persisted. The new failure path treats it as proof and updates live budgets even if the write failed before recording any spend.

Example: A $0.40 failure row cannot be enqueued because the database queue fails. The writer returns True; a key with a $0.30 budget gets a $0.40 counter increment without a matching database charge

Recommended fix: Give update_database an outcome that distinguishes a successful or queued charge from a failed write, and only increment on the former. Preserve its existing batch-deduplication behavior

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The success path gates counters on the same return value, so failure rows match it. Live, a paused Postgres still queued the row, which landed afterwards

user_api_key_dict, token, end_user_id, counted_rows, start_time
)

async def _increment_failure_spend_counters(
self,
user_api_key_dict: UserAPIKeyAuth,
token: str | None,
end_user_id: str | None,
counted_rows: Sequence[tuple[float, Mapping[str, object]]],
start_time: datetime,
) -> None:
"""The counters the success path raises for the same spend, sent before the client sees the error. A
counter store slower than ``failure_counter_wait_seconds`` finishes them in the background instead of
holding the error back. The reservation was already released, so every counter takes the full row cost."""
increment: Final = asyncio.create_task(
self._raise_failure_spend_counters(user_api_key_dict, token, end_user_id, counted_rows, start_time)
)
self._pending_increments.add(increment)
increment.add_done_callback(self._pending_increments.discard)
finished, _ = await asyncio.wait((increment,), timeout=self._failure_counter_wait_seconds)
if not finished:
verbose_proxy_logger.warning(
"Spend counters for failure spend rows took over %ss, finishing them in the background",
self._failure_counter_wait_seconds,
)

async def _raise_failure_spend_counters(
self,
user_api_key_dict: UserAPIKeyAuth,
token: str | None,
end_user_id: str | None,
counted_rows: Sequence[tuple[float, Mapping[str, object]]],
start_time: datetime,
) -> None:
for row_cost, row_kwargs in counted_rows:
await self._raise_row_spend_counters(
user_api_key_dict, token, end_user_id, row_cost, row_kwargs, start_time
)
await flush_post_call_redis_batches()

async def _raise_row_spend_counters(
self,
user_api_key_dict: UserAPIKeyAuth,
token: str | None,
end_user_id: str | None,
row_cost: float,
row_kwargs: Mapping[str, object],
start_time: datetime,
) -> None:
standard_logging_object: Final = row_kwargs.get("standard_logging_object")
sl_object: Final = (
cast("StandardLoggingPayload", standard_logging_object) # cast-ok: the failure snapshot dict
if isinstance(standard_logging_object, dict)
else None
)
metadata: Final = _str_keyed_fields(_str_keyed_fields(row_kwargs.get("litellm_params")).get("metadata"))
served_model_id: Final = _str_keyed_fields(metadata.get("model_info")).get("id") or _str_keyed_fields(
standard_logging_object
).get("model_id")
try:
await self._spend_counters()(
Comment on lines +726 to +727

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Cold counters double-count failure spend

When a failure spend row reaches the database before increment_spend_counters seeds a cold counter, that row counts twice. SpendCounterReseed seeds from database spend that already includes the row. The affected budget can reject a request below its limit

Learn more

The failure writer queues its spend log before starting the counter task. A cold counter is initialized by reading the database and then incrementing the row cost. If the log and spend updates flush between those operations, the seed already contains this row, and the increment adds it again. The same ordering applies to budget-window counters, whose cold seed can aggregate spend logs.

Example: A key has no live counter and $0 previous spend. A $0.50 broken-stream row reaches the database before the counter's cold read. The seed reads $0.50, then the new increment yields $1.00 against $0.50 actually billed

Recommended fix: Coordinate initialization and spend attribution so a cold seed excludes this row, or initialize the affected counters before enqueueing the row. Check both coalesced and coalesced_window, including concurrent database flushes

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The success path also writes its row before raising counters. Six live cold-counter breaks, half with Redis paused past the DB flush, each counted once

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction, a cold counter seeded after a stall past the DB flush counts these rows twice, and completed streams held the same way double too

token=token,
team_id=user_api_key_dict.team_id,
user_id=user_api_key_dict.user_id,
response_cost=row_cost,
org_id=user_api_key_dict.org_id,
end_user_id=end_user_id,
tags=_get_request_tags_for_cost_tracking(sl_object=sl_object, metadata=dict(metadata)),
request_started_at=start_time,
model_access_groups=debitable_model_access_groups(
attributed=get_request_model_access_groups(row_kwargs),
served_model_id=served_model_id if isinstance(served_model_id, str) else None,
router=get_llm_router(),
),
project_id=user_api_key_dict.project_id,
)
except Exception: # noqa: BLE001 # one row's counter failure must not keep the other rows' counters from landing
verbose_proxy_logger.exception("Failed to raise spend counters for a failure spend row")

async def _PROXY_track_cost_callback(
self,
Expand Down Expand Up @@ -1060,7 +1165,7 @@ def _metadata_keys(metadata: object) -> tuple[str, ...]:
return tuple(sorted(str(key) for key in metadata))


def _get_budget_reservation_from_metadata(metadata: dict) -> dict | None:
def _get_budget_reservation_from_metadata(metadata: dict) -> dict[str, object] | None:
return budget_reservation_from_metadata(metadata)


Expand Down Expand Up @@ -1095,6 +1200,7 @@ async def __call__(
tags: list[str] | None = None,
request_started_at: datetime | None = None,
model_access_groups: Sequence[str] | None = None,
project_id: str | None = None,
) -> None: ...


Expand All @@ -1111,7 +1217,7 @@ async def _update_database_and_spend_counters(
start_time: datetime | None,
end_time: datetime | None,
response_cost: float,
budget_reservation: dict | None,
budget_reservation: dict[str, object] | None,
request_tags: list[str] | None = None,
model_access_groups: Sequence[str] | None = None,
project_id: str | None = None,
Expand Down Expand Up @@ -1174,7 +1280,7 @@ async def _update_database_and_spend_counters_in_batch(
start_time: datetime | None,
end_time: datetime | None,
response_cost: float,
budget_reservation: dict | None,
budget_reservation: dict[str, object] | None,
request_tags: list[str] | None,
model_access_groups: Sequence[str] | None,
project_id: str | None,
Expand Down
2 changes: 1 addition & 1 deletion litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3508,7 +3508,7 @@ async def increment_spend_counters(
user_id: str | None,
response_cost: float | None,
org_id: str | None = None,
budget_reservation: dict | None = None,
budget_reservation: dict[str, object] | None = None,
end_user_id: str | None = None,
tags: list[str] | None = None,
request_started_at: datetime | None = None,
Expand Down
173 changes: 173 additions & 0 deletions tests/integration/spend/_partial_stream.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import json
import threading
import uuid
from collections.abc import Callable, Iterable, Iterator
from hashlib import sha256
from typing import Final

import httpx
from integration._support.client import Gateway, Scenario, eventually, held
from integration._support.wire import Reply, Request, Wire
from openai.types.chat import ChatCompletionChunk
from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter

JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
BACKEND: Final = "integration-partial-stream"
PIECE: Final = "partial stream billed tokens "
DELIVERED_PIECES: Final = 12
_FAILURE_ROWS: Final = 'SELECT spend FROM "LiteLLM_SpendLogs" WHERE api_key=%s AND status=%s ORDER BY "startTime"'
ROWS: Final = 'SELECT status, spend FROM "LiteLLM_SpendLogs" WHERE api_key=%s ORDER BY "startTime"'


class _SpendRow(BaseModel):
model_config = ConfigDict(frozen=True)

spend: float
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


class StatusRow(BaseModel):
model_config = ConfigDict(frozen=True)

status: str
spend: float


class _BudgetError(BaseModel):
model_config = ConfigDict(frozen=True)

type: str


class _ErrorResponse(BaseModel):
model_config = ConfigDict(frozen=True)

error: _BudgetError


def _chunk(stream_id: str, delta: dict[str, JsonValue], finish_reason: str | None = None) -> bytes:
body: Final = {
"id": stream_id,
"object": "chat.completion.chunk",
"created": 1700000000,
"model": BACKEND,
"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
}
return f"data: {json.dumps(body)}\n\n".encode()


def completion() -> bytes:
return json.dumps(
{
"id": f"chatcmpl-{uuid.uuid4().hex}",
"object": "chat.completion",
"created": 1700000000,
"model": BACKEND,
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
}
).encode()


def peer(delivered: int | None, gate: threading.Event | None = None) -> Callable[[Request], Reply]:
def respond(request: Request) -> Reply:
if request.method != "POST":
return Reply(status=404)
if JSON_OBJECT.validate_json(request.body).get("stream") is True:
stream_id: Final = f"chatcmpl-{uuid.uuid4().hex}"
return Reply(
content_type="text/event-stream",
chunks=(
*(_chunk(stream_id, {"role": "assistant", "content": PIECE}) for _ in range(DELIVERED_PIECES)),
_chunk(stream_id, {}, "stop"),
b"data: [DONE]\n\n",
),
abort_after=delivered,
pause_between_chunks=0.02,
gate_before_first=gate,
)
return Reply(body=completion())

return respond


def priced_model(scenario: Scenario, wire: Wire) -> str:
return scenario.model(
model=f"openai/{BACKEND}",
api_base=f"{wire.url}/v1",
api_key="synthetic-openai-key",
input_cost_per_token=0.001,
output_cost_per_token=0.002,
)


def stream(gateway: Gateway, model: str, key: str, **fields: JsonValue) -> httpx.Response:
return gateway.request(
"POST",
"/v1/chat/completions",
{
"model": model,
"max_tokens": 5,
"stream": True,
"messages": [{"role": "user", "content": "partial stream"}],
**fields,
},
key=key,
)


def broken_stream(gateway: Gateway, model: str, key: str, **fields: JsonValue) -> None:
response: Final = stream(gateway, model, key, **fields)
assert response.status_code == 200, response.text
events: Final = tuple(
line.removeprefix("data: ")
for line in response.text.splitlines()
if line.startswith("data: ") and line != "data: [DONE]"
)
assert "error" in JSON_OBJECT.validate_json(events[-1]), response.text
delivered: Final = "".join(_streamed_text(ChatCompletionChunk.model_validate_json(event) for event in events[:-1]))
assert delivered == PIECE * DELIVERED_PIECES, response.text


def _streamed_text(chunks: Iterable[ChatCompletionChunk]) -> Iterator[str]:
for chunk in chunks:
yield from (choice.delta.content or "" for choice in chunk.choices)


def chat(gateway: Gateway, model: str, key: str, **fields: JsonValue) -> httpx.Response:
return gateway.request(
"POST",
"/v1/chat/completions",
{
"model": model,
"max_tokens": 5,
"messages": [{"role": "user", "content": f"after {uuid.uuid4().hex}"}],
**fields,
},
key=key,
)


def failure_spend(gateway: Gateway, key: str, rows: int = 1) -> tuple[float, ...]:
digest: Final = sha256(key.encode()).hexdigest()
eventually(lambda: gateway.rows(_FAILURE_ROWS, (digest, "failure")), lambda found: len(found) >= rows, seconds=70)
found: Final = held(
lambda: gateway.rows(_FAILURE_ROWS, (digest, "failure")), lambda latest: len(latest) == rows, holding=2
)
return tuple(_SpendRow.model_validate(row).spend for row in found)


def chats_sent(wire: Wire) -> int:
return sum(1 for request in wire.drain() if request.method == "POST")


def recovered_cost(gateway: Gateway, scenario: Scenario, model: str) -> float:
key: Final = scenario.key(models=[model], max_budget=100)
broken_stream(gateway, model, key)
(spend,) = failure_spend(gateway, key)
assert spend > 0
return spend


def assert_budget_refusal(response: httpx.Response) -> None:
assert response.status_code == 422, response.text
assert _ErrorResponse.model_validate_json(response.content).error.type == "budget_exceeded", response.text
Loading
Loading