Repository navigation
fix(proxy): use current spend for virtual key soft budget alerts - #48355
Draft
tanishqbaweja wants to merge 3 commits into
Draft
tanishqbaweja wants to merge 3 commits into
tanishqbaweja wants to merge 3 commits into
Conversation
Contributor
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
proxy-infra-root failed on test_token_counter_loads_a_custom_tokenizer_off_the_event_loop, a timing-sensitive test that BerriAI#48458 made deterministic on main.
5 of 7 tasks
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Virtual keys now send a soft-budget alert after their spend crosses the threshold, including when another proxy records that spend. The check reads current spend and keeps soft budgets as warnings, so requests can continue
Details
TLDR
Problem this solves:
How it solves it:
User Flow
Before, a standalone key can exceed its soft budget without an alert
POST http://127.0.0.1:41479/key/generatewithsoft_budget: 0.01POST http://127.0.0.1:41479/v1/chat/completionsand wait for its spend to persistGET http://127.0.0.1:41479/key/infoshows spend above the budget, but the configured webhook receives no soft-budget messageAfter, the same key emits the missing warning on a later request
POST http://127.0.0.1:41479/key/generatewithsoft_budget: 0.01POST http://127.0.0.1:41479/v1/chat/completionsand wait for its spend to persistGET http://127.0.0.1:41479/key/infoshows spend above the budget, and the configured webhook receives one soft-budget messageRelevant issues
Fixes #35800
Root cause and change
virtual_key_soft_budget_checkcompared the threshold againstvalid_token.spend, which can remain stale in the auth cache while the spend counter advances. It now callsget_current_spendusing the key's counter and the cached value as the cold-cache fallback. The returned spend drives both the threshold comparison and the alert payloadThe helper receives no hard budget, so strict budget enforcement cannot turn this warning into a request rejection. An unset or zero soft budget still exits before reading the counter
Pre-Submission checklist
CI
On
9f6aaaf334ad3fbf523bd3b7e307bf4b4168acfb, unit tests, lint, smoke tests, cost-map guard and combined coverage pass. That commit is empty and only re-runs CI. The earlier proxy-infra-root failure was the tokenizer timing test, which #48458 made deterministic on main, and the rerun of that group passesOn
f8afcdc27d0, the corrected auth group passed all 291 tests with 54 warnings, and the downloaded coverage artifact for that commit covers all five changed executable linesThe OSV scan fails on the same 53 advisories as other open PRs against current main (for example #48708), mostly
pillowinuv.lock. This PR changes no dependency locks or scan settingsNo automated code review or maintainer feedback has appeared yet. Missing reviews are not counted as passes, and this remains a draft
Screenshots / Proof of Fix
The live checks use PostgreSQL, Redis, a real local Qwen3.5 0.8B model served by Ollama 0.40.11, and a local HTTP receiver for Slack-format messages. Test prices are configured at $0.001 per input token and $0.002 per output token. The proxy config enables Slack budget alerts with a 24-hour cooldown and the normal five-second batching interval
MASTER_KEYandVIRTUAL_KEYbelow replace temporary credentials. The verification record includes the drivers, exact commands, complete redacted responses, screenshots and source provenance. Both revisions serve the same production dashboard export, whose sources match the unchanged dashboard at the merge baseThe current tip
f8afcdc27d0ba7f9e2aef46521d1b7eca45d54bcadds authentication regression coverage to the recorded fix at8c0fe877b9bbfa0a6934d8ec9373fcaf029a2082. The follow-up source check confirms that production and dashboard files match the live-tested revisionBefore (dddbaa8)
Crossing a standalone key's soft budget
Create a key with no team or hard budget, and keep its returned value in
VIRTUAL_KEYHTTP 200,
soft_budget: 0.01,spend: 0,team_id: null,max_budget: nullSend these three real inference requests, waiting after the first until
GET /key/infoshows its spend persistedAll three return HTTP 200 with nonzero token usage
Read the final spend and wait beyond the five-second alert batching interval
Selected fields from the final HTTP 200 response
{ "spend": 0.105, "soft_budget": 0.01, "team_id": null, "max_budget": null }Read the local receiver after the 16-second wait
curl -sS --max-time 10 'http://127.0.0.1:41480/messages?alias=qa35800-api-crossed-by-request'{ "count": 0, "messages": [] }Alert controls
Repeat with an already-crossed key, a high soft budget, and no soft budget, using the recorded curl commands and responses
Delete all four owned keys, each deletion returns HTTP 200
Dashboard workflow
Open
http://127.0.0.1:41479/ui/?page=api-keys, select Create New Key, and create a standalone key. Open its Settings, choose Edit Settings, set Soft Budget (USD) to0.01, save, and reloadSend three real requests with that key, reload Overview, and confirm the recorded spend. Repeat using touch input at 390 × 844. The desktop and phone receiver counts are both 0
Raise the soft budget to
1000, save and reload to verify it. Delete the key through More key actions, Delete Key, type its alias to confirm, and submit. The row disappears and a request using the deleted key returns HTTP 401Inspect the desktop recording, phone recording, and request/readback report. The report checks preserved fields, persisted spend, alert counts, and revocation
After (8c0fe87)
Crossing a standalone key's soft budget
Create a key with no team or hard budget, and keep its returned value in
VIRTUAL_KEYHTTP 200,
soft_budget: 0.01,spend: 0,team_id: null,max_budget: nullSend these three real inference requests, waiting after the first until
GET /key/infoshows its spend persistedAll three return HTTP 200 with nonzero token usage
Read the final spend and wait beyond the five-second alert batching interval
Selected fields from the final HTTP 200 response
{ "spend": 0.105, "soft_budget": 0.01, "team_id": null, "max_budget": null }Read the local receiver after the 16-second wait
curl -sS --max-time 10 'http://127.0.0.1:41480/messages?alias=qa35800-api-crossed-by-request'{ "count": 1, "messages": [ { "received_at": "2026-10-25T22:19:10.144649+00:00", "body": { "text": "Alert type: `budget_alerts`\nLevel: `High`\nTimestamp: `22:19:05`\n\nMessage: Soft Budget Crossed: Total Soft Budget:`0.01`\n\n*spend:* `0.035`\n*soft_budget:* `0.01`\n*key_alias:* `qa35800-api-crossed-by-request`\n*event_group:* `key`\n\n\nProxy URL: `http://127.0.0.1:41479`" } } ] }Alert controls
Repeat with an already-crossed key, a high soft budget, and no soft budget, using the recorded curl commands and responses
Delete all four owned keys, each deletion returns HTTP 200
Dashboard workflow
Open
http://127.0.0.1:41479/ui/?page=api-keys, select Create New Key, and create a standalone key. Open its Settings, choose Edit Settings, set Soft Budget (USD) to0.01, save, and reloadSend three real requests with that key, reload Overview, and confirm the recorded spend. Repeat using touch input at 390 × 844. The desktop and phone receiver counts are both 1
Raise the soft budget to
1000, save and reload to verify it. Delete the key through More key actions, Delete Key, type its alias to confirm, and submit. The row disappears and a request using the deleted key returns HTTP 401Inspect the desktop recording, phone recording, and request/readback report. The report checks preserved fields, persisted spend, alert counts, and revocation
Tests run
The new regression fails four stale-spend unit cases on main. The cross-proxy integration also fails on main after three successful inference responses because its receiver gets no alert
The fixed working tree passes 892 unit tests across these files, with 76 warnings recorded in the log
The existing authentication regression now supplies the spend counter explicitly and verifies the complete delivered webhook while the request remains authorized. Its stale-spend case fails on unchanged main, while the current-spend control passes. The full authentication CI group passes 291 tests with 54 recorded warnings and no reruns, using these four files
Full
make format,make lintand committed-diff formatting pass again for this test updateThe real PostgreSQL/Redis integration selection passes three cases in
tests/integration/spend/test_key_budget_lockout.py, including the new two-proxy alert case and existing hard-budget lockout/recovery controls. The integration harness scripts only the external upstream response, while the separate live proof above uses actual inferenceAll seven deliberate mutations fail the new unit regression. They cover reading stale spend, sending stale spend, losing the threshold boundary, using the wrong counter, discarding the cold fallback, enforcing the warning as a hard limit, and enabling a zero threshold. The exact production source was restored and the seven focused cases passed again
The six selected key creation, edit, form-value and budget-display frontend files pass 292 tests with three existing expected failures. Production TypeScript passes.
make format, fullmake lint, and the committed-diff formatting check pass without increasing any budgets or adding suppressions. The existing test file's unrelated formatting was restored with its AST verified identicalThe final live runs make ten curl inference requests plus six browser-driven inference requests per revision. Desktop and touch-phone flows verify saved budget values, persisted spend, unchanged sibling fields, alert counts and deleted-key rejection. All 28 screenshots and eight sampled frames from each of the four recordings were visually inspected
Type
Bug fix
Caveats
Low
The visual inspection and browser comparison record those existing UI limitations and exact error counts. Dashboard source files are unchanged, and this verification reuses the existing production export
Final Attestation