Skip to content

fix(proxy): raise live budget counters for failure spend rows - #47741

Merged
yucheng-berri merged 6 commits into
mainfrom
litellm_partial_stream_live_budget_counters
Oct 30, 2026
Merged

yucheng-berri merged 6 commits into
mainfrom
litellm_partial_stream_live_budget_counters

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • A stream that breaks mid-flight logs its partial cost to the DB only
  • The live budget counters stay low, so over-budget keys keep passing
  • The gap lasts until the counter is repaired from the DB, about 60s

How it solves it:

  • Every charged failure row with a cost now raises the live counters
  • Same counters the success path raises, from key to access group
  • The error waits at most 1s for them, then they finish in the background

User Flow

Before: a developer whose broken streams already used up their key's budget keeps getting served

  1. The admin creates a key with POST https://litellm-domain/key/generate and "max_budget": 0.00066
  2. The developer's app streams POST https://litellm-domain/v1/chat/completions and the connection to OpenAI drops after 40 chunks
  3. The stream ends with an APIConnectionError error frame and https://litellm-domain/ui/?page=logs shows the request as a failure costing $0.00044
  4. The same thing happens a second time, which puts the key at $0.00088, over its budget
  5. Attempt 3, sent from the Admin UI Playground with the same key, still streams and breaks the same way, so the key is charged $0.00132 against a $0.00066 budget

After: the same developer is refused as soon as the broken streams use up the budget

  1. The admin creates a key with POST https://litellm-domain/key/generate and "max_budget": 0.00066
  2. The developer's app streams POST https://litellm-domain/v1/chat/completions and the connection to OpenAI drops after 40 chunks
  3. The stream ends with an APIConnectionError error frame and https://litellm-domain/ui/?page=logs shows the request as a failure costing $0.00044
  4. The same thing happens a second time, which puts the key at $0.00088, over its budget
  5. Attempt 3, sent from the Admin UI Playground with the same key, comes back 422 Budget has been exceeded! Key=developer-app-head (sk-...hzLQ) Current cost: 0.00088, Max budget: 0.00066 without calling OpenAI

Relevant 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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-sol calls. Two broken streams come from a developer's app, then attempt 3 is sent from the Playground with the same virtual key

Before (e333cca): attempt 3 streams and breaks like the first two

Before: attempt 3 streams from the Playground

Before (e333cca): the key's logs show three failures of $0.000440 against a $0.00066 budget

Before: three charged failure rows

After (5485c90): attempt 3 is refused with the 422 budget error

After: attempt 3 refused in the Playground

After (5485c90): the key's logs show two failures of $0.000440 and the refused attempt at $0

After: two charged failure rows and one refused row

curl

Real proxy with Redis and Postgres, real openai/gpt-6.1-sol calls, 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 containing BREAK, the way a flaky network does. OpenAI still answers and bills every call, and its x-request-ids are listed at the end of each run. Same config and same steps on both sides:

model_list:
  - model_name: gpt-live
    litellm_params:
      model: openai/gpt-6.1-sol
      api_base: http://127.0.0.1:4580/v1   # the forwarder
      api_key: os.environ/OPENAI_API_KEY
router_settings:
  redis_host: 127.0.0.1
  redis_port: <redis port>
general_settings:
  master_key: sk-master-35568
  database_url: postgresql://...

One broken stream costs $0.00044, so the key gets a budget of 1.5 broken streams. Each attempt is

curl -sN $P/v1/chat/completions -H "Authorization: Bearer $KEY" \
  -d '{"model": "gpt-live", "stream": true, "max_tokens": 400, "messages": [{"role": "user", "content": "BREAK test. Count from 1 to 200, one number per line, nothing else"}]}'

