Skip to content

fix(proxy): keep carried end-user spend when a budget reset is retried - #51143

Merged
mateo-berri merged 18 commits into
BerriAI:mainfrom
PyExtreme:fix-50898-enduser-reset-retry
Nov 14, 2026
Merged

mateo-berri merged 18 commits into
BerriAI:mainfrom
PyExtreme:fix-50898-enduser-reset-retry

Conversation

@PyExtreme

@PyExtreme PyExtreme commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

If the budget-reset job fails partway through, the next run will reset end-users on rollover budgets again, causing customers to lose the spend they should have carried into the new window. Now each end-user, customer team and customer member records the window of its last reset, and a retry skips anyone already processed. Each window is named by the budget, its count of closed windows and its reset time, so budgets that never had a reset time are covered too.

Details

TLDR

Problem this solves:

  • A failed budget window advance makes the next tick replay end-user, customer team and customer member resets
  • Capped end users, customer teams and customer members lose carried spend on the retry (15 -> 5 -> 0)
  • A row the failed tick already reset also loses the spend it adds before the retry

How it solves it:

  • New spend_reset_window column on LiteLLM_EndUserTable, LiteLLM_CustomerTeamTable and LiteLLM_CustomerMemberTable, and a budget_reset_count column on LiteLLM_BudgetTable that only the window advance counts up
  • Each end-user, customer team and customer member reset stamps the window it closes, and a retry skips rows already stamped with that name
    • The name joins the tier id, when the tier was created, its count, and its reset time
    • A failed advance leaves the name as it was, so the retry skips rows already reset, even after an admin edits the tier's limits
    • The advance, a new reset time, or a tier recreated under the same id gives a new name, so the next close resets everyone
    • A customer member runs on its unexpired override when that has its own duration, else on its template
  • A tier already advanced on the writer is skipped, so a stale replica read leaves it alone

User Flow

Before: a customer on a rollover tier loses their carried overage when the reset job hits a DB error once

  1. The admin creates a tier with POST /budget/new (max_budget: 10, budget_duration: "1d") with budget_rollover: true
  2. The admin attaches a customer with POST /customer/new, and the customer spends 15 in the window
  3. The window closes, the reset job runs, and the DB write that moves the window forward fails once
  4. GET /customer/info shows spend 5, then the next run retries and it shows spend 0

After: the same retry keeps the carried overage

  1. Same tier, same customer, same spend of 15
  2. Same failure on the first run, GET /customer/info shows spend 5
  3. The retry moves the window forward and GET /customer/info still shows spend 5
  4. When the next window closes the customer is reset again as usual (22 -> 12)
  5. An admin who writes back the closed window's budget_reset_at with POST /budget/update still gets the customer reset again, also with no tier on max_end_user_budget_id
  6. A customer moved to another tier with POST /customer/update is reset when that tier's window closes
  7. A customer member on an organization's default budget keeps its carried spend through the same retry, as GET /management/v1/customer_members/{id} shows
  8. Changing the tier's budget_duration with POST /budget/update while the advance keeps failing resets the customer when the new window closes

Relevant issues

Fixes #50898

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

Before ran at the merge base 6021db5 and After at the tip ff516f3. Each side runs two proxies with 2 workers each on its own Postgres 16 and Redis, alternating requests. One real gpt-5.4-nano request puts the customer over a 0.00002 cap, and a Postgres trigger makes the window advance fail, as setup only. The gist has every output and script

Case Setup Before After
Due reset time, one failed advance locked 1.115e-05 -> 0 8.65e-06 -> 8.65e-06
No reset time, one failed advance locked 8.65e-06 -> 0 1.615e-05 -> 1.615e-05
Admin forces a reset locked 4.48e-05 -> 2.48e-05 4.855e-05 -> 2.855e-05
Admin forces a reset, customer with no tier default tier 3.855e-05 -> 1.855e-05 4.48e-05 -> 2.48e-05
Admin edits the tier, advance failing locked 9.9e-06 -> 0 1.115e-05 -> 1.115e-05
Customer moved to another tier locked 2.48e-05 -> 4.8e-06 5.22e-05 -> 3.22e-05
Tier duration changed, advance failing locked 3.24e-05 -> 1.24e-05 3.855e-05 -> 1.855e-05
Customer member, one failed advance locked 2.99e-05 -> 0 2.99e-05 -> 9.9e-06
Due reset time, one failed advance lockless 7.4e-06 -> 0 8.65e-06 -> 8.65e-06
No reset time, one failed advance lockless 7.4e-06 -> 0 1.365e-05 -> 1.365e-05
New spend, advance failing 60 s rollover off 3.115e-05 -> 0 2.99e-05 -> 2.99e-05
Window closes, no fault replica 6.15e-06 -> 0 1.115e-05 -> 1.115e-05

