Skip to content

fix(proxy): use current spend for virtual key soft budget alerts - #48355

Draft
tanishqbaweja wants to merge 3 commits into
BerriAI:mainfrom
tanishqbaweja:litellm_fix_35800_soft_budget_spend
Draft

tanishqbaweja wants to merge 3 commits into
BerriAI:mainfrom
tanishqbaweja:litellm_fix_35800_soft_budget_spend

Conversation

@tanishqbaweja

@tanishqbaweja tanishqbaweja commented Oct 25, 2026 •

Copy link
Copy Markdown

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:

  • Cached key spend can hide a crossed soft budget

How it solves it:

  • Read current spend from the existing shared counter
  • Include that spend in the alert payload
  • Cover stale caches, boundary values, and cross-proxy spending

User Flow

Before, a standalone key can exceed its soft budget without an alert

  1. Enable budget alerts and create a key using POST http://127.0.0.1:41479/key/generate with soft_budget: 0.01
  2. Send a request that incurs spend to POST http://127.0.0.1:41479/v1/chat/completions and wait for its spend to persist
  3. Send two more requests, which both return HTTP 200
  4. GET http://127.0.0.1:41479/key/info shows spend above the budget, but the configured webhook receives no soft-budget message

After, the same key emits the missing warning on a later request

  1. Enable budget alerts and create a key using POST http://127.0.0.1:41479/key/generate with soft_budget: 0.01
  2. Send a request that incurs spend to POST http://127.0.0.1:41479/v1/chat/completions and wait for its spend to persist
  3. Send two more requests, which both return HTTP 200
  4. GET http://127.0.0.1:41479/key/info shows spend above the budget, and the configured webhook receives one soft-budget message

Relevant issues

Fixes #35800

Root cause and change

virtual_key_soft_budget_check compared the threshold against valid_token.spend, which can remain stale in the auth cache while the spend counter advances. It now calls get_current_spend using the key's counter and the cached value as the cold-cache fallback. The returned spend drives both the threshold comparison and the alert payload

The 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

  • I have added meaningful tests
  • The selected backend and frontend test files pass locally
  • My PR passes all required CI/CD checks
  • My PR only solves one specific problem
  • Every available automated review has finished and findings are addressed

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 passes

On 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 lines