Before (e333cca)

  1. POST /key/generate with {"max_budget": 0.00066, "models": ["gpt-live"]} creates the key
  2. Attempt 1 streams 40 chunks, then data: {"error": {"message": "litellm.APIConnectionError: APIConnectionError: OpenAIException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>, and redis-cli GET spend:key:$TOKEN reads 0
  3. Attempt 2 streams 40 chunks and ends the same way, and the counter still reads 0
  4. Attempt 3 streams 40 chunks and ends the same way, and the counter still reads 0
  5. Attempt 4 streams 40 chunks and ends the same way, and the counter still reads 0
  6. LiteLLM_SpendLogs holds four failure rows of $0.00044 each, so the key was charged $0.00176 against $0.00066
  7. OpenAI request ids req_b41609238c9b452a9e39e9ad164dcff2, req_c0540c571f54456996067d6061af2acc, req_2ba68ff9a6964fe88c4e1c92a7525efd, req_3d32d257dcda494c97550b14570fe65f

After (5485c90)

  1. POST /key/generate with {"max_budget": 0.00066, "models": ["gpt-live"]} creates the key
  2. Attempt 1 streams 40 chunks, then data: {"error": {"message": "litellm.APIConnectionError: APIConnectionError: OpenAIException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>, and redis-cli GET spend:key:$TOKEN reads 0.00044
  3. Attempt 2 streams 40 chunks and ends the same way, and the counter reads 0.00088
  4. Attempt 3 comes back {"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 OpenAI
  5. Attempt 4 comes back the same 422, and the counter stays at 0.00088
  6. LiteLLM_SpendLogs holds two failure rows of $0.00044 and two refused rows of $0, so the key was charged $0.00088 against $0.00066
  7. OpenAI request ids req_5f9da4e2eb74493d966f72c0b7f92b6b, req_eb0880e6cffb43e788155494dbb505b4

Behavior changes

Removed / renamed

  • None

Silent regressions to watch

  • A failure row that cost something now raises the live counters right away, the way a success does
    • That covers recovered stream cost, the cost of a guardrail that blocked the request, and provider-billed timeouts and earlier retry attempts
    • Main only reached the same totals once the counter was repaired from the DB, about a minute later
  • Failure spend now also adds to budget_limits windows, which main never did
    • Measured live, a key with a one-day window of 1.5 broken streams is refused on attempt 3, where main served all four
  • Main already charges the DB twice on three paths, and the counters now carry that doubled amount right away instead of after the repair
    • A guarded allm_passthrough_route stream where a priced guardrail raises after the first frame
    • Native /v1/messages and /v1/responses streams blocked at the end by a priced post-call guardrail, such as Bedrock
    • A2A streaming, where the failure hook runs twice on the same request
  • During a Redis outage the error frame of a broken stream waits up to 1s longer than on main
    • Measured with Redis paused mid-stream, a key with no budget got its error after 1.3 to 1.5s here against 0.4 to 0.6s on main
    • A key with a budget got it after 16.3 to 16.6s here against 15.4 to 15.9s on main
    • The counters still land once Redis answers
  • A cold counter seeded after a Redis stall that outlasts the DB spend flush can count the stalled failure rows twice
    • Completed streams held past a flush double the same way. With Redis paused 3.3s on two workers, 12 rows of 0.107 seeded the key counter at 1.284 and landed at 2.568
    • It refuses early rather than late, which is the trade the cold seed already makes for successes

Migration for existing customers

  • None required

Regression tests

  • tests/integration/spend/test_partial_stream_live_budget.py and test_failure_spend_live_counters_chaos.py drive 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 422
    • A key budget, a team budget shared by two keys, a user budget across two keys, an end-user budget, a tag budget and a one-day budget_limits window
    • Six concurrent broken streams, provider-billed retries before a timeout, a native Anthropic /v1/messages stream and a Bedrock guardrail's cost on blocked requests
    • Twelve broken streams through a paused Redis on two workers. Each is logged once, the errors come back without waiting out the 5s Redis timeout, the key counter ends up with at least their full cost, and the budget holds on both workers and after one of them is killed
  • These cells pass on main and here: a stream that breaks before any chunk costs nothing, finished streams count once, and disable_spend_updates: true leaves the budget alone
  • Every integration cell passed 10 runs in a row at 2 integration workers
  • test_failure_spend_rows_raise_the_live_spend_counters_by_their_cost checks all nine counters for recovered stream cost, billed attempts and a zero-cost failure
  • test_failure_spend_rows_leave_the_live_spend_counters_alone_while_spend_updates_are_disabled covers disable_spend_updates
  • test_a_failing_spend_counter_store_is_still_sent_every_failure_spend_row and test_a_slow_spend_counter_store_lets_the_failure_out_and_raises_the_counters_once_it_answers cover a failing and a hung counter store
  • test_a_failure_spend_row_lands_in_the_key_budget_window_as_of_the_request_start and test_a_billed_attempt_on_a_deployment_the_router_dropped_debits_every_attributed_access_group cover budget windows and access groups
  • The new unit tests run the real spend writer and never read the clock
  • Mutation check, the unit tests kill 17 of 19 mutants of the fix. One survivor drops the Redis flush, and the integration test catches it. The other ignores the writer's charged flag, which the real writer always sets for failure rows

/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

  • Breaking: none found besides the declared changes above
  • Backward incompatible: none. ProxyDBLogger only gained keyword arguments with defaults
  • Driven live and the same on both sides
    • A stream that finishes counts the same
    • /v1/messages broken streams on an OpenAI model are billed as successes, and the key is refused at attempt 3 on both sides
    • /v1/responses broken streams record $0 on both sides, see Caveats
    • A paused Postgres changes nothing
  • Driven live and fixed here
    • Key and team budgets refuse attempt 3, where main served all four. A one-day window refuses attempt 3, where main refused attempt 4
    • Eight concurrent broken streams leave the key counter at the DB spend of $0.00352, where main left it at 0
    • Same at 4 workers
    • Without Redis at 1 worker the next request is refused. At 4 workers counters stay per worker, as they are for successes
  • Not verified live: the three double-charge paths above, A2A, MCP tool failures and Responses WebSocket rejected frames. They were traced on paper and none of them reaches the new code differently from a chat stream

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • /v1/responses broken streams record $0 recovered cost on main and here, so they still never count toward a budget
  • With disable_error_logs: true the failure hook returns before it records any recovered cost, so the gap stays there

Low

  • On an OpenAI model, a broken /v1/messages stream sometimes writes no spend row, on main and here alike. The request's max_tokens reservation then stays on the counter instead of the real cost
  • CircleCI runs tests/integration on main only, so the flush mutation is not caught on this PR's CI
  • CodeQL reports alert 9134 on hash_token in litellm/proxy/utils.py. That alert has been open on main since 2026-08-17 and this PR does not touch the file
  • image-scan fails on certifi 2026.4.22 (GHSA-6q48-6c7w-9gw2, fixed in 2026.10.19). Main's uv.lock pins the same version and other open PRs fail the same way

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

REVIEWER MUST KNOW BEFORE APPROVING

  • Failure spend now counts toward live budgets right away, including guardrail cost on blocked requests, provider-billed timeouts and retries, and budget_limits windows. Main counted it only after the counter was repaired from the DB about a minute later
  • On the three paths where main already charges the DB twice, the counters now carry the doubled amount right away. Fixing those double charges is left for follow-ups
  • During a Redis outage a broken stream's error reaches the client up to 1s later than on main
  • A cold counter seeded after a Redis stall longer than the DB flush can count the stalled failure rows twice, as it does for successes
  • Not yet approved by a reviewer

Devin Review


Note

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, _ProxyDBLogger increments key/team/user/org/tag/access-group counters via increment_spend_counters, flushes post-call Redis batches, and respects disable_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. ProxyDBLogger gains injectable spend_counters and failure_counter_wait_seconds for 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.

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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 2 potential issues.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +605 to +606
try:
await self._spend_counters()(

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

Comment on lines +541 to +545
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(

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

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@codspeed

codspeed Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 43 untouched benchmarks


Comparing litellm_partial_stream_live_budget_counters (68cb874) with main (24b8889)

Open in CodSpeed

@litereview

litereview Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: 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
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/proxy/hooks/proxy_track_cost_callback.py, litellm/proxy/proxy_server.py (a type annotation only), and tests under tests/integration/spend/ and tests/unit/proxy/hooks/. None of these files sit under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.

  • Passed · Compatibility requirements (required): No supported API, config key, default or persisted schema changes.

  • _ProxyDBLogger.__init__ gains two keyword parameters, and both have defaults.

  • _IncrementSpendCounters gains an optional project_id.

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 budget_limits windows. The PR description declares this under Behavior changes. It brings window counters in line with the key spend that DB already records. I judged it a budget-enforcement fix, not a compatibility break that needs a ! marker.

  • Passed · Changed behavior and result consistency (required): Standards I read: tests/integration/AGENTS.md and tests/integration/README.md. The new tests poll with eventually and use the owned wire server, which follows those guides.

Path I traced: async_post_call_failure_hook releases the reservation, then _failure_spend_rows builds the final row plus any billed earlier attempts. Next, _write_failure_spend_rows calls update_database for each row, and its returned charged flag decides which rows count. Only charged rows with cost above zero reach increment_spend_counters, which runs with budget_reservation=None because the reservation is already released. A per-row try isolates counter errors. flush_post_call_redis_batches then sends the batched writes, and the hook waits at most 1s before letting the task finish in the background. The background task's done-callback removes it from _pending_increments.

Boundary cases checked:

  • Zero-cost row: skipped.
  • disable_spend_updates: update_database returns True early, and the new gate skips the counters.
  • Batch-retrieve row the writer did not charge: the charged=False filter skips it.
  • Billed retry attempts: each row raises its own counter and access groups through debitable_model_access_groups.
  • Redis stall: covered by the chaos test.

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.

  • Passed · Unit tests: tests/unit/proxy/hooks/test_proxy_track_cost_callback.py (optional): .venv/bin/python -m pytest tests/unit/proxy/hooks/test_proxy_track_cost_callback.py -q: 133 passed.
  • Passed · Integration tests: partial-stream live budget and chaos (optional): Command: INTEGRATION_WORKERS=2 python tests/integration/run.py accounting tests/integration/spend/test_partial_stream_live_budget.py tests/integration/spend/test_failure_spend_live_counters_chaos.py.

Environment: local Postgres 15, redis-server and prisma generate, with the env vars that .circleci/scripts/run_integration.sh sets.

Result: 15 passed in 234s, none skipped. The run covered key, team, user, end-user, tag and window budgets, concurrent streams, billed retries, a /v1/messages stream, guardrail cost, a Redis stall across two workers and disable_spend_updates.


View review · Reviewed a8a18d600c7c

@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable findings

Summary

Charged failure rows now raise the live budget counters used to check later requests

  • Charged failure spend now raises the live counters used by budget checks.

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

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous 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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

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.

✅ 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
@yucheng-berri
yucheng-berri merged commit f4d1f45 into main Oct 30, 2026
116 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_partial_stream_live_budget_counters branch October 30, 2026 20:05
mateo-berri pushed a commit to izzybn/litellm that referenced this pull request Nov 24, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Recovered partial stream cost is released from live budget counters

2 participants