Each cell shows the customer's spend before and after the tested sweeps settle. Retry rows should keep the carried spend, and with rollover off new spend should stay. Forced, moved and duration rows should reset once more

Locked proxy config, start commands, and env var names, the same on both sides

Lockless drops coordination_redis and router_settings, so every proxy runs the sweep on its own. Rollover off drops budget_rollover. Default tier adds max_end_user_budget_id: qa-default-tier. Replica adds DATABASE_URL_READ_REPLICA, pointing at a streaming replica that applies changes 20 s late. The trigger raises on the first update that moves the tier's budget_reset_at more than a minute ahead, and in the rollover-off case on every such update for 60 s

model_list:
  - model_name: gpt-5.4-nano
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  coordination_redis:
    host: 127.0.0.1
    port: <redis port>
litellm_settings:
  drop_params: true
  budget_rollover: true
router_settings:
  redis_host: 127.0.0.1
  redis_port: <redis port>
docker run -d --name qa-6fd6ee9c-pg -e POSTGRES_USER=llmproxy -e POSTGRES_PASSWORD=... -e POSTGRES_DB=postgres -p 127.0.0.1:<pg port>:5432 postgres:16 -c max_connections=400
docker exec qa-6fd6ee9c-pg psql -U llmproxy -d postgres -qc "CREATE DATABASE qa_base_<setup>"
docker exec qa-6fd6ee9c-pg psql -U llmproxy -d postgres -qc "CREATE DATABASE qa_head_<setup>"
redis-server --port <redis port> --bind 127.0.0.1 --save '' --appendonly no --daemonize yes

The replica setup adds a streaming replica of the same Postgres

docker run -d --name qa-6fd6ee9c-pg-replica --network host -e PGPASSWORD=... postgres:16 -c "pg_basebackup -h 127.0.0.1 -p <pg port> -U llmproxy -D /var/lib/postgresql/data -R -X stream && postgres -D /var/lib/postgresql/data -p <replica port> -c recovery_min_apply_delay=20s"
export DATABASE_URL_READ_REPLICA=postgresql://llmproxy:...@127.0.0.1:<replica port>/<database>

Each side's two proxies use its own database (qa_base_<setup> or qa_head_<setup>) and its own Redis, both recreated for each setup

export DATABASE_URL=... LITELLM_MASTER_KEY=... OPENAI_API_KEY=...
export PROXY_BUDGET_RESCHEDULER_MIN_TIME=10 PROXY_BUDGET_RESCHEDULER_MAX_TIME=12 LITELLM_PRISMA_COMMAND_TIMEOUT=600
python litellm/proxy/proxy_cli.py --config qa.yaml --port <port A or B> --num_workers 2 --use_v2_migration_resolver --timeout_worker_healthcheck 60

Due reset time, locked

Before (6021db5), the retry zeroes the carried 0.00001115
## leg=base rig=locked case=due proxies A=http://127.0.0.1:22276 B=http://127.0.0.1:30886
$ curl -s -X POST http://127.0.0.1:22276/budget/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-26b2072e", "max_budget": 0.00002, "budget_duration": "1d"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "max_budget", "budget_duration", "budget_reset_at")})'
{'budget_id': 'qa-tier-26b2072e', 'max_budget': 2e-05, 'budget_duration': '1d', 'budget_reset_at': '2026-11-14T00:00:00Z'}

$ curl -s -X POST http://127.0.0.1:30886/customer/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"user_id": "qa-customer-26b2072e", "budget_id": "qa-tier-26b2072e"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-26b2072e', 'budget_id': 'qa-tier-26b2072e', 'spend': 0.0}

$ curl -s -X POST http://127.0.0.1:22276/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "gpt-5.4-nano", "user": "qa-customer-26b2072e", "messages": [{"role": "user", "content": "Write one sentence about budgets."}]}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["model"], d["usage"]["total_tokens"], "tokens:", d["choices"][0]["message"]["content"][:80]) if "model" in d else print("refused:", str(d.get("error", d))[:240])'
gpt-5.4-nano 35 tokens: Budgets help organizations plan, allocate resources, and track spending to ensur

