Skip to content

fix(proxy): release unclaimed budget reservations at request end - #42304

Merged
mateo-berri merged 10 commits into
mainfrom
litellm_release_unreconciled_budget_reservation
Sep 22, 2026
Merged

mateo-berri merged 10 commits into
mainfrom
litellm_release_unreconciled_budget_reservation

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A budgeted key that cancels a batch gets 422 on every call after it
  • The cancel reserves budget at auth but never runs the cost callback that releases it
  • The counter stays pinned at the budget until its TTL while /key/info shows near-zero spend
  • Same hole for any LLM route whose handler never runs the cost callback (LIT-5478)

How it solves it:

  • Auth hands the reservation to the request state
  • The async client wrapper claims the reservation for its cost callback when a call starts and hands it back when the call fails
  • Pass-through claims it only once its cost callback is actually enqueued
  • A request-end middleware releases every reservation no callback claimed
  • Streaming and background callbacks keep settling the ones they claimed, after the response

User Flow

Before: a developer whose budgeted key cancels a batch cannot use that key again until the reservation expires, while the key's spend still reads near zero

  1. They create a key with max_budget: 0.05 via POST https://litellm-domain/key/generate and get an sk-... key back
  2. They upload a batch input with POST https://litellm-domain/v1/files (purpose: batch) and get a file-... ID back
  3. They start a batch with POST https://litellm-domain/v1/batches for gpt-5.6-luna, HTTP 200, a batch_... ID comes back
  4. They cancel it with POST https://litellm-domain/v1/batches/{batch_id}/cancel, HTTP 200, "status": "cancelling"
  5. Their next POST https://litellm-domain/v1/chat/completions with the same key fails with HTTP 422 Budget has been exceeded! ... Current cost: 0.05, Max budget: 0.05, and so do the ones 5 and 30 seconds later
  6. GET https://litellm-domain/key/info for that key shows "spend": 7.4e-06, nowhere near the budget

After: the cancel's reservation is released the moment the cancel finishes, so the key keeps working until real spend reaches the budget

  1. They create a key with max_budget: 0.05 via POST https://litellm-domain/key/generate and get an sk-... key back
  2. They upload a batch input with POST https://litellm-domain/v1/files (purpose: batch) and get a file-... ID back
  3. They start a batch with POST https://litellm-domain/v1/batches for gpt-5.6-luna, HTTP 200, a batch_... ID comes back
  4. They cancel it with POST https://litellm-domain/v1/batches/{batch_id}/cancel, HTTP 200, "status": "cancelling"
  5. Their next POST https://litellm-domain/v1/chat/completions with the same key returns HTTP 200 with a normal completion, and so do the ones 5 and 30 seconds later
  6. GET https://litellm-domain/key/info for that key shows "spend" growing by each chat's real cost, still well under the budget

Relevant issues

Related: #36718 closed the token-counting routes by name; this closes the class

Affected release

Linear ticket

Resolves LIT-7173

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

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

Both legs ran the same flow against the same rig: two proxy instances per leg, each booted with --num_workers 2, sharing one Postgres (litellm_lit7173) and one Redis (127.0.0.1:27315) so the reservation written through one instance is read back through the other, requests alternating between the two. gpt-5.6-luna is real OpenAI. The only difference between the legs is the commit the proxies were booted from. $MASTER_KEY and $KEY are redacted, everything else is verbatim

Before (b720909, the merge base)