The OSV scan fails on the same 53 advisories as other open PRs against current main (for example #48708), mostly pillow in uv.lock. This PR changes no dependency locks or scan settings

No 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_KEY and VIRTUAL_KEY below 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 base

The current tip f8afcdc27d0ba7f9e2aef46521d1b7eca45d54bc adds authentication regression coverage to the recorded fix at 8c0fe877b9bbfa0a6934d8ec9373fcaf029a2082. The follow-up source check confirms that production and dashboard files match the live-tested revision

Before (dddbaa8)

Crossing a standalone key's soft budget

  1. Create a key with no team or hard budget, and keep its returned value in VIRTUAL_KEY

    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/key/generate -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' --data-raw '{"key_alias": "qa35800-api-crossed-by-request", "models": ["qa-alert-model"], "soft_budget": 0.01, "spend": 0.0}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    HTTP 200, soft_budget: 0.01, spend: 0, team_id: null, max_budget: null

  2. Send these three real inference requests, waiting after the first until GET /key/info shows its spend persisted

    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 1"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '
    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 2"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '
    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 3"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    All three return HTTP 200 with nonzero token usage

  3. Read the final spend and wait beyond the five-second alert batching interval

    curl -sS --max-time 120 -X GET http://127.0.0.1:41479/key/info -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' --get --data-urlencode "key=$VIRTUAL_KEY" -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    Selected fields from the final HTTP 200 response

    {
      "spend": 0.105,
      "soft_budget": 0.01,
      "team_id": null,
      "max_budget": null
    }
  4. 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

  1. Repeat with an already-crossed key, a high soft budget, and no soft budget, using the recorded curl commands and responses

    Case Soft budget Final spend Inference responses Alerts
    already-crossed 0.01 1.07 2 × HTTP 200 1
    below-budget 1000.0 0.102 3 × HTTP 200 0
    no-soft-budget unset 0.07200000000000001 2 × HTTP 200 0
  2. Delete all four owned keys, each deletion returns HTTP 200

Dashboard workflow

  1. 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) to 0.01, save, and reload

    Saved desktop soft budget

  2. Send 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

    Phone spend after crossing the soft budget

  3. 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 401

  4. Inspect 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

  1. Create a key with no team or hard budget, and keep its returned value in VIRTUAL_KEY

    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/key/generate -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' --data-raw '{"key_alias": "qa35800-api-crossed-by-request", "models": ["qa-alert-model"], "soft_budget": 0.01, "spend": 0.0}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    HTTP 200, soft_budget: 0.01, spend: 0, team_id: null, max_budget: null

  2. Send these three real inference requests, waiting after the first until GET /key/info shows its spend persisted

    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 1"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '
    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 2"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '
    curl -sS --max-time 120 -X POST http://127.0.0.1:41479/v1/chat/completions -H "Authorization: Bearer $VIRTUAL_KEY" -H 'Content-Type: application/json' --data-raw '{"model": "qa-alert-model", "messages": [{"role": "user", "content": "Say hi. crossed-by-request call 3"}], "max_tokens": 8, "cache": {"no-cache": true}}' -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    All three return HTTP 200 with nonzero token usage

  3. Read the final spend and wait beyond the five-second alert batching interval

    curl -sS --max-time 120 -X GET http://127.0.0.1:41479/key/info -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' --get --data-urlencode "key=$VIRTUAL_KEY" -w '
    CURL_HTTP_STATUS:%{http_code}
    '

    Selected fields from the final HTTP 200 response

    {
      "spend": 0.105,
      "soft_budget": 0.01,
      "team_id": null,
      "max_budget": null
    }
  4. 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

  1. Repeat with an already-crossed key, a high soft budget, and no soft budget, using the recorded curl commands and responses

    Case Soft budget Final spend Inference responses Alerts
    already-crossed 0.01 1.07 2 × HTTP 200 1
    below-budget 1000.0 0.102 3 × HTTP 200 0
    no-soft-budget unset 0.07200000000000001 2 × HTTP 200 0
  2. Delete all four owned keys, each deletion returns HTTP 200

Dashboard workflow

  1. 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) to 0.01, save, and reload

    Saved desktop soft budget

  2. Send 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

    Phone spend after crossing the soft budget

  3. 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 401

  4. Inspect 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

python -m pytest -q --tb=short \
  tests/unit/proxy/auth/test_auth_checks.py \
  tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py \
  tests/unit/proxy/proxy_server/test_spend_counters.py \
  tests/unit/integrations/SlackAlerting/test_slack_alerting.py

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

python -m pytest -q --tb=short -n 4 --dist loadscope \
  tests/unit/proxy/auth/test_auth_checks.py \
  tests/unit/proxy/auth/test_user_api_key_auth.py \
  tests/unit/proxy/test_credential_slot_registry.py \
  tests/unit/proxy/test_deprecated_key_grace_period.py

Full make format, make lint and committed-diff formatting pass again for this test update

The 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 inference

All 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, full make 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 identical

The 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

  • Hosted Slack and paid provider calls were not tested
  • Alert retry and cooldown behavior remain outside this fix
  • New integration coverage runs in CircleCI on main
  • Existing phone layout overflow and static 404s remain

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

  • Regression and edge-case checks pass, including all seven targeted mutations

@codspeed

codspeed Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 35 untouched benchmarks


Comparing tanishqbaweja:litellm_fix_35800_soft_budget_spend (9f6aaaf) with main (e4832c5)

Open in CodSpeed

@codecov

codecov Bot commented Oct 25, 2026

Copy link
Copy Markdown

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.
@CLAassistant

CLAassistant commented Nov 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

This branch has not been deployed

No deployments
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]: Standalone virtual-key soft_budget alert is not sent to Slack

2 participants