waiting for the customer's spend to show up in /customer/info
$ curl -s 'http://127.0.0.1:30886/customer/info?end_user_id=qa-customer-26b2072e' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-26b2072e', 'budget_id': 'qa-tier-26b2072e', 'spend': 3.115e-05}

fault injection (setup, not evidence): Postgres raises once on the first write that moves qa-tier-26b2072e's reset time more than a minute ahead
$ curl -s -X POST http://127.0.0.1:22276/budget/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-26b2072e", "budget_reset_at": "2026-11-13T19:43:25Z"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "budget_reset_at")} if "budget_id" in d else "error: " + str(d.get("error", d))[:240])'
{'budget_id': 'qa-tier-26b2072e', 'budget_reset_at': '2026-11-13T19:43:25Z'}

polling GET /customer/info and POST /budget/info every 0.2 s, alternating proxies, printing changes
19:44:25.833 via 22276: customer spend=0.00003115 budget_reset_at=2026-11-13T19:43:25Z window_advanced=no
19:44:26.705 via 30886: customer spend=0.00001115 budget_reset_at=2026-11-13T19:43:25Z window_advanced=no
19:44:29.019 via 30886: customer spend=0.0 budget_reset_at=2026-11-14T00:00:00Z window_advanced=yes
$ curl -s 'http://127.0.0.1:30886/customer/info?end_user_id=qa-customer-26b2072e' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-26b2072e', 'budget_id': 'qa-tier-26b2072e', 'spend': 0.0}

carried spend after the retry: expected 0.00001115, got 0.00000000
next window closes with no fault
$ curl -s -X POST http://127.0.0.1:22276/budget/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-26b2072e", "budget_reset_at": "2026-11-13T19:43:29Z"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "budget_reset_at")} if "budget_id" in d else "error: " + str(d.get("error", d))[:240])'
{'budget_id': 'qa-tier-26b2072e', 'budget_reset_at': '2026-11-13T19:43:29Z'}

19:44:29.852 via 22276: customer spend=0.0 budget_reset_at=2026-11-13T19:43:29Z window_advanced=no
19:44:32.777 via 22276: customer spend=0.0 budget_reset_at=2026-11-14T00:00:00Z window_advanced=yes
$ curl -s 'http://127.0.0.1:22276/customer/info?end_user_id=qa-customer-26b2072e' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-26b2072e', 'budget_id': 'qa-tier-26b2072e', 'spend': 0.0}
After (ff516f3), the retry keeps the carried 0.00000865
## leg=head rig=locked case=due proxies A=http://127.0.0.1:20658 B=http://127.0.0.1:29880
$ curl -s -X POST http://127.0.0.1:20658/budget/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-469660b1", "max_budget": 0.00002, "budget_duration": "1d"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "max_budget", "budget_duration", "budget_reset_at")})'
{'budget_id': 'qa-tier-469660b1', 'max_budget': 2e-05, 'budget_duration': '1d', 'budget_reset_at': '2026-11-14T00:00:00Z'}

$ curl -s -X POST http://127.0.0.1:29880/customer/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"user_id": "qa-customer-469660b1", "budget_id": "qa-tier-469660b1"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-469660b1', 'budget_id': 'qa-tier-469660b1', 'spend': 0.0}

$ curl -s -X POST http://127.0.0.1:20658/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "gpt-5.4-nano", "user": "qa-customer-469660b1", "messages": [{"role": "user", "content": "Write one sentence about budgets."}]}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["model"], d["usage"]["total_tokens"], "tokens:", d["choices"][0]["message"]["content"][:80]) if "model" in d else print("refused:", str(d.get("error", d))[:240])'
gpt-5.4-nano 33 tokens: Budgets help ensure resources are allocated wisely and spending stays aligned wi

waiting for the customer's spend to show up in /customer/info
$ curl -s 'http://127.0.0.1:29880/customer/info?end_user_id=qa-customer-469660b1' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-469660b1', 'budget_id': 'qa-tier-469660b1', 'spend': 2.865e-05}

fault injection (setup, not evidence): Postgres raises once on the first write that moves qa-tier-469660b1's reset time more than a minute ahead
$ curl -s -X POST http://127.0.0.1:20658/budget/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-469660b1", "budget_reset_at": "2026-11-13T19:41:45Z"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "budget_reset_at")} if "budget_id" in d else "error: " + str(d.get("error", d))[:240])'
{'budget_id': 'qa-tier-469660b1', 'budget_reset_at': '2026-11-13T19:41:45Z'}