instance A = http://127.0.0.1:27311, instance B = http://127.0.0.1:27312 (two proxies, 2 uvicorn workers each, one Postgres, one Redis)

  1. create a budgeted key on A

    [19:00:29] curl -X POST http://127.0.0.1:27311/key/generate -H 'Authorization: Bearer $MASTER_KEY' -d '{"max_budget": 0.05, "key_alias": "lit7173-main3"}'
    {"key_alias": "lit7173-main3", "spend": 0.0, "max_budget": 0.05, "key_name": "sk-...JbKQ"}
    
  2. upload the batch input on B

    [19:00:30] curl -X POST http://127.0.0.1:27312/v1/files -H 'Authorization: Bearer $KEY' -F purpose=batch -F file=@batch.jsonl
    {"id":"file-18NVXpCpR7pJ9GPVfq1vG3","bytes":208,"created_at":1790042430,"filename":"batch.jsonl","object":"file","purpose":"batch","status":"processed","expires_at":1792634430,"status_details":null}
    HTTP 200 in 0.888474s
    
  3. create the batch on A

    [19:00:31] curl -X POST http://127.0.0.1:27311/v1/batches -H 'Authorization: Bearer $KEY' -d '{"input_file_id": "file-18NVXpCpR7pJ9GPVfq1vG3", "endpoint": "/v1/chat/completions", "completion_window": "24h", "model": "gpt-5.6-luna"}'
    {"id":"batch_bGl0ZWxsbTpiYXRjaF82YWIxZTEzZjc2Nzg4MTkwYmRlM2Y2NThlNmFkM2Y5Zjttb2RlbCxncHQtNS42LWx1bmE","completion_window":"24h","created_at":1790042431,"endpoint":"/v1/chat/completions","input_file_id":"file-bGl0ZWxsbTpmaWxlLTE4TlZYcENwUjdwSjlHUFZmcTF2RzM7bW9kZWwsZ3B0LTUuNi1sdW5h","object":"batch","status":"validating","cancelled_at":null,"cancelling_at":null,"completed_at":null,"error_file_id":nu
    HTTP 200 in 0.528367s
    
  4. a chat on B works before the cancel

    [19:00:31] curl -X POST http://127.0.0.1:27312/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # before the cancel
    {"id":"chatcmpl-EQk649oJtg2a425rKoFi9P1GXeKNb","created":1790042432,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 1.177648s
    
  5. cancel the batch on B

    [19:00:32] curl -X POST http://127.0.0.1:27312/v1/batches/batch_bGl0ZWxsbTpiYXRjaF82YWIxZTEzZjc2Nzg4MTkwYmRlM2Y2NThlNmFkM2Y5Zjttb2RlbCxncHQtNS42LWx1bmE/cancel -H 'Authorization: Bearer $KEY'
    {"id":"batch_bGl0ZWxsbTpiYXRjaF82YWIxZTEzZjc2Nzg4MTkwYmRlM2Y2NThlNmFkM2Y5Zjttb2RlbCxncHQtNS42LWx1bmE","completion_window":"24h","created_at":1790042431,"endpoint":"/v1/chat/completions","input_file_id":"file-bGl0ZWxsbTpmaWxlLTE4TlZYcENwUjdwSjlHUFZmcTF2RzM7bW9kZWwsZ3B0LTUuNi1sdW5h","object":"batch","
    HTTP 200 in 0.675023s
    
  6. chats on A and B right after, 5s later, 30s later

    [19:00:33] curl -X POST http://127.0.0.1:27311/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # right after the cancel, on A
    {"error":{"message":"Budget has been exceeded! Key=89846fbfb694ce112196823a8e4c5a4085f1793a3779e7461a69826a7adb4a3f Current cost: 0.05002679999999999, Max budget: 0.05","type":"budget_exceeded","param":null,"code":"422"}}
    HTTP 422 in 0.231664s
    [19:00:33] curl -X POST http://127.0.0.1:27312/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # right after the cancel, on B
    {"error":{"message":"Budget has been exceeded! Key=89846fbfb694ce112196823a8e4c5a4085f1793a3779e7461a69826a7adb4a3f Current cost: 0.05002679999999999, Max budget: 0.05","type":"budget_exceeded","param":null,"code":"422"}}
    HTTP 422 in 0.030933s
    [19:00:39] curl -X POST http://127.0.0.1:27311/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # 5s later, on A
    {"error":{"message":"Budget has been exceeded! Key=89846fbfb694ce112196823a8e4c5a4085f1793a3779e7461a69826a7adb4a3f Current cost: 0.05002679999999999, Max budget: 0.05","type":"budget_exceeded","param":null,"code":"422"}}
    HTTP 422 in 0.133208s
    [19:01:04] curl -X POST http://127.0.0.1:27312/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # 30s later, on B
    {"error":{"message":"Budget has been exceeded! Key=89846fbfb694ce112196823a8e4c5a4085f1793a3779e7461a69826a7adb4a3f Current cost: 0.05002679999999999, Max budget: 0.05","type":"budget_exceeded","param":null,"code":"422"}}
    HTTP 422 in 0.037837s
    
  7. the key's spend as the user sees it

    [19:01:04] curl http://127.0.0.1:27311/key/info -H 'Authorization: Bearer $KEY'
    {"key_alias": "lit7173-main3", "spend": 7.399999999999999e-06, "max_budget": 0.05}
    

After (3c1dc4d)

instance A = http://127.0.0.1:27313, instance B = http://127.0.0.1:27314 (two proxies, 2 uvicorn workers each, one Postgres, one Redis)

  1. create a budgeted key on A

    [19:04:09] curl -X POST http://127.0.0.1:27313/key/generate -H 'Authorization: Bearer $MASTER_KEY' -d '{"max_budget": 0.05, "key_alias": "lit7173-after9"}'
    {"key_alias": "lit7173-after9", "spend": 0.0, "max_budget": 0.05, "key_name": "sk-...sf4Q"}
    
  2. upload the batch input on B

    [19:04:10] curl -X POST http://127.0.0.1:27314/v1/files -H 'Authorization: Bearer $KEY' -F purpose=batch -F file=@batch.jsonl
    {"id":"file-7VcpGS4Fcsr8dbvY7wsiL2","bytes":208,"created_at":1790042651,"filename":"batch.jsonl","object":"file","purpose":"batch","status":"processed","expires_at":1792634651,"status_details":null}
    HTTP 200 in 1.599860s
    
  3. create the batch on A

    [19:04:11] curl -X POST http://127.0.0.1:27313/v1/batches -H 'Authorization: Bearer $KEY' -d '{"input_file_id": "file-7VcpGS4Fcsr8dbvY7wsiL2", "endpoint": "/v1/chat/completions", "completion_window": "24h", "model": "gpt-5.6-luna"}'
    {"id":"batch_bGl0ZWxsbTpiYXRjaF82YWIxZTIxYzY1Mjg4MTkwYjMyNDc0Yjc3ZWZmMmY2ZTttb2RlbCxncHQtNS42LWx1bmE","completion_window":"24h","created_at":1790042652,"endpoint":"/v1/chat/completions","input_file_id":"file-bGl0ZWxsbTpmaWxlLTdWY3BHUzRGY3NyOGRidlk3d3NpTDI7bW9kZWwsZ3B0LTUuNi1sdW5h","object":"batch","status":"validating","cancelled_at":null,"cancelling_at":null,"completed_at":null,"error_file_id":nu
    HTTP 200 in 1.172449s
    
  4. a chat on B works before the cancel

    [19:04:13] curl -X POST http://127.0.0.1:27314/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # before the cancel
    {"id":"chatcmpl-EQk9db48EVnW7fM0F7KuGpYBrOvyA","created":1790042653,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 1.318088s
    
  5. cancel the batch on B

    [19:04:14] curl -X POST http://127.0.0.1:27314/v1/batches/batch_bGl0ZWxsbTpiYXRjaF82YWIxZTIxYzY1Mjg4MTkwYjMyNDc0Yjc3ZWZmMmY2ZTttb2RlbCxncHQtNS42LWx1bmE/cancel -H 'Authorization: Bearer $KEY'
    {"id":"batch_bGl0ZWxsbTpiYXRjaF82YWIxZTIxYzY1Mjg4MTkwYjMyNDc0Yjc3ZWZmMmY2ZTttb2RlbCxncHQtNS42LWx1bmE","completion_window":"24h","created_at":1790042652,"endpoint":"/v1/chat/completions","input_file_id":"file-bGl0ZWxsbTpmaWxlLTdWY3BHUzRGY3NyOGRidlk3d3NpTDI7bW9kZWwsZ3B0LTUuNi1sdW5h","object":"batch","
    HTTP 200 in 0.602826s
    
  6. chats on A and B right after, 5s later, 30s later

    [19:04:15] curl -X POST http://127.0.0.1:27313/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # right after the cancel, on A
    {"id":"chatcmpl-EQk9fQCcJVNa6AJuHBM05qdgYJdhS","created":1790042655,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 0.959413s
    [19:04:16] curl -X POST http://127.0.0.1:27314/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # right after the cancel, on B
    {"id":"chatcmpl-EQk9gyFwARQF8GlzdLnLd4b9dWY0f","created":1790042656,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 0.992932s
    [19:04:22] curl -X POST http://127.0.0.1:27313/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # 5s later, on A
    {"id":"chatcmpl-EQk9mJzJTKgWtgxUMTbgiepidM9N4","created":1790042662,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 0.824521s
    [19:04:48] curl -X POST http://127.0.0.1:27314/v1/chat/completions -H 'Authorization: Bearer $KEY' -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Reply with the single word: pong"}], "max_tokens": 20}'   # 30s later, on B
    {"id":"chatcmpl-EQkADYZs1hPOxdRxDuGs37lsrM2lb","created":1790042689,"model":"gpt-5.6-luna","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"pong","role":"assistant","provider_specific_fields":{"refusal":null},"annotations":[]},"provider_specific_fields":{}}],"usage":{"completion_tokens":4,"prompt_tokens":13,"total_tokens":17,"completion_tokens_details":
    HTTP 200 in 1.385763s
    
  7. the key's spend as the user sees it

    [19:04:49] curl http://127.0.0.1:27313/key/info -H 'Authorization: Bearer $KEY'
    {"key_alias": "lit7173-after9", "spend": 2.959999999999999e-05, "max_budget": 0.05}
    

Live risk cells, same rig, both trees

One fresh key with max_budget: 0.05 per tree, requests alternating between A and B, the key's Redis counter (spend:key:<hash>, the value the budget check reads) read right after each cell. Every status, SSE line count, and counter value was identical on the merge base and the tip; only the /key/info figure differs, and that is the batched Postgres spend write lagging the counter by a few requests on both trees, unrelated to this PR. Cell 0 reads the counter the flow above left behind: pinned at 0.05 on the merge base, at the five chats' real cost on the tip

Cell Request Result on both trees Counter after
0 fresh budgeted key, read the flow key's counter merge base 0.04999999999999999, tip 0.00003699999999998 (the flow key)
1 non-streaming chat on A HTTP 200 0.0000074
2 streaming chat on B 4 SSE lines 0.0000148
3 max_tokens: 0 chat on A HTTP 400 from OpenAI unchanged
4 unknown model on B HTTP 400 before any provider call unchanged
5 five concurrent chats across A and B 5 x HTTP 200 0.0000518
6 GET /v1/files on A HTTP 200 unchanged
7 streaming /openai/v1/chat/completions pass-through on A 4 SSE lines 0.000053
8 non-streaming /openai/v1/chat/completions pass-through on B HTTP 200 0.0000604
9 GET /key/info on A HTTP 200 0.0000604

Live PR risk

Merge base b720909dac, tip 3c1dc4d5e2. Everything under Regression risk was observed on the rig above, not reasoned

Breaking: none. No route, response field, config key, env var, or exception changes. budget_reservation never reaches the wire: UserAPIKeyAuth.budget_reservation is exclude=True, the spend-log metadata allowlist does not carry it, and the standard logging payload strips it. The one place it is serialized outward, the offloaded spend event, now carries the extra callback_bound key next to the existing ones, and the counter update that consumes that event reads its keys by name (finalized, entries, reserved_cost), so the extra key is inert

Backward incompatible: none in wire or config. The behavior change is the fix itself: a reservation no callback claims is released when the response ends instead of expiring at its TTL. A reservation dict without the new callback_bound key (there is no persisted reservation, so only a hand-built one) is treated as unclaimed and released, which is the release every reservation got before this PR

Regression risk: the table above. Two regressions were found in the PR's own earlier cuts and fixed before this tip. At 3a66693a84 the SSE pass-through chunk processor handed its cost callback to the logging worker after the response and never claimed the reservation, so the middleware released it at response end and the key was unguarded until the worker drained; fixed in 8c283535a7 by claiming at both of the chunk processor's success hand-offs, and test_chunk_processor_claims_the_budget_reservation_before_handing_it_to_the_cost_callback fails on either hand-off alone. At 8c283535a7 the pass-through claim was stamped before the enqueue, so an enqueue that raised (a full logging queue) left the reservation claimed with no callback to settle it, pinning the budget until the TTL; fixed in 273fa05e4b by stamping the claim only after the enqueue returned, with two regression tests that fail on the old order. Cells 7 and 8 drive both pass-through routes on a real provider on both trees

Dependency graph of the reservation dict. Producer: reserve_budget_for_request, called from one auth exit that stamps it on the request state (or the socket state, shared with the synthetic auth request for websocket routes), on UserAPIKeyAuth.budget_reservation, and on metadata["user_api_key_budget_reservation"]; the three are the same object. Readers that decide with it: the async client wrapper (claims after function_setup, hands back in its except), the four pass-through claim sites, the Rust bridge's setup and failure_handler, release_unbound_budget_reservation in the middleware (reads callback_bound), the cost callback's reconcile and the endpoint failure hook's release (both short-circuit on finalized), #40322's lease renewal (reads finalized and the request task, never callback_bound), and realtime's own finally release, which is idempotent with the middleware's through finalized. Copies that break identity, all pre-existing on main and untouched here: the /responses and /v1/messages mid-stream fallbacks deep-copy metadata before the primary attempt, acreate_file and aretrieve_batch deep-copy kwargs per deployment, and silent experiments shallow-copy metadata so the experiment shares the live dict. In every copy case the live dict is what the middleware sees; a wrapper on the primary attempt has claimed it, so the middleware leaves it alone and the copy settles through its own callback exactly as on main. MCP routes shallow-copy the ASGI scope, which keeps the same state dict, so their reservation is released like any other

Not verified live: websocket routes (realtime, Vertex live, the Deepgram and OpenAI pass-through sockets) are covered by the middleware's websocket test and the pass-through socket's claim, not by a socket driven on the rig, since the rig has no realtime deployment. The Rust bridge mirror is covered by its unit tests only. The /responses and /v1/messages mid-stream fallback replay was not driven, since it needs a provider that fails mid-stream behind a configured fallback, so the pre-existing double settle of the deep-copied reservation on that path is reported under Caveats rather than measured. The sync client wrapper never claims (decision 3); no proxy route reaches it

CI at the tip: CircleCI pipeline 90029: integration green; build_and_test red only on jobs that are red on main the same way, plus one VCR flake in pass_through_unit_testing that passed on the rerun from failed (each under Caveats). GitHub Action Unit Tests green on the rerun of its one order flake. Required checks green

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Pre-existing on main, unchanged here: mid_stream_fallback_hop_kwargs deep-copies the metadata buckets for the /responses and /v1/messages mid-stream fallback, so the copied reservation settles once more through the fallback attempt's callback. Out of this PR's scope (it is the router's hop copy, not the release path), tracked as LIT-8321
    • Not driven live: needs a provider that fails mid-stream behind a configured fallback

Low

  • Cell 7's streaming pass-through settles at a lower cost than cell 2, on both trees: pre-existing pass-through cost accounting
  • /key/info lags the Redis counter by a few requests on both trees: the batched spend write
  • The two legs ran one after the other, not concurrently
  • Cancel bodies are cut at 300 chars in the logs
  • Earlier legs at 9a90adad32b, 29792c45a9, 8c283535a7, 05b7d551aa, 137c8416fb, 273fa05e4b, and eadda9aae4 (before at cc9970efbf) gave the same results as the legs shown
  • Local make check on Python 3.14 regenerates _lazy_openapi_snapshot.json differently from CI's 3.12; the local regeneration was discarded before every commit
  • CircleCI pipeline 90029 at 3c1dc4d5e2: integration green; build_and_test red on five jobs that fail the same way on main at b720909dac (pipeline 90023) and on pipelines 90021 and 89979, so none of them is this branch's: llm_translation_testing (tip job 2199187, main 2198871; the 12 transform_inline / document_inlining / json_response_format_stream / drop_nested_params tests), unit (tip 2199189, main 2198895; test_scan_message_stays_linear_on_adversarial_credential_lines[assignment-flood] over its 10s bound), local_testing_part1 (tip 2199215, main 2198903; the two test_get_model_info_bedrock_* tests), and e2e_ui_testing (tip 2199204, main 2198876; no failing test, the mock server and proxy start steps fail). using_litellm_on_windows timed out on main in Install Dependencies (main 2198868) and passed at the tip (2199223)
  • pass_through_unit_testing (tip job 2199219) failed on test_passthrough_logging_payload_for_a_route_no_provider_handler_claims with upstream_received empty: the shared VCR cassette replayed a response recorded at the same ephemeral port on an earlier run ([VCR HIT] played=1 entries=50), so the test's local server never saw the request. Test-infra flake in main's test, not this branch's (the branch's pass-through diff only binds the reservation after the success-handler enqueue, after the upstream call; the same test was green at eadda9aae4 and on main 90023, 90021, and 89979); tracked as LIT-8320. The rerun from failed (workflow 104b207c) passed it: job 2199440, 265 tests, 0 failures
  • GitHub Action Unit Tests (proxy-endpoints / Run tests, run 35677978854) failed once on test_proxy_setting_endpoints.py::TestTeamAdminEditableTeamFieldsSetting::test_get_reports_the_stored_list_and_advertises_supported_fields (assert [] == ['tpm_limit'], 1 failed of 13,351, green on main runs 35677379713 and 35677928592, green locally, nothing on this branch near proxy settings): an xdist order flake; the rerun of the failed job passed
  • On that same rerun unit (job 2199444) failed on the fleet-wide assignment-flood test again plus test_invoke_stream_collector_keeps_usage_without_retaining_the_stream (assert 334147 < 925127 // 4, a memory-retention bound measured on the CI runner): its file, tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.py, is untouched by this branch, the same assertion's converse sibling failed on main pipeline 89979, and the tip's first unit run (2199189) passed it. The local_testing_part1 and llm_translation_testing reruns (jobs 2199441, 2199442) failed on exactly the same fleet-wide tests as before; the e2e_ui_testing rerun (2199443) was still running when this body was written

Design decisions

  1. A reservation is claimed by the async client wrapper right after its logging setup, which runs before every path that schedules a success handler on that logging object (normal dispatch, cache hit, stream end, the embedding rebuild, the Rust bridge), and the wrapper's except block hands it back so the endpoint failure hook or the request-end release settles it. A retry re-enters the wrapper and claims it again. The first cut claimed it wherever a logging object merely saw the reservation, and the after leg still returned 422: the proxy's pre-call setup builds a logging object for every route, including the batch cancel that has no wrapper and never runs a callback
  2. Claiming only when a callback reconciles was rejected because success callbacks run after the response, so almost every non-streaming reservation would have been released first. Adding a failure event to the cost callback was rejected because router retries fire it on intermediate failures and would release a reservation the winning attempt still settles
  3. The sync client wrapper never claims: the cost callback is async only, so a sync call's reservation stays with the request-end release
  4. Pass-through claims the reservation at each of its success-handler hand-offs: the non-streaming enqueue, the raw byte relay, the websocket session, and the SSE chunk processor's two end-of-stream hand-offs (the immediate enqueue and the coroutine parked for deferred dispatch behind post-call guardrails). An upstream 4xx or 5xx never enqueues, so the reservation stays unclaimed and the middleware releases it. The chunk processor was missed in the first cut and found by the dependency walk above: its callback runs on the logging worker after the response, so the middleware would have released the reservation first and left the key unguarded until the worker drained
  5. The Rust bridge mirrors the wrapper: setup claims on an asynchronous, non-internal call and failure_handler hands back on an asynchronous, non-internal failure. Its LoggingSurface protocol exposes litellm_params as a read-only Mapping[str, object] for that, so the bridge never sees the mutable dict
  6. Internal calls (is_internal_call) neither claim nor hand back, so an emulated inner step cannot steal or drop the outer request's claim
  7. The release runs once per request from a pure ASGI middleware sitting inside the in-flight counter, so it fires on success, on an exception, and on a client disconnect alike. Hanging it off each handler family (batches, files, fine-tuning) was rejected because the ticket's point is the class, not the named routes
  8. The release callback is typed Mapping[str, object] at the middleware boundary and narrowed to dict inside release_unbound_budget_reservation, since the counter code mutates the reservation in place
  9. The auth helper now has one exit that always stamps the request state, so a request that skips budget checks leaves None there and the middleware does nothing
  10. The two QA legs ran one after the other on the same Postgres and Redis rather than concurrently, because the machine was already at its memory ceiling with other runs
  11. WebSocket sessions (realtime, Vertex live, Responses API, the Deepgram and OpenAI pass-through sockets) are covered the same way, after Greptile's review pointed out they were not: their auth builds a synthetic HTTP request, and that request now shares the socket's own state dict instead of a throwaway one, so whatever auth stamps is on the socket the middleware sees. The middleware runs its release for websocket scopes too, once the socket handler returns. A realtime call goes through the async client wrapper and claims like any other call, the pass-through socket claims right before its success handler, and a socket that closes early (no provider key, a refused session, an unpriced model) never claims, so the middleware releases it
  12. The wrapper reads litellm_params off whatever logging object a caller hands in through litellm_logging_obj. Every real Logging sets that attribute in __init__, and every proxy caller passes a real Logging (the MCP and guardrail callers type it LiteLLMLoggingObj | None), so the three xai realtime tests whose hand-rolled FakeLogging lacked it were given the attribute rather than the wrapper a defensive getattr for an object that never occurs in production
  13. The pass-through claim is stamped only after the success handler's enqueue returned, never before. The SDK wrapper and the Rust bridge already hand the claim back in their failure paths, and the chunk processor's deferred-dispatch parking is a plain assignment that cannot raise, so the enqueue is the only hand-off that can fail after a claim. Greptile's review found the old order
  14. The vertex streaming test doubles were given a real litellm_params = {} instead of the pass-through claim tolerating a logging object without one, for the same reason as decision 12
  15. main was merged into the branch rather than rebased onto it, three times: 137c8416fb because the lint workflow from refactor(mcp): extract explicit operation context and dispatch #42292 runs against the PR head and needs its MCP boundary files present; eadda9aae4 to resolve the proxy_server.py import conflict with fix(proxy): record aborted outcome when spend-log cleanup is cancelled at shutdown #41213 and to pick up fix(logging_worker): make flush() survive an event loop change #42355, whose logging-worker flush fix is what the CircleCI unit job's jev timeouts at 273fa05e4b needed; and 3c1dc4d5e2 to resolve the test_litellm_logging.py conflict with fix(logging): price terminal Responses stream events from their inner response #42385 (both sides kept, main's test first) and to pick up 1dacb03ad9, which fixes the integration-providers fal video test that failed at eadda9aae4. Those two hunks are the only hand-resolved ones
  16. _lazy_openapi_snapshot.json stays as main has it: the local regeneration under Python 3.14 differs from CI's 3.12 output byte for byte and would only churn

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

Note

Medium Risk
Changes budget counter lifecycle on every authenticated HTTP/WebSocket request; incorrect bind/unbind timing could release reservations early or leave counters pinned, though extensive tests cover pass-through enqueue ordering and middleware edge cases.

Overview
Fixes budgeted API keys getting stuck at max spend when auth reserves budget but no cost callback ever runs (e.g. batch cancel, file-only routes).

Auth now always stores the reservation on request/socket state. New callback_bound on each reservation marks ownership: the async client wrapper, Rust bridge, and pass-through paths bind only when a success/cost handler is actually scheduled (pass-through after enqueue succeeds), and unbind on async failures so request-end cleanup can run.

BudgetReservationReleaseMiddleware on the proxy releases any reservation still unbound when the HTTP response finishes or the WebSocket closes, via release_unbound_budget_reservation. Bound reservations are left for existing reconcile/release in cost callbacks (including after streaming).

Shared helpers budget_reservation_from_metadata / bind-unbind live in core_helpers and replace duplicate metadata lookup in the cost tracker.

Reviewed by Cursor Bugbot for commit 3c1dc4d. Bugbot is set up for automated code reviews on this repo. Configure here.

@devin-ai-integration

devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_release_unreconciled_budget_reservation (3c1dc4d) with main (b833e1f)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding blocking or non-blocking defect remains in the reviewed changes.

Findings

  1. P2 Shared Reservation Is Mutated ▶
  2. P2 FastAPI Import Boundary Violated ▶

Summary

This PR adds request-lifecycle ownership for budget reservations so reservations not claimed by cost callbacks are released when HTTP or WebSocket work ends, while callback-owned streaming and background work remains responsible for reconciliation.

  • Auth propagates the reservation into ASGI request or socket state.
  • Async model and pass-through paths mark reservations as callback-owned only when terminal logging is scheduled.
  • Failure paths return ownership to request-end cleanup.
  • Middleware releases unclaimed reservations after success, exceptions, or connection closure.
  • Tests cover ordinary responses, failures, WebSockets, streaming completion, enqueue failures, and shared reservation state.

Reviews (10) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.64865% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/rust_bridge/callbacks_legacy_python.py 90.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

for metadata_variable_name in ("metadata", "litellm_metadata"):
metadata = litellm_params.get(metadata_variable_name)
if not isinstance(metadata, Mapping):
continue

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.

P2 Shared Reservation Is Mutated

This assignment mutates the shared reservation dictionary in place, violating the repository's no-mutation directive. This requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

The reservation is a shared mutable record by design. reconcile_budget_reservation on main already stamps finalized in place, and every holder must see the claim

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.

You're right. In this design the reservation is intentionally a shared mutable record: reconcile_budget_reservation already updates it in place, and all holders must observe the same callback_bound state. The assignment here is therefore the required synchronization mechanism, not an unintended mutation. I’m withdrawing this finding; no change is needed.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…fore its cost callback

The SSE chunk processor hands its success handler to the logging worker
after the response, so the request-end release freed the reservation
first and left the key unguarded until the worker drained. Claim it at
both end-of-stream hand-offs, the immediate enqueue and the coroutine
parked for deferred dispatch.

Give the xai realtime test double the litellm_params attribute every
real Logging object carries, since the wrapper now reads it.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

await authorize()
assert (await request.json())["model"] == target
assert get_client_requested_model(request) == "AgentX-LLM"

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.

P2 FastAPI Import Boundary Violated

This new test imports Request from FastAPI outside the litellm/proxy/ package, violating the repository directive that FastAPI imports must remain inside that package. The newly added tests at lines 9098 and 9122 repeat this pattern for Request and WebSocket. Use the equivalent Starlette types instead; this repository requirement must be satisfied before merging.

Rule Used: What: Do not allow fastapi imports on files outside of the proxy/ folder Why: Fastapi is a proxy dependency, not an SDK one Example of what BAD looks like: File: litellm/litellm/integrations/custom_guardrail.py ``` from fastapi.exceptions impo... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

This file already imports fastapi at line 18 on main; it tests litellm/proxy/auth, so the SDK boundary rule does not apply

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.

You're right. This is an existing proxy-auth test module that already imports fastapi at the module level, and the new Request/WebSocket imports only construct framework objects for proxy tests. The SDK boundary concern does not apply here, so my previous comment was incorrect and can be disregarded.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.

  • P1 Failed Dispatch Pins Budget litellm/proxy/pass_through_endpoints/streaming_handler.py:255 ▶

    The reservation is marked as owned by the callback before the callback is enqueued. If enqueueing raises, the exception is caught but the ownership claim remains. The callback therefore never reconciles the reservation, and request-end cleanup skips it because callback_bound is still true, leaving the caller's budget pinned until the reservation expires. Unbind the reservation in the exception path or claim it only after dispatch succeeds.

…params dict

The spec'd Logging mocks in test_vertex_ai_anthropic_streaming_cost_injection.py
lacked the instance attribute the chunk processor now reads to claim the budget
reservation. Also restores main's _lazy_openapi_snapshot.json: the branch's copy
had been regenerated under Python 3.14, which dedents one docstring description
that the CI regeneration on Python 3.12 keeps indented, and the PR adds no lazily
loaded route, so main's file is the correct one.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…allback is enqueued

Every pass-through success hand-off stamped callback_bound before handing the
coroutine to the logging worker. When that enqueue raised, the reservation stayed
claimed with no callback left to reconcile it, so the request-end release skipped it
and the reserved cost stayed pinned on the key's counter. Enqueue first, then claim,
so a failed hand-off leaves the reservation for the request-end release.
@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 22, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…onciled_budget_reservation

# Conflicts:
#	litellm/proxy/proxy_server.py
@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 22, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…onciled_budget_reservation

# Conflicts:
#	tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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 3c1dc4d. Configure here.

@mateo-berri mateo-berri 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.

LGTM

@mateo-berri
mateo-berri merged commit e7cd97c into main Sep 22, 2026
183 of 191 checks passed
@mateo-berri
mateo-berri deleted the litellm_release_unreconciled_budget_reservation branch September 22, 2026 02:51

This branch had an error being deployed

1 failed deployment
e2e-changed — 3c1dc4d5 Deployed Sep 22, 2026 by mateo-berri via oauth #253
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant