Repository navigation
fix(proxy): release unclaimed budget reservations at request end - #42304
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…onciled_budget_reservation
| for metadata_variable_name in ("metadata", "litellm_metadata"): | ||
| metadata = litellm_params.get(metadata_variable_name) | ||
| if not isinstance(metadata, Mapping): | ||
| continue |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
…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.
| await authorize() | ||
| assert (await request.json())["model"] == target | ||
| assert get_client_requested_model(request) == "AgentX-LLM" | ||
|
|
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
This file already imports fastapi at line 18 on main; it tests litellm/proxy/auth, so the SDK boundary rule does not apply
There was a problem hiding this comment.
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.
Comments Outside DiffThese 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.
|
…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.
…onciled_budget_reservation
…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.
…onciled_budget_reservation # Conflicts: # litellm/proxy/proxy_server.py
…onciled_budget_reservation # Conflicts: # tests/test_litellm/litellm_core_utils/test_litellm_logging.py
|
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 3c1dc4d. Configure here.
TLDR
Problem this solves:
/key/infoshows near-zero spendHow it solves it:
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
max_budget: 0.05via POST https://litellm-domain/key/generate and get ansk-...key backpurpose: batch) and get afile-...ID backgpt-5.6-luna, HTTP 200, abatch_...ID comes back"status": "cancelling"Budget has been exceeded! ... Current cost: 0.05, Max budget: 0.05, and so do the ones 5 and 30 seconds later"spend": 7.4e-06, nowhere near the budgetAfter: the cancel's reservation is released the moment the cancel finishes, so the key keeps working until real spend reaches the budget
max_budget: 0.05via POST https://litellm-domain/key/generate and get ansk-...key backpurpose: batch) and get afile-...ID backgpt-5.6-luna, HTTP 200, abatch_...ID comes back"status": "cancelling""spend"growing by each chat's real cost, still well under the budgetRelevant 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
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@greptileaito 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-lunais real OpenAI. The only difference between the legs is the commit the proxies were booted from.$MASTER_KEYand$KEYare redacted, everything else is verbatimBefore (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)
create a budgeted key on A
upload the batch input on B
create the batch on A
a chat on B works before the cancel
cancel the batch on B
chats on A and B right after, 5s later, 30s later
the key's spend as the user sees it
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)
create a budgeted key on A
upload the batch input on B
create the batch on A
a chat on B works before the cancel
cancel the batch on B
chats on A and B right after, 5s later, 30s later
the key's spend as the user sees it
Live risk cells, same rig, both trees
One fresh key with
max_budget: 0.05per 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/infofigure 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 at0.05on the merge base, at the five chats' real cost on the tip0.04999999999999999, tip0.00003699999999998max_tokens: 0chat on A/v1/fileson A/openai/v1/chat/completionspass-through on A/openai/v1/chat/completionspass-through on B/key/infoon ALive PR risk
Merge base
b720909dac, tip3c1dc4d5e2. Everything under Regression risk was observed on the rig above, not reasonedBreaking: none. No route, response field, config key, env var, or exception changes.
budget_reservationnever reaches the wire:UserAPIKeyAuth.budget_reservationisexclude=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 extracallback_boundkey 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 inertBackward 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_boundkey (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 PRRegression risk: the table above. Two regressions were found in the PR's own earlier cuts and fixed before this tip. At
3a66693a84the 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 in8c283535a7by claiming at both of the chunk processor's success hand-offs, andtest_chunk_processor_claims_the_budget_reservation_before_handing_it_to_the_cost_callbackfails on either hand-off alone. At8c283535a7the 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 in273fa05e4bby 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 treesDependency 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), onUserAPIKeyAuth.budget_reservation, and onmetadata["user_api_key_budget_reservation"]; the three are the same object. Readers that decide with it: the async client wrapper (claims afterfunction_setup, hands back in itsexcept), the four pass-through claim sites, the Rust bridge'ssetupandfailure_handler,release_unbound_budget_reservationin the middleware (readscallback_bound), the cost callback's reconcile and the endpoint failure hook's release (both short-circuit onfinalized), #40322's lease renewal (readsfinalizedand the request task, nevercallback_bound), and realtime's ownfinallyrelease, which is idempotent with the middleware's throughfinalized. Copies that break identity, all pre-existing onmainand untouched here: the/responsesand/v1/messagesmid-stream fallbacks deep-copymetadatabefore the primary attempt,acreate_fileandaretrieve_batchdeep-copykwargsper deployment, and silent experiments shallow-copymetadataso 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 onmain. MCP routes shallow-copy the ASGI scope, which keeps the samestatedict, so their reservation is released like any otherNot 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
/responsesand/v1/messagesmid-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 syncclientwrapper never claims (decision 3); no proxy route reaches itCI at the tip: CircleCI pipeline 90029:
integrationgreen;build_and_testred only on jobs that are red onmainthe same way, plus one VCR flake inpass_through_unit_testingthat passed on the rerun from failed (each under Caveats). GitHub ActionUnit Testsgreen on the rerun of its one order flake. Required checks greenType
🐛 Bug Fix
Caveats (if any)
Medium
main, unchanged here:mid_stream_fallback_hop_kwargsdeep-copies the metadata buckets for the/responsesand/v1/messagesmid-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-8321Low
/key/infolags the Redis counter by a few requests on both trees: the batched spend write9a90adad32b,29792c45a9,8c283535a7,05b7d551aa,137c8416fb,273fa05e4b, andeadda9aae4(before atcc9970efbf) gave the same results as the legs shownmake checkon Python 3.14 regenerates_lazy_openapi_snapshot.jsondifferently from CI's 3.12; the local regeneration was discarded before every commit3c1dc4d5e2:integrationgreen;build_and_testred on five jobs that fail the same way onmainatb720909dac(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 12transform_inline/document_inlining/json_response_format_stream/drop_nested_paramstests),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 twotest_get_model_info_bedrock_*tests), ande2e_ui_testing(tip 2199204, main 2198876; no failing test, the mock server and proxy start steps fail).using_litellm_on_windowstimed out onmaininInstall Dependencies(main 2198868) and passed at the tip (2199223)pass_through_unit_testing(tip job 2199219) failed ontest_passthrough_logging_payload_for_a_route_no_provider_handler_claimswithupstream_receivedempty: 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 inmain'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 ateadda9aae4and on main 90023, 90021, and 89979); tracked as LIT-8320. The rerun from failed (workflow104b207c) passed it: job 2199440, 265 tests, 0 failuresUnit Tests(proxy-endpoints / Run tests, run 35677978854) failed once ontest_proxy_setting_endpoints.py::TestTeamAdminEditableTeamFieldsSetting::test_get_reports_the_stored_list_and_advertises_supported_fields(assert [] == ['tpm_limit'], 1 failed of 13,351, green onmainruns 35677379713 and 35677928592, green locally, nothing on this branch near proxy settings): an xdist order flake; the rerun of the failed job passedunit(job 2199444) failed on the fleet-wideassignment-floodtest again plustest_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'sconversesibling failed onmainpipeline 89979, and the tip's firstunitrun (2199189) passed it. Thelocal_testing_part1andllm_translation_testingreruns (jobs 2199441, 2199442) failed on exactly the same fleet-wide tests as before; thee2e_ui_testingrerun (2199443) was still running when this body was writtenDesign decisions
setupclaims on an asynchronous, non-internal call andfailure_handlerhands back on an asynchronous, non-internal failure. ItsLoggingSurfaceprotocol exposeslitellm_paramsas a read-onlyMapping[str, object]for that, so the bridge never sees the mutable dictis_internal_call) neither claim nor hand back, so an emulated inner step cannot steal or drop the outer request's claimMapping[str, object]at the middleware boundary and narrowed todictinsiderelease_unbound_budget_reservation, since the counter code mutates the reservation in placeNonethere and the middleware does nothinglitellm_paramsoff whatever logging object a caller hands in throughlitellm_logging_obj. Every realLoggingsets that attribute in__init__, and every proxy caller passes a realLogging(the MCP and guardrail callers type itLiteLLMLoggingObj | None), so the three xai realtime tests whose hand-rolledFakeLogginglacked it were given the attribute rather than the wrapper a defensivegetattrfor an object that never occurs in productionlitellm_params = {}instead of the pass-through claim tolerating a logging object without one, for the same reason as decision 12mainwas merged into the branch rather than rebased onto it, three times:137c8416fbbecause 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;eadda9aae4to resolve theproxy_server.pyimport 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 CircleCIunitjob's jev timeouts at273fa05e4bneeded; and3c1dc4d5e2to resolve thetest_litellm_logging.pyconflict with fix(logging): price terminal Responses stream events from their inner response #42385 (both sides kept, main's test first) and to pick up1dacb03ad9, which fixes theintegration-providersfal video test that failed ateadda9aae4. Those two hunks are the only hand-resolved ones_lazy_openapi_snapshot.jsonstays asmainhas it: the local regeneration under Python 3.14 differs from CI's 3.12 output byte for byte and would only churnFinal Attestation
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_boundon 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.BudgetReservationReleaseMiddlewareon the proxy releases any reservation still unbound when the HTTP response finishes or the WebSocket closes, viarelease_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 incore_helpersand 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.