polling GET /customer/info and POST /budget/info every 0.2 s, alternating proxies, printing changes
19:42:45.928 via 20658: customer spend=0.00002865 budget_reset_at=2026-11-13T19:41:45Z window_advanced=no
19:42:46.213 via 29880: customer spend=0.000008649999999999997 budget_reset_at=2026-11-13T19:41:45Z window_advanced=no
19:42:50.204 via 20658: customer spend=0.000008649999999999997 budget_reset_at=2026-11-14T00:00:00Z window_advanced=yes
$ curl -s 'http://127.0.0.1:29880/customer/info?end_user_id=qa-customer-469660b1' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-469660b1', 'budget_id': 'qa-tier-469660b1', 'spend': 8.649999999999997e-06}

carried spend after the retry: expected 0.00000865, got 0.00000865
next window closes with no fault
$ curl -s -X POST http://127.0.0.1:20658/budget/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"budget_id": "qa-tier-469660b1", "budget_reset_at": "2026-11-13T19:41:50Z"}' | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("budget_id", "budget_reset_at")} if "budget_id" in d else "error: " + str(d.get("error", d))[:240])'
{'budget_id': 'qa-tier-469660b1', 'budget_reset_at': '2026-11-13T19:41:50Z'}

19:42:50.796 via 20658: customer spend=0.000008649999999999997 budget_reset_at=2026-11-13T19:41:50Z window_advanced=no
19:42:52.132 via 29880: customer spend=0.0 budget_reset_at=2026-11-14T00:00:00Z window_advanced=yes
$ curl -s 'http://127.0.0.1:20658/customer/info?end_user_id=qa-customer-469660b1' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d.get(k) for k in ("user_id", "budget_id", "spend")})'
{'user_id': 'qa-customer-469660b1', 'budget_id': 'qa-tier-469660b1', 'spend': 0.0}

Observations from the run

  • Stale cached spend briefly refuses requests after a reset, pre-existing
Unit tests and mutation checks

Re-run at ff516f3 by the reviewer. pytest tests/unit/proxy/common_utils/test_reset_budget_job.py tests/unit/proxy/management_endpoints/test_budget_endpoints.py tests/unit/repositories/test_unit_of_work.py passes (262). Merging current main brought migrations stamped up to 20261113140000, so this PR's migration is 20261113150000_add_spend_reset_window and applies last. Each of these mutants fails at least one test: the tier, its creation time, its count or its reset time left out of the window name, the name taken from the tier's last write, no count increment on the advance, no skip guard, no due filter on the writer read, customer teams and members reset without a window, and a member's clock always on its template or ignoring the override's expiry or duration

tests/integration/management/test_budget_updates.py was already red on the merge base, since /budget/info gained nine fields after the test was written. 7a85fc5 lists every budget column and relation there, budget_reset_count included, so a partial update must also keep the count, and the file passes (3). That commit changes only this test, so the proof above still applies

From the author, for an earlier design that pinned empty reset times

pytest tests/unit/proxy/common_utils/test_reset_budget_job.py tests/unit/repositories/test_unit_of_work.py passes (198). The new retry test fails on the merge base. Each of these mutants fails at least one test: guard reduced to IS NULL, guard without the NULL branch, a < guard instead of !=, no stamp on the zero or the decrement statement, no guard at all, the first tier's window used for every tier, an unguarded uncapped tier, no pin for an empty reset time, a pin that overwrites a stored reset time, the pod's own time used instead of the stored pin, keeping a read-back later than the pod's own pin, pinning without rounding to the millisecond, reading the pin back from the read replica, and rollover caps for a tier the sweep left out. make check passes at 62251d9e77. The branch was then rebased onto current main, which added a migration with the same timestamp prefix, so this PR's migration moved to 20261111120000 to apply after it. At 271e7c9 all migrations apply in order to a fresh Postgres and the tests above plus test_customer_budget.py pass (204).

Live dependency check

Keys, orgs, customers and tags on one tier each reset once after the window closed, on the merge base and at ff516f3. The only response difference is budget_reset_count on /budget/info and /budget/list, covered under Decisions. The budget, reset, spend and customer integration files pass on the head (106 and 119) and on the tip merged with current main. 7a85fc5 changes only a test, so this carries to it

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • End users, customer teams and customer members at zero spend on the failed attempt are never stamped
    • One that spends before the retry has that spend zeroed by the retry, as on main
    • Stamping them would write every row on the tier each window
