Repository navigation
fix(customer-management)!: preserve permanent budgets across temporary increases - #52787
Conversation
|
@greptileai review the permanent member budget separation, legacy override preservation, and temporary increase expiry behavior on the latest commit. |
|
@cursor review the permanent member budget separation, ownership checks, and temporary increase expiry behavior on the latest commit. |
[High impact] The reviewed revision appears safe to merge, with no new blocking issues found.
|
|
@greptileai review the latest commit. Creation now locks the organization before capacity, with a failing-before and passing-after PostgreSQL regression. |
|
@cursor review the latest commit, including consistent organization-first capacity locking and the PostgreSQL regression for concurrent member creation and moves. |
|
@greptileai please re-review this update. First custom member edits now copy preset settings in the backend, preserving explicit nulls and temporary grants. |
|
@cursor bugbot run. Please review backend preset copying on first custom edits, explicit null handling, reset dates, and independent temporary grants. |
|
Unable to authenticate your request. Please make sure to connect your GitHub account to Cursor. Go to Cursor |
|
bugbot run Please review this update for preset snapshot correctness, explicit clears, unchanged reset dates, and temporary override isolation. |
|
@greptileai review the latest fixes. Legacy promotion preserves expiring deltas, and organization deletion follows organization-first locking with failing-before regressions. |
|
bugbot run Please review legacy budget promotion and cascading deletion on the latest commit, including the expiry and PostgreSQL contention regressions. |
|
@greptileai review the latest commit, especially shared presets, private custom budgets, temporary expiry, app scope isolation, and migration compatibility. |
|
bugbot run Please review the latest app association budget changes for ownership, expiry, isolation, and legacy compatibility regressions. |
|
@greptileai review 7f7d325. Updated migration notes and real dashboard/API proof cover permanent budgets, inherited limits, expiry, and isolation. |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
77d3975 to
d33df0f
Compare
…y-extras (#52917) The changed-tests lane only mirrors litellm/<dir>/<module>.py to tests/unit/<dir>/test_<module>.py. proxy-extras lives at litellm/proxy-extras/litellm_proxy_extras/ but its tests are in tests/unit/litellm_proxy_extras/, and migrations are .sql, so no proxy-extras change selected any test. #52787 merged a non-idempotent migration that way. Any change under litellm/proxy-extras/ now selects every test file in tests/unit/litellm_proxy_extras/.
…ges (#53940) Brings nine tests in line with behavior that intentionally changed: - SSO client removal: /sso/key/generate without SSO now redirects to /ui/login (#53205) - budget partial update: /budget/info returns the app relation keys (#52477, #52787, #53232) - performance alerts opt-out: /alerts/monitoring returns thresholds (#52139) - cost margin rejection: the error names 'customer' as a valid key (#52406) - regional two-image generation: Gemini gets n single-image requests (#52103) - customer app budget key rotation: the rotated key's cleanup tolerates /key/regenerate - DeepSeek 401: the upstream error type is relayed (#53217) - vLLM rejected predicate: the plain upstream message is relayed (#53217). The case still fails on the non-OpenAI error type that #51809 fixes - /callbacks/list e2e: the Rust spend logger is listed as spend_log (#52182)
Handwritten 1-3 sentence description
[insert handwritten description here]
Breaking change: clients must send explicit nulls to clear app association policies and remove customer or app budget references through the owning entity before using
/budget/delete.Details
TLDR
Problem this solves:
How it solves it:
Intentional product change: custom budgets become independent of subsequent preset edits. App member edits affect only that app. The editor rejects simultaneous preset selection and permanent custom edits instead of silently discarding custom limits.
User Flow
Before, saving only a custom spend limit removes inherited rate limits and budget windows.
http://127.0.0.1:4354/customers/usage?org=app-budget-ui-organd edit Budget Validation App A.After, the same edit preserves the inherited policy in an independent permanent budget.
http://127.0.0.1:4354/customers/usage?org=app-budget-ui-organd edit Budget Validation App A.The matching member flow uses
http://127.0.0.1:4354/customers/usage?org=app-budget-ui-org&member=app-budget-ui-member, enters 350, and preserves the same inherited restrictions. The other app and global member remain unchanged.portal-save-reopen-f7504.mp4
Budget behavior
Presets reference shared budget rows. The first permanent custom edit copies the preset's settings into an entity-owned
budget_idand applies the supplied fields. Later edits retain that private ID. Omitted fields retain their settings, explicit nulls clear limits, and zero remains a valid cap. Monthly and yearly windows, model restrictions, cap policy, rate limits, and unchanged reset dates survive partial edits.Temporary grants use
budget_override_idwith expiry. Responses expose the stored permanent policy separately from the effective policy. Read-edit-save cannot turn an older additive increase into a permanent cap. Approval remains a global customer-member workflow. App associations accept temporary policy and expiry through their management APIs.Legacy nonexpiring overrides remain supported. Converting them through the editor preserves their raw permanent settings before applying visible edits. API clients perform that conversion with
budgetand explicitbudget_override: null. An omitted override is retained. Legacy app overrides retain their original complete-policy meaning.App members inherit from their app-specific organization member policy, then the app default.
budget: nullreturns to inheritance. App organization policies resolve their own budget, the legacy tier reference, then the app default tier. The legacytier_budget_idinput remains supported.Organization-first locks serialize related edits and deletion. Cleanup captures owned app budgets before cascading association rows, then deletes only unreferenced budgets. Generic budget deletion returns HTTP 409 while customer or app references remain.
Rollout and compatibility
The schema-only migration
20261119000000_app_association_base_budgetsadds nullablebudget_idandbudget_override_expires_atcolumns and budget foreign keys to the app-organization and app-member association tables. All three Prisma schema copies are synchronized. It does not rewrite existing rows or change their spend.App association PUT previously cleared omitted tier, override, and member-default fields. It now retains omitted fields so permanent edits do not erase independent grants. Callers that relied on an empty or partial request clearing those fields must send explicit nulls. Existing customer and app budgets must be detached through their owner before generic deletion.
Pre-Submission checklist
Current tip is
744eb97ba910a3aadb023149bc7c1af9757ce3e3. The Devin payload-mutation finding is fixed by constructing the return value immutably. Fresh automated reviews and CI are running. The review gate remains open until those results complete.Screenshots / Proof of Fix
Reproduce the actual dashboard flow
The screenshots above use the same URL and fixture data on the merge-base dashboard and proxy, then the final product dashboard and proxy. Both services must run the selected source revision. The UI recording is 28.5 seconds of actual browser interaction on
f7504bed90f74a2155164cd2e0a54012f2796a1e.With the proxy running as described below, start the dashboard from
litellm/ui/litellm-dashboardin the same checkout.Use the locally supplied
UI_USERNAMEandUI_PASSWORDto sign in. The visible deployment-warning banner is the gateway'senv_credential_loginwarning for these local environment credentials./health/deployment_warningsreturned HTTP 200. It is not a failed budget request and appears in both builds.The exact fixture scripts used for the captures follow. Save them together in a private local
proofdirectory. They read only the local master key fromprivate.json. Create that file from your existingLITELLM_MASTER_KEYwithout printing the value.Save as
proof/ui_fixture.py.Save as
proof/ui_proof_fixture.py.Run the Before clicks above, save and reopen both app association scopes, then stop the dashboard and proxy. Switch both to the final product revision and restart them with the same configuration. Run
python3 proof/ui_proof_fixture.py reset --name after-initialto clear the baseline legacy overrides, then repeat the same clicks.python3 proof/ui_proof_fixture.py snapshot --name after-savedrecords the real persisted responses. The fixtures are intentionally retained for clicking through the local demo. Use a fresh isolated database for another complete before/after run.Current PR tip is
744eb97ba910a3aadb023149bc7c1af9757ce3e3. Compared with the recorded product revisionf7504bed90f74a2155164cd2e0a54012f2796a1e, the only production change replaces post-construction payload mutation with an immutable return. Both budget-window paths return the same values. All remaining changes consolidate tests, so the existing live API and UI proof carries forward.The actual
maincomparison contains 645 added production lines and 633 added test lines, excluding 41 schema/migration lines and 31 generated API-type lines. Added tests fell from 1,602 to 633. No baseline test cases or coverage thresholds were removed to satisfy the ratio.The final scoped runs passed 358 backend unit tests, 157 dashboard tests across seven files, and seven real PostgreSQL cases. Backend coverage across the affected modules is 95%. Canonical
make checkpassed, including Python lint, typing and test-quality gates, dashboard lint, and API-type synchronization. The consolidated PostgreSQL deletion cases still fail against the pre-fix implementation, five failures before and seven passing cases after.Focused verification commands
Run from the repository root.
From
litellm/ui/litellm-dashboard.The PostgreSQL run used an isolated database on port 54972 with a separately generated Prisma client. The cluster was stopped afterward. Cleanup and concurrent-edit cases share setup and assert the exact surviving budget IDs, including shared-profile preservation.
The recorded API run uses final product revision
f7504bed90f74a2155164cd2e0a54012f2796a1e. It issues fresh requests to the real local gateway, waits for actual expiry, and removes its fixtures.Before API recording
app-budgets-main-before.mp4
After API recording
app-budgets-final-after.mp4
Screenshots / Proof of Fix
The real two-worker proxy passed 101 live API/database assertions at
42888f89250f26c3d50f7d81e6488bbe31ae8da4. The recorded product commit isf7504bed90f74a2155164cd2e0a54012f2796a1e. Its diff from the tested commit contains only five frontend files.git diff --name-only 42888f89250f26c3d50f7d81e6488bbe31ae8da4..f7504bed90f74a2155164cd2e0a54012f2796a1e -- litellm/proxy litellm/types litellm/proxy-extras schema.prismais empty, so the backend proof carries forward. The actual UI proof is recorded separately.The primary before build is the merge base
37a637dc163e8d9e9ff18befb8bd71f1de2e386c. Supplementary defect checks at67b7703613a53e1ca15bb8b40d887eccc88fe5fdcaught the six organization partial-copy failures and the association fixes. Both primary legs used real PostgreSQL, the same dedicated Redis, and two serving workers. No provider inference was needed. Real/v1/chat/completionsprobes verified budget denial before dispatch; an allowed request reached deliberately closed local port 9. Provider success and spend accounting are outside this proof.The client below is self-contained. It creates and deletes its own fixtures and exercises both app association scopes, copied limits and resets, private-ID reuse, temporary expiry, base edits during a grant, explicit legacy conversion, isolation, and the global member approved-grant lifecycle. Setup and output are included so the proof does not depend on local helper scripts.
Shared setup and exact proxy configuration
Use an isolated checkout, a local PostgreSQL database named
codex_app_budget_validation_20261119, and a dedicated Redis on 6395. On a fresh development environment, the repository's dependency command ismake install-proxy-dev. The measured runtime used Python 3.13.16, Prisma 0.11.0, psycopg 3.3.6, httpx 0.28.1, uvicorn 0.51.0 and FastAPI 0.136.3. Its venv and generated Prisma client were isolated from the parent checkout.Supply
DATABASE_URL,LITELLM_MASTER_KEY,UI_USERNAMEandUI_PASSWORDlocally. Never print or commit them.DATABASE_URLmust target that fresh local database and have no query parameters for the psycopg client. The proxy used the same URL with?connection_limit=4appended.The remaining environment was
For a fresh database, create the merge-base schema with Prisma and adopt it through the normal v2 resolver. After changing source to the after revision, run the resolver again to apply the additive migration. Generate only in the isolated venv, with the proxy stopped. These standalone commands perform the schema preparation used by the local setup helper.
Save this exact config as
proxy-config.yamlat your chosen absolute path.The Redis command was
/opt/homebrew/bin/redis-server --bind 127.0.0.1 --port 6395 --save '' --appendonly noThe exact proxy command in the validation checkout was
Use the absolute path where you saved the config when reproducing. Both router and coordination state use Redis 6395. Reload and detailed debug were omitted for these pinned two-worker runs. Schema updates were disabled during proxy runs because the normal migration resolver was exercised separately. Sixteen authenticated management requests were observed on sockets owned by both workers in each leg.
To run the after leg, stop this proxy, checkout
42888f89250f26c3d50f7d81e6488bbe31ae8da4or its backend-equivalent finalf7504bed90f74a2155164cd2e0a54012f2796a1e, run the same resolver and isolated Prisma generation commands, then start with the same config, database, Redis and worker count. The measured primary-before service ran against the additive schema too; the old source still rejected the unsupported request fields.Complete client, save as pr_client.py
Run from the selected checkout with
.venv/bin/python -u pr_client.py. The local run used the absolute script path/Users/tin/Documents/Codex/2026-11-18/can/work/validation52787/live/pr_client.py. Both outputs below came from this exact client.Before
37a637dc163e8d9e9ff18befb8bd71f1de2e386cPermanent app
budgetand global memberbudgetrequests returned HTTP 422. Existing nonexpiring app policies remained 700. Their old temporary increment raised them to 750, then expiry restored 700. The unrelated app and global member remained 202 and 111.Actual before client output, exit 0
After
42888f89250f26c3d50f7d81e6488bbe31ae8da4, backend equivalent tof7504bed90f74a2155164cd2e0a54012f2796a1eThe same permanent requests returned HTTP 200. Copies retained omitted limits and reset timestamps; subsequent edits reused private IDs. App grants expired to the edited bases, 800 and 400. Omitting a legacy override preserved it; explicit
budget_override:nullconverted it while retaining RPM 29. The global member approved grant reached 900 and expired to the edited base 400 with RPM 31.Actual after client output, exit 0
The full acceptance run used
.venv/bin/python -u /Users/tin/Documents/Codex/2026-11-18/can/work/validation52787/live/validate.py final42888-acceptance --acceptanceand reportedRESULT 101 passed, 0 failed. It additionally covered all six organization partial-copy variants, scalar zero/null and per-model JSON-null clearing, custom-to-preset/inheritance cleanup, legacy overlapping grants, persisted/API agreement, cascade cleanup, empty-PUT preservation, and five attached-budget/budget/deleterequests returning 409 without deleting their rows. Full JSON and logs are supplementary evidence, not a replacement for the standalone primary client above.The migration check adopted the 261-migration merge-base schema, seeded legacy associations, applied
20261119000000_app_association_base_budgetsonce, and reran the normal resolver. New association columns were null, old IDs/budgets/spend/reset values were unchanged, and the rerun had no pending migrations and one successful ledger entry. This checks normal resolver idempotence, not raw ALTER TABLE replay.The live backend console on 4353 completed its after smoke run in 19.486 seconds. It creates fresh fixtures and streams real requests, and is labeled as a backend API console. The parent owns the actual recording; the dashboard on 4354 is a separate UI proof surface.
Type
Bug Fix and New Feature
Caveats
Severe
/budget/delete.Low
Final Attestation
Note
High Risk
Changes core budget persistence, effective-limit resolution, deletion rules, and PUT semantics for customer/app associations—areas that directly affect spend enforcement and authorization.
Overview
Introduces permanent base budgets (
budget/budget_id) for customer members and app–customer org/member associations, separate from expiringbudget_overridegrants. A migration and Prisma schema add nullablebudget_idandbudget_override_expires_aton app association tables with FKs toLiteLLM_BudgetTable.Backend: First custom edits fork shared presets into private budget rows (via
private_budget_patch/fork_budget) so partial updates keep inherited TPM/RPM, windows, and models. Legacy non-expiring overrides can be promoted to permanentbudget_idwhen clients send explicitbudgetplusbudget_override: null. App PUT handlers persist base vs override independently, use row locks, and compute effective policy from base + active override. Member updates and budget-increase approval callpreserve_member_custom_budgetso grants do not wipe permanent limits./budget/deleteusesdelete_unattached_customer_budgetand returns 409 when a budget is still referenced by customer or app entities.API & UI: Member and app PUT/PATCH models accept
budgetwith validators rejecting preset + custom in one request. Dashboard forms send permanent limits asbudget(not onlybudget_override) and block simultaneous preset selection and custom edits.Breaking: Empty or partial app association PUTs no longer clear omitted tier/override/member-default fields—callers must send explicit nulls. Detach budgets through owning entities before generic delete.
Reviewed by Cursor Bugbot for commit 744eb97ba910a3aadb023149bc7c1af9757ce3e3. Bugbot is set up for automated code reviews on this repo. Configure here.