Repository navigation
fix(proxy): raise live budget counters for failure spend rows - #47741
Conversation
A stream that breaks mid-flight writes its recovered cost to the spend log, but the failure hook had already released the reservation and never touched the live counters, so an over-budget key kept passing until the counter was next repaired from the database Every charged failure row with a cost now raises the same counters the success path raises. The error waits at most a second for them, so a hung Redis cannot hold it back Fixes #35568
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
Devin Review found 2 potential issues.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| try: | ||
| await self._spend_counters()( |
There was a problem hiding this comment.
🔴 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
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
| 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( |
There was a problem hiding this comment.
🟡 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
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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
Merging this PR will not alter performance1 warning
Comparing |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. I ran the PR's unit file and both new integration files against a local proxy with Postgres and Redis. Every test passed. Checks and execution details
One input changes behavior: a key whose failure rows carry cost. Before, the next request still passed the live counter check until the DB repair ran about 60s later. Now that request is refused right away. Key, team and user DB spend already counted these rows, so this change closes an enforcement gap without breaking a supported contract. Failure spend also starts counting toward
Path I traced: Boundary cases checked:
The PR description acknowledges three paths where the DB already charges twice. Those duplicates come from existing behavior: the counters already reached the doubled totals after the DB repair, and now they reach them sooner.
Environment: local Postgres 15, Result: 15 passed in 234s, none skipped. The run covered key, team, user, end-user, tag and window budgets, concurrent streams, billed retries, a View review · Reviewed |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…nd outages Integration cells for team, user, end-user, tag and window budgets, concurrent streams, billed retries, native /v1/messages, Bedrock guardrail cost, a Redis stall on two workers and disable_spend_updates
|
@litereview code-review |
|
bugbot run |
…m_live_budget_counters
[Medium impact] The PR appears safe to merge, with no new actionable findings SummaryCharged failure rows now raise the live budget counters used to check later requests
All seven supplied previous threads are unnumbered and resolved. Their fixes remain present. No new actionable issue was found Reviews (5) · Last reviewed commit: "test(proxy): move the stalled counter bo..." · Reviewed by Greptile |
|
bugbot run |
…iter - The Redis stall cell now reads the burst key's live counter and requires at least the full failure spend - Unit tests drop the charging writer double, bare dicts, list mutation and wall-clock timestamps - Partial-stream test models are frozen
|
bugbot run |
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit d19ab3b. Configure here.
…m_live_budget_counters # Conflicts: # litellm/proxy/hooks/proxy_track_cost_callback.py
…I#47741) * fix(proxy): raise live budget counters for failure spend rows A stream that breaks mid-flight writes its recovered cost to the spend log, but the failure hook had already released the reservation and never touched the live counters, so an over-budget key kept passing until the counter was next repaired from the database Every charged failure row with a cost now raises the same counters the success path raises. The error waits at most a second for them, so a hung Redis cannot hold it back Fixes BerriAI#35568 * test(proxy): cover failure spend counters across budgets, endpoints and outages Integration cells for team, user, end-user, tag and window budgets, concurrent streams, billed retries, native /v1/messages, Bedrock guardrail cost, a Redis stall on two workers and disable_spend_updates * test(proxy): check stalled failure counters and use the real spend writer - The Redis stall cell now reads the burst key's live counter and requires at least the full failure spend - Unit tests drop the charging writer double, bare dicts, list mutation and wall-clock timestamps - Partial-stream test models are frozen * test(proxy): move the stalled counter bound reason into the assert message --------- Co-authored-by: yucheng-berri <293926326+yucheng-berri@users.noreply.github.com> Adapted for lts/1.108.x: the line's failure hook has no finalized-cost branch, so the completed-cost unit test is left out (cherry picked from commit f4d1f45)
Description
When a streamed reply breaks partway through, the proxy already logs the partial cost against the key, but it never added that cost to the live counter the budget check reads. A key that had gone over budget kept getting served until the counter was repaired from the database about a minute later. Failure rows that cost something now raise the same live counters a successful request raises, so the next request is refused right away
Details
TLDR
Problem this solves:
How it solves it:
User Flow
Before: a developer whose broken streams already used up their key's budget keeps getting served
"max_budget": 0.00066APIConnectionErrorerror frame and https://litellm-domain/ui/?page=logs shows the request as a failure costing $0.00044After: the same developer is refused as soon as the broken streams use up the budget
"max_budget": 0.00066APIConnectionErrorerror frame and https://litellm-domain/ui/?page=logs shows the request as a failure costing $0.00044Budget has been exceeded! Key=developer-app-head (sk-...hzLQ) Current cost: 0.00088, Max budget: 0.00066without calling OpenAIRelevant issues
Fixes #35568
Thanks to @Hamjaster for #35752, which spotted the same gap first. That PR reconciles only the reserved counters and its test file has since been deleted on main, so this PR raises every live counter the success path raises instead
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Admin UI
The User Flow above, on the bundled dashboard of a real proxy with real
openai/gpt-6.1-solcalls. Two broken streams come from a developer's app, then attempt 3 is sent from the Playground with the same virtual keyBefore (e333cca): attempt 3 streams and breaks like the first two
Before (e333cca): the key's logs show three failures of $0.000440 against a $0.00066 budget
After (5485c90): attempt 3 is refused with the 422 budget error
After (5485c90): the key's logs show two failures of $0.000440 and the refused attempt at $0
curl
Real proxy with Redis and Postgres, real
openai/gpt-6.1-solcalls, run on a Linux box. A small forwarder sits in front of api.openai.com and drops the connection after 40 content chunks for any prompt containingBREAK, the way a flaky network does. OpenAI still answers and bills every call, and itsx-request-ids are listed at the end of each run. Same config and same steps on both sides:One broken stream costs $0.00044, so the key gets a budget of 1.5 broken streams. Each attempt is
Before (e333cca)
POST /key/generatewith{"max_budget": 0.00066, "models": ["gpt-live"]}creates the keydata: {"error": {"message": "litellm.APIConnectionError: APIConnectionError: OpenAIException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>, andredis-cli GET spend:key:$TOKENreads0000LiteLLM_SpendLogsholds four failure rows of $0.00044 each, so the key was charged $0.00176 against $0.00066req_b41609238c9b452a9e39e9ad164dcff2,req_c0540c571f54456996067d6061af2acc,req_2ba68ff9a6964fe88c4e1c92a7525efd,req_3d32d257dcda494c97550b14570fe65fAfter (5485c90)
POST /key/generatewith{"max_budget": 0.00066, "models": ["gpt-live"]}creates the keydata: {"error": {"message": "litellm.APIConnectionError: APIConnectionError: OpenAIException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>, andredis-cli GET spend:key:$TOKENreads0.000440.00088{"error":{"message":"Budget has been exceeded! Key=key (sk-...T83g) Current cost: 0.00088, Max budget: 0.00066","type":"budget_exceeded","param":null,"code":"422"}}without calling OpenAI0.00088LiteLLM_SpendLogsholds two failure rows of $0.00044 and two refused rows of $0, so the key was charged $0.00088 against $0.00066req_5f9da4e2eb74493d966f72c0b7f92b6b,req_eb0880e6cffb43e788155494dbb505b4Behavior changes
Removed / renamed
Silent regressions to watch
budget_limitswindows, which main never didallm_passthrough_routestream where a priced guardrail raises after the first frame/v1/messagesand/v1/responsesstreams blocked at the end by a priced post-call guardrail, such as BedrockMigration for existing customers
Regression tests
tests/integration/spend/test_partial_stream_live_budget.pyandtest_failure_spend_live_counters_chaos.pydrive a real proxy, Postgres and Redis against a local stand-in for the provider. In these cells main serves the next request with 200 and this PR refuses it with 422budget_limitswindow/v1/messagesstream and a Bedrock guardrail's cost on blocked requestsdisable_spend_updates: trueleaves the budget alonetest_failure_spend_rows_raise_the_live_spend_counters_by_their_costchecks all nine counters for recovered stream cost, billed attempts and a zero-cost failuretest_failure_spend_rows_leave_the_live_spend_counters_alone_while_spend_updates_are_disabledcoversdisable_spend_updatestest_a_failing_spend_counter_store_is_still_sent_every_failure_spend_rowandtest_a_slow_spend_counter_store_lets_the_failure_out_and_raises_the_counters_once_it_answerscover a failing and a hung counter storetest_a_failure_spend_row_lands_in_the_key_budget_window_as_of_the_request_startandtest_a_billed_attempt_on_a_deployment_the_router_dropped_debits_every_attributed_access_groupcover budget windows and access groups/live-pr-risk
Ran the merge base e333cca against 5485c90 after the bot loop, on a real proxy with real OpenAI calls, Postgres and Redis, at 1 and 4 workers, with and without Redis, and with Redis or Postgres paused mid-stream. The commit after 5485c90 only adds integration tests, so the proxy code is the same
ProxyDBLoggeronly gained keyword arguments with defaults/v1/messagesbroken streams on an OpenAI model are billed as successes, and the key is refused at attempt 3 on both sides/v1/responsesbroken streams record $0 on both sides, see CaveatsType
🐛 Bug Fix
✅ Test
Caveats (if any)
Medium
/v1/responsesbroken streams record $0 recovered cost on main and here, so they still never count toward a budgetdisable_error_logs: truethe failure hook returns before it records any recovered cost, so the gap stays thereLow
/v1/messagesstream sometimes writes no spend row, on main and here alike. The request'smax_tokensreservation then stays on the counter instead of the real costtests/integrationon main only, so the flush mutation is not caught on this PR's CIhash_tokeninlitellm/proxy/utils.py. That alert has been open on main since 2026-08-17 and this PR does not touch the fileimage-scanfails on certifi 2026.4.22 (GHSA-6q48-6c7w-9gw2, fixed in 2026.10.19). Main'suv.lockpins the same version and other open PRs fail the same wayFinal Attestation
REVIEWER MUST KNOW BEFORE APPROVING
budget_limitswindows. Main counted it only after the counter was repaired from the DB about a minute laterNote
Medium Risk
Changes budget enforcement on every charged failure path (streams, retries, guardrails) and adds up to 1s latency when Redis counters are slow; mis-increment could refuse or allow traffic incorrectly until repair.
Overview
Failure spend that was already written to the database now updates the same live budget counters as successful requests, so keys over budget after a broken stream (or other charged failure) are refused on the next call instead of staying under the limit until counters are repaired from the DB.
After persisting failure spend rows,
_ProxyDBLoggerincrements key/team/user/org/tag/access-group counters viaincrement_spend_counters, flushes post-call Redis batches, and respectsdisable_spend_updates. Counter updates wait up to 1 second (FAILURE_SPEND_COUNTER_WAIT_SECONDS); slower stores finish in the background so errors are not blocked on Redis.ProxyDBLoggergains injectablespend_countersandfailure_counter_wait_secondsfor tests.Tests add integration coverage for partial streams, team/user/end-user/tag/window budgets, guardrail-blocked spend, Redis stalls, and multi-worker behavior, plus unit tests for counter increments, disabled spend updates, slow/failing stores, budget windows, and access groups.
Reviewed by Cursor Bugbot for commit d19ab3b. Bugbot is set up for automated code reviews on this repo. Configure here.