Decisions
  • The admin budget endpoints now return budget_reset_count with the rest of the budget row. /budget/* already return raw rows with internal fields like created_by and updated_at, so the new field is additive, and hiding it would need a response model on five routes
  • Rows at zero spend stay unstamped, since a stamp on each would cost a write per row per window, and the retry treats them as main does

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
Bugbot summary

[!NOTE]
High Risk
Changes core budget reset and spend persistence paths; a bug could mis-account customer spend or leave tiers stuck due, and it requires a DB migration in production.

Overview
This PR makes paged budget spend resets idempotent when a window advance fails after end users, customer teams, or customer members were already updated—addressing carried rollover spend being zeroed on retry (#50898).

Schema: Adds budget_reset_count on LiteLLM_BudgetTable and spend_reset_window on end users, customer teams, and customer members, plus a migration.

Reset job: Resolves each tier’s closing window name (budget id, creation time, reset count, and budget_reset_at) via a writer read in BudgetRepository.due_tier_windows, then only resets tiers still due. Paged writes use WindowedSpendResetWrites: stamp spend_reset_window and skip rows already stamped for that window; customer paging groups by cap and window (override-owned clock when an unexpired override has its own budget_duration). budget_reset_count increments when the window advances.

Tests: Large expansion of test_reset_budget_job (retry, admin forced reset, tier moves, replica lag) and unit-of-work expectations for window guards.

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

End-user pages commit before the budget window advance. When the advance
failed, the tier stayed due and the next tick replayed every page, so a
rollover-capped row already cut to its carryover (15 -> 5) matched the
under-cap zero and lost it, and spend accrued since the first pass was
zeroed again. Each end-user reset now stamps the tier window it closes
in a new spend_reset_window column and skips rows already stamped with it.

Fixes BerriAI#50898
…n window

A tier with no budget_reset_at falls back to the old unguarded reset
instead of stamping created_at, which an admin clearing the reset time
would reuse and silently skip end users. Tests now give tiers distinct
windows and cover a second window closing.
@PyExtreme
PyExtreme requested a review from a team November 11, 2026 05:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T05:53:46.029143Z 271e7c9 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@veria-ai

veria-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mubashir1osmani

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.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found.

Summary

The PR stamps end-user, customer-team and customer-member resets with the closing budget window so retries preserve carried spend. It also adds budget_reset_count and checks due windows on the writer.

The latest change updates integration-test expectations for the complete budget response, including budget_reset_count.

All supplied previous threads are unnumbered, so none require ledger entries. Their findings are fixed or retracted. Greptile retracted the budget-edit scan finding after mateo-berri explained that only rewinding a closed window triggered the scan.

  • Spend rows keep their carried amount when a reset job retries.
  • The reset job skips budget tiers another worker already advanced.

Reviews (7) · Last reviewed commit: "test(integration): list every budget col..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…e tier's reset time

A failed /budget/update used to leave the new reset time written with the
stamps still set, so repeating the request found the time unchanged and
skipped the clear. The update and the clear now commit together, and a
reset time in the future no longer scans the tier's end users
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Stamp end-user resets with the tier's updated_at read on the writer instead
of its reset time. A failed window advance leaves updated_at as it was, so the
retry still skips the end users already reset, while the advance or any
/budget/update moves it and opens a new window. That covers a forced reset on
the default end-user tier and drops the stamp clear, so /budget/update is the
one-row update it is on main. The writer read also leaves out a tier another
sweep already advanced, which a lagging read replica still showed as due
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/repositories/unit_of_work.py Resolved
…ount

Tiers advanced in one batch share updated_at, so a customer moved between
them could skip the new tier's reset, and any unrelated tier edit during a
failed advance reopened the window. A budget_reset_count that only the
window advance bumps, prefixed with the tier id, names the window instead.
# Conflicts:
#	litellm/repositories/budget_repository.py
# Conflicts:
#	litellm/proxy/common_utils/reset_budget_job.py
#	tests/unit/proxy/common_utils/test_reset_budget_job.py
# Conflicts:
#	litellm/proxy/common_utils/reset_budget_job.py
#	tests/unit/proxy/common_utils/test_reset_budget_job.py
…tried reset

Customer team and member pages commit before the window advance like end-user
pages, so they now stamp the window they close and a retry skips them too. A
member runs on its unexpired override when that has its own duration, else on
its template.

The window name now joins the tier id, its creation time, its count of closed
windows and its reset time, so a duration change or a tier recreated under the
same id opens a new window even when the advance failed.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codspeed

codspeed Bot commented Nov 14, 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 PyExtreme:fix-50898-enduser-reset-retry (7a85fc5) with main (2df4f9a)

Open in CodSpeed

@codecov

codecov Bot commented Nov 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.42857% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/repositories/unit_of_work.py 88.88% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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 7a85fc5. 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. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit 5f381ad into BerriAI:main Nov 14, 2026
101 checks passed
mateo-berri added a commit that referenced this pull request Nov 14, 2026
…piKeyHelper (#51319)

* fix(cli): let Claude Code renew a --pkce login's key through lite's apiKeyHelper

* fix(cli): keep an explicit --api-key over lite's apiKeyHelper and persist its absolute path

An explicit --api-key or LITELLM_PROXY_API_KEY is now exported to Claude Code
even when lite's renewing helper is configured, since the helper prints the
stored login's key instead. The helper command also uses the absolute path of
the lite found on PATH, so a relative PATH entry cannot make Claude Code run
another repository's bin/lite

* fix(cli): keep an explicit key and --pkce when lite's renewing helper is set

A --settings that blanks apiKeyHelper now keeps the exported key, and a key passed with --api-key turns lite's helper off for that launch, so Claude Code no longer warns about two credentials or sends the stored login's key beside it

The helper names the lite installed beside the Python that ran the login before one found on PATH, so a pyenv shim no longer fails in projects pinned to another Python

lite claude signs in again with --pkce when the stored login used it, and print-token's hints name the proxy and --pkce

* fix(cli): keep a shell token from beating the renewing helper and reuse --pkce only for the same proxy

The --pkce --config-claude login now writes an empty env.ANTHROPIC_AUTH_TOKEN beside the helper, since a token exported in the shell wins over apiKeyHelper

lite claude sends any other key through a private settings file that blanks the helper and merges the user's own --settings

A re-login keeps --pkce only when the stored login is for the same proxy, else the saved default decides

* fix(cli): let any lite install's helper renew for its proxy and name the renewing login in print-token hints

lite claude now treats a lite auth print-token helper for this proxy as renewing whichever lite path it names, since every lite reads the same token store

Every print-token hint to sign in again, including an expired key and an unreadable keychain, names lite login --pkce with the proxy

Shorter docstrings

* fix(cli): send a launch key to the proxy it was issued for

The private settings file lite claude writes for a key that lite's helper would not renew now also sets ANTHROPIC_BASE_URL. Without it, lite --base-url B --api-key <B key> claude after a --pkce --config-claude login to A sent the B key to A, since the login's settings point Claude Code at A

* fix(proxy): preserve caller metadata on auth failures (#51745)

* fix(proxy): keep x-litellm-spend-logs-metadata on auth-rejected failure spend logs

Budget, invalid-key and other auth-stage rejections are raised before the
request headers are merged into metadata, so the persisted failure row lost
the caller's spend logs metadata header. The auth failure handler now parses
it with the same pre-call helper and stamps it into the metadata bucket it
already uses for the requester IP and user agent.

* fix(proxy): type the spend logs metadata header parser honestly

The parser takes the request headers as a str mapping and returns the parsed
JSON as object, which is what successful requests already store. The auth
failure path keeps only JSON objects. The precedence regression now also
asserts the caller's request body is left untouched.

* fix(proxy): stamp the auth failure spend logs metadata into the route's bucket

A chat request whose body also carried litellm_metadata got the header in
litellm_metadata, which the failure spend row never reads on chat routes.
The header now goes into the bucket picked by metadata_variable_name_for_request
for the route, and the failure row lifts spend_logs_metadata from that bucket
the same way it already lifts the requester IP and user agent. The regression
tests now assert on the built failure spend row.

* fix(proxy): keep the auth failure spend logs metadata fix inside the auth handler

Restores the failure spend row's lifted fields to main, so failures after auth
on litellm_metadata routes keep their current logging. The auth handler now
writes the parsed header into metadata, which the failure spend row reads on
every route, and into the route's own bucket for callbacks on litellm_metadata
routes.

* fix(proxy): make the spend logs metadata header field read-only and test the real spend writer

The header collector now sets spend_logs_metadata when it is built, so the
field can be ReadOnly with the same stored value. The auth failure tests run
the real DBSpendUpdateWriter and read the queued spend log row from a fake
database client instead of an autospec writer.

* test(proxy): read auth failure spend rows from a real unconnected PrismaClient

Replaces the mocked database client and the class-level queue byte reset.
The test now enqueues into a real PrismaClient's own queue and dequeues
its row in cleanup, which keeps the shared byte counter balanced.

---------

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>

* fix(logging): keep a content-block system prompt in logged messages (#51699)

* fix(logging): keep a content-block system prompt in logged messages

A /v1/messages request whose top-level system prompt is a list of content
blocks never reached the logged messages, because only a plain-text system
prompt was prepended. Accept a non-empty list too, so every logger that reads
messages sees it. Claude on Vertex also normalizes a plain-text system prompt
into blocks, so it was dropped there as well.

Fixes #36402

* fix(logging): type the logged system message

* fix(logging): type the system message without a mutable annotation, close the test client

* refactor(mcp): let the semantic filter take its MCP tool loader as a parameter (#50483)

* test(mcp): check the tool dict conversion without patching the MCP handler

* refactor(mcp): let the semantic filter take its MCP tool loader as a parameter

* refactor(mcp): type the semantic filter's default tool loader

Annotate the chosen loader as _OpenAIToolLoader and narrow its return to
FunctionToolParam, so a default that returns raw MCP tools fails the type
check. Drop the unused patch import.

* fix(mcp): give the MCP client exactly the servers left on in the connect page (#50973)

* fix(cli): send the launch key under a project apiKeyHelper and give each key its own settings file

A `lite login --pkce --config-claude` leaves an empty ANTHROPIC_AUTH_TOKEN in Claude Code's user settings. When a repo's project settings set their own apiKeyHelper, `lite claude` skipped its private settings file, so the empty token hid the exported key and Claude Code sent the project helper's key. `lite claude` now also writes that file whenever the settings files leave ANTHROPIC_AUTH_TOKEN empty

Every key launch also wrote the one file `--subscription` uses, so two launches started together could read each other's key and proxy. A key launch's file is now named after a hash of its contents, and every overlay is written to a temp file and renamed so a starting Claude Code never reads half of one

* fix(proxy): keep carried end-user spend when a budget reset is retried (#51143)

* fix(proxy): keep carried end-user spend when a budget reset is retried

End-user pages commit before the budget window advance. When the advance
failed, the tier stayed due and the next tick replayed every page, so a
rollover-capped row already cut to its carryover (15 -> 5) matched the
under-cap zero and lost it, and spend accrued since the first pass was
zeroed again. Each end-user reset now stamps the tier window it closes
in a new spend_reset_window column and skips rows already stamped with it.

Fixes #50898

* fix(proxy): leave never-reset tiers unguarded and test each tier's own window

A tier with no budget_reset_at falls back to the old unguarded reset
instead of stamping created_at, which an admin clearing the reset time
would reuse and silently skip end users. Tests now give tiers distinct
windows and cover a second window closing.

* test(proxy): give the end-user ledger its own fake prisma client

* fix(proxy): pin a reset time on tiers without one before end-user pages commit

* fix(proxy): read the reset-time pin from the writer and skip tiers another sweep advanced

* fix(proxy): keep linked rows of a tier another sweep advanced out of the rollover reset

* fix(proxy): order the end-user reset window migration after upstream's same-timestamp migration

* fix(proxy): reset end users again when an admin moves a tier's reset time back to a closed window

* fix(proxy): clear end-user reset stamps in the same transaction as the tier's reset time

A failed /budget/update used to leave the new reset time written with the
stamps still set, so repeating the request found the time unchanged and
skipped the clear. The update and the clear now commit together, and a
reset time in the future no longer scans the tier's end users

* fix(proxy): name each end-user reset window by the tier's last write

Stamp end-user resets with the tier's updated_at read on the writer instead
of its reset time. A failed window advance leaves updated_at as it was, so the
retry still skips the end users already reset, while the advance or any
/budget/update moves it and opens a new window. That covers a forced reset on
the default end-user tier and drops the stamp clear, so /budget/update is the
one-row update it is on main. The writer read also leaves out a tier another
sweep already advanced, which a lagging read replica still showed as due

* fix(proxy): name end-user reset windows by the tier and its advance count

Tiers advanced in one batch share updated_at, so a customer moved between
them could skip the new tier's reset, and any unrelated tier edit during a
failed advance reopened the window. A budget_reset_count that only the
window advance bumps, prefixed with the tier id, names the window instead.

* fix(proxy): keep carried spend for customer teams and members on a retried reset

Customer team and member pages commit before the window advance like end-user
pages, so they now stamp the window they close and a retry skips them too. A
member runs on its unexpired override when that has its own duration, else on
its template.

The window name now joins the tier id, its creation time, its count of closed
windows and its reset time, so a duration change or a tier recreated under the
same id opens a new window even when the advance failed.

* test(integration): list every budget column and relation in the budget update field check

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>

* test(otel): keep proxy startup out of the per-test timeout in the excluded services matrix (#51759)

Co-authored-by: mateo <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(cli): skip the working directory when the login looks up lite for its helper

On Windows, shutil.which searches the current directory before the directories it is given, so a lite.exe planted in the repo where someone ran `lite login --pkce --config-claude` could become their user-level apiKeyHelper

The login now checks each directory by full path, this Python's scripts directory first and then each PATH entry, skipping empty entries

* fix(bedrock): answer 400 for service tiers Bedrock cannot serve, forward reserved (#50516)

* fix(bedrock): answer 400 for service tiers Bedrock cannot serve, forward reserved

Converse used to drop any service_tier outside default, flex, and priority
with no error, rewrite auto to default, and drop reserved. Now reserved and
standard_only map to Bedrock tiers, auto sends no tier, and any other value
answers 400 unless drop_params is on. Nova batch rows honor the row's
drop_params.

* fix(bedrock): keep a Responses batch row's drop_params and keep it out of passthrough rows

* test(bedrock): annotate service tier test locals as Final and drop the row helper's kwargs

* fix(bedrock): refuse a service tier on Nova batch rows unless drop_params, and honor the deployment's drop_params

* fix(bedrock): map standard and any-case service tiers, and drop tiers from Claude batch rows under the deployment's drop_params

* fix(bedrock): forward the tiers OpenAI-format batch rows take, accept auto on Claude rows, and label tiers in lowercase

* fix(bedrock): mark the service tier block field read-only

* fix(bedrock): read drop_params given as a string on batch rows, and cover the Nova row mapper's drop_params

* test(prometheus): sort the service tier label test imports

* fix(bedrock): send the Invoke route's service tier as a header and name the accepted tiers in the 400

* fix(bedrock): report and bill the tier Bedrock served on Invoke calls and streams, and send the tier header only to Nova

* fix(bedrock): return copies when stamping the served tier, read its header without re-encoding the others, and pin it per stream chunk

The Nova Invoke mapper and the event-stream decoder now return model_copy results instead of writing service_tier in place. One shared reader finds the X-Amzn-Bedrock-Service-Tier response header case-insensitively, so a non-ASCII request id no longer breaks the stream decoder, and the passthrough uses the same reader. Tests now vary the served tier in both directions, check every chunk, and cover a stream with no tier header or an empty one

* test(bedrock): check the served tier on a stream whose headers come as a plain dict with an upper-case name

The non-ASCII request id stream test now also carries X-AMZN-BEDROCK-SERVICE-TIER in a plain dict and asserts every chunk reports that tier, so a case-sensitive header reader or a lookup by the canonical name fails it

* refactor(bedrock): drop the passthrough's own service tier header reader that main re-added

The passthrough already reads the served tier through the shared case-insensitive reader in common_utils, so the httpx.Headers copy main brought back with the embeddings change has no callers and references a constant this branch removed

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>

* fix(cli): delete the key files lite claude leaves on logout and unconfigure

lite claude hands its process to Claude Code, so the --settings files holding
its key stayed in the Claude config dir. lite logout and lite unconfigure claude
now delete them, and Claude Code reads one only at startup, so open sessions
keep working

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: joshua-berri <joshua@berri.ai>
Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
Co-authored-by: ryan-crabbe-berri <ryan@berri.ai>
Co-authored-by: shrey <shrey@berri.ai>
Co-authored-by: Ankit Jha <45779665+PyExtreme@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: quietjules <349048734+quietjules@users.noreply.github.com>
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.

A retried budget reset erases the carried spend of rollover-capped end users

3 participants