Skip to content

fix(customer-management)!: preserve permanent budgets across temporary increases - #52787

Merged
tin-berri merged 17 commits into
mainfrom
litellm_customer_member_base_budget
Nov 19, 2026
Merged

tin-berri merged 17 commits into
mainfrom
litellm_customer_member_base_budget

Conversation

@tin-berri

@tin-berri tin-berri commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Temporary increases can replace permanent custom limits.
  • Partial edits can drop inherited or hidden restrictions.
  • Deletion can leave private app budgets behind.

How it solves it:

  • Copy preset settings into private budgets on first customization.
  • Keep permanent limits and expiring grants independent.
  • Preserve hidden policies and reclaim unreferenced private budgets.
  • Share policy resolution and bounded deletion helpers.

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.

  1. Open http://127.0.0.1:4354/customers/usage?org=app-budget-ui-org and edit Budget Validation App A.
  2. Select Custom budget, enter 750 in Spend limit, leave other fields untouched, save, and reopen.
  3. The saved limit is 750, but TPM, RPM, reset period, and the yearly cap are gone.

Before saving and reopening the same app budget

After, the same edit preserves the inherited policy in an independent permanent budget.

  1. Open http://127.0.0.1:4354/customers/usage?org=app-budget-ui-org and edit Budget Validation App A.
  2. Select Custom budget, enter 750 in Spend limit, leave other fields untouched, save, and reopen.
  3. The saved limit is 750, with 1,700 TPM, 17 RPM, monthly reset, and the 6,000 yearly cap retained.

After saving and reopening the same app budget

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_id and 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_id with 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 budget and explicit budget_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: null returns to inheritance. App organization policies resolve their own budget, the legacy tier reference, then the app default tier. The legacy tier_budget_id input 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_budgets adds nullable budget_id and budget_override_expires_at columns 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

  • Meaningful regressions cover the reported defects.
  • Focused backend, dashboard, and PostgreSQL tests passed.
  • Required checks passed on the final pushed commit.
  • Scope remains permanent and temporary customer budgets.
  • Latest automated reviews completed with findings addressed.

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-dashboard in the same checkout.

export LENS_DEV_PROXY_URL=http://127.0.0.1:4352
export NEXT_PUBLIC_BASE_URL=http://127.0.0.1:4354
export PROXY_BASE_URL=http://127.0.0.1:4354
export NEXT_TELEMETRY_DISABLED=1
node node_modules/next/dist/bin/next dev --webpack --hostname 127.0.0.1 --port 4354

Use the locally supplied UI_USERNAME and UI_PASSWORD to sign in. The visible deployment-warning banner is the gateway's env_credential_login warning for these local environment credentials. /health/deployment_warnings returned 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 proof directory. They read only the local master key from private.json. Create that file from your existing LITELLM_MASTER_KEY without printing the value.

mkdir -p proof
chmod 700 proof
python3 - <<'PYKEY'
import json, os
from pathlib import Path
path = Path("proof/private.json")
path.write_text(json.dumps({"master_key": os.environ["LITELLM_MASTER_KEY"]}))
path.chmod(0o600)
PYKEY
python3 proof/ui_fixture.py
python3 proof/ui_proof_fixture.py reset --name before-initial

Save as proof/ui_fixture.py.

import json
from pathlib import Path
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen

WORK = Path(__file__).parent
SETTINGS = json.loads((WORK / "private.json").read_text())
ORG = "app-budget-ui-org"
TEAM = "app-budget-ui-team"
MEMBER = "app-budget-ui-member"
POLICY = {"max_budget": 500, "budget_duration": "1mo", "tpm_limit": 1700, "rpm_limit": 17,
          "budget_limits": [{"budget_duration": "12mo", "max_budget": 6000}], "cap_policy": "pause_allow_increase"}


def request(method, path, body=None, missing=False):
    req = Request("http://127.0.0.1:4352" + path, method=method,
                  data=json.dumps(body).encode() if body is not None else None,
                  headers={"Authorization": "Bearer " + SETTINGS["master_key"], "Content-Type": "application/json"})
    try:
        with urlopen(req, timeout=20) as response:
            raw = response.read()
            result = json.loads(raw) if raw else None
    except HTTPError as error:
        if missing and error.code == 404:
            return None
        raise
    if method != "GET":
        time.sleep(.1)
    return result


def api(method, path, body=None, missing=False):
    return request(method, "/management/v1" + path, body, missing)


if (WORK / "ui-fixture.json").exists():
    existing = json.loads((WORK / "ui-fixture.json").read_text())
    assert api("GET", "/customer_organizations/" + ORG, missing=True)
    print("Existing persistent UI fixture preserved.", ORG, MEMBER)
else:
    api("PUT", "/apps/definition", {"resource_type": "team"})
    groups = api("GET", "/customer_organization_budget_groups")
    result = api("PATCH", "/customer_organization_budget_groups",
                 {"expected_revision": groups["budget_groups_revision"], "default_budget_template": None,
                  "default_budgets": [*groups["default_budgets"], {"name": "UI Standard", **POLICY},
                                      {"name": "UI Plus", **POLICY, "max_budget": 800}]})
    presets = {group["name"]: group["budget_id"] for group in result["default_budgets"]
               if group["name"] in ("UI Standard", "UI Plus")}
    organization = api("POST", "/customer_organizations",
                       {"customer_org_id": ORG, "alias": "Budget Validation Organization",
                        "default_budgets": [{"name": "Member Standard", **POLICY, "max_budget": 111}]})
    api("POST", "/customer_teams", {"customer_team_id": TEAM, "alias": "Budget Validation Team", "parent_org_id": ORG})
    api("POST", "/customer_members", {"customer_member_id": MEMBER, "alias": "Budget Validation Member",
                                      "parent_team_ids": [TEAM]})
    apps = []
    for label, cap in (("A", 201), ("B", 202)):
        team = request("POST", "/team/new", {"team_alias": "Budget Validation App " + label})
        app = api("POST", "/apps", {"resource_id": team["team_id"], "default_tier_budget_id": presets["UI Standard"],
                                    "default_customer_member_budget": {**POLICY, "max_budget": cap}})
        api("PUT", f"/apps/{app['app_id']}/customer_organizations/{ORG}", {"tier_budget_id": presets["UI Standard"]})
        api("PUT", f"/apps/{app['app_id']}/customer_members/{MEMBER}", {})
        apps.append({"label": label, "app_id": app["app_id"], "team_id": team["team_id"]})
    (WORK / "ui-fixture.json").write_text(json.dumps({
        "customer_org_id": ORG, "customer_team_id": TEAM, "customer_member_id": MEMBER,
        "organization_member_preset_id": organization["default_budget_template_id"],
        "presets": presets, "apps": apps, "proxy": "http://127.0.0.1:4352", "dashboard": "http://127.0.0.1:4354",
        "private_credentials_file": str(WORK / "private.json"),
    }, indent=2))
    print("Created persistent UI fixture.", ORG, MEMBER)

Save as proof/ui_proof_fixture.py.

"""Safe fixture reset and API observations for the real dashboard proof."""

import argparse
import json
from pathlib import Path
from urllib.request import Request, urlopen

WORK = Path(__file__).resolve().parent
FIXTURE = json.loads((WORK / "ui-fixture.json").read_text())
PRIVATE = json.loads((WORK / "private.json").read_text())
PREFIX = "http://127.0.0.1:4352/management/v1"
ORG = FIXTURE["customer_org_id"]
MEMBER = FIXTURE["customer_member_id"]


def api(method, path, body=None):
    req = Request(
        PREFIX + path,
        method=method,
        data=None if body is None else json.dumps(body).encode(),
        headers={
            "Authorization": "Bearer " + PRIVATE["master_key"],
            "Content-Type": "application/json",
        },
    )
    with urlopen(req, timeout=30) as response:
        return json.load(response)


def snapshot():
    return {
        "runtime": json.loads((WORK / "runtime.json").read_text()),
        "organization": api("GET", f"/customer_organizations/{ORG}"),
        "member": api("GET", f"/customer_members/{MEMBER}"),
        "apps": [
            {
                "label": app["label"],
                "organization": api("GET", f"/apps/{app['app_id']}/customer_organizations/{ORG}"),
                "member": api("GET", f"/apps/{app['app_id']}/customer_members/{MEMBER}"),
            }
            for app in FIXTURE["apps"]
        ],
    }


def reset():
    org = api("GET", f"/customer_organizations/{ORG}")
    plus = next((group for group in org["default_budgets"] if group["name"] == "Member Plus"), None)
    if plus is None:
        org = api("POST", f"/customer_organizations/{ORG}/default_budgets", {
            "name": "Member Plus", "max_budget": 222, "budget_duration": "1mo",
            "tpm_limit": 3400, "rpm_limit": 34,
        })
        plus = next(group for group in org["default_budgets"] if group["name"] == "Member Plus")
    FIXTURE["organization_member_plus_preset_id"] = plus["budget_id"]
    (WORK / "ui-fixture.json").write_text(json.dumps(FIXTURE, indent=2))
    api("PATCH", f"/customer_members/{MEMBER}", {
        "budget_id": FIXTURE["organization_member_preset_id"],
        "budget_override": None, "budget_override_expires_at": None,
    })
    for app in FIXTURE["apps"]:
        api("PUT", f"/apps/{app['app_id']}/customer_organizations/{ORG}", {
            "tier_budget_id": FIXTURE["presets"]["UI Standard"],
            "budget_override": None, "customer_member_budget": None,
        })
        api("PUT", f"/apps/{app['app_id']}/customer_members/{MEMBER}", {"budget_override": None})
    return snapshot()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("action", choices=["reset", "snapshot"])
    parser.add_argument("--name", required=True)
    args = parser.parse_args()
    result = reset() if args.action == "reset" else snapshot()
    destination = WORK / "ui-proof" / (args.name + ".json")
    destination.parent.mkdir(exist_ok=True)
    destination.write_text(json.dumps(result, indent=2))
    print(destination)

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-initial to clear the baseline legacy overrides, then repeat the same clicks. python3 proof/ui_proof_fixture.py snapshot --name after-saved records 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 revision f7504bed90f74a2155164cd2e0a54012f2796a1e, 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 main comparison 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 check passed, 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.

uv run --no-sync pytest -q \
  tests/unit/proxy/management_endpoints/management_v1/test_apps.py \
  tests/unit/proxy/management_endpoints/management_v1/test_customer_budget_increase_requests.py \
  tests/unit/proxy/management_endpoints/management_v1/test_customers.py \
  tests/unit/proxy/management_endpoints/test_budget_endpoints.py \
  tests/unit/proxy/management_helpers/test_apps.py \
  tests/unit/proxy/management_helpers/test_customer_hierarchy.py
# 358 passed
make check
# check: PASS

From litellm/ui/litellm-dashboard.

node_modules/.bin/vitest run \
  'src/app/(dashboard)/apps/_components/CustomerMemberApps.integration.test.tsx' \
  'src/app/(dashboard)/apps/_components/CustomerOrganizationApps.integration.test.tsx' \
  'src/app/(dashboard)/apps/_components/appForms.test.ts' \
  'src/app/(dashboard)/customers/_components/CustomerHierarchySettings.integration.test.tsx' \
  'src/app/(dashboard)/customers/_components/customerHierarchyForms.test.ts' \
  'src/app/(dashboard)/customers/_components/CreateCustomerHierarchyDialog.test.tsx' \
  'src/app/(dashboard)/apps/_components/AppsManager.integration.test.tsx'
# 7 files passed, 157 tests passed

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

Final live API result

Screenshots / Proof of Fix

The real two-worker proxy passed 101 live API/database assertions at 42888f89250f26c3d50f7d81e6488bbe31ae8da4. The recorded product commit is f7504bed90f74a2155164cd2e0a54012f2796a1e. 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.prisma is 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 at 67b7703613a53e1ca15bb8b40d887eccc88fe5fd caught 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/completions probes 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 is make 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_USERNAME and UI_PASSWORD locally. Never print or commit them. DATABASE_URL must target that fresh local database and have no query parameters for the psycopg client. The proxy used the same URL with ?connection_limit=4 appended.

The remaining environment was

export PYTHONPATH="$PWD"
export PYTHON_DOTENV_DISABLED=1
export LITELLM_LOCAL_MODEL_COST_MAP=True
export DISABLE_SCHEMA_UPDATE=true
export REDIS_HOST=127.0.0.1
export REDIS_PORT=6395
export LITELLM_LOG=ERROR
export NEXT_PUBLIC_BASE_URL=http://127.0.0.1:4354
export PROXY_BASE_URL=http://127.0.0.1:4354
export VALIDATION_PROXY_URL=http://127.0.0.1:4352

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.

git checkout --detach 37a637dc163e8d9e9ff18befb8bd71f1de2e386c
.venv/bin/python -m prisma db push --skip-generate \
  --schema litellm/proxy-extras/litellm_proxy_extras/schema.prisma
PYTHONPATH="$PWD/litellm/proxy-extras:$PWD" .venv/bin/python -c \
  'from litellm_proxy_extras.utils import ProxyExtrasDBManager; assert ProxyExtrasDBManager.setup_database(use_migrate=True,use_v2_resolver=True)'
.venv/bin/python -m prisma generate --schema litellm/proxy/schema.prisma

Save this exact config as proxy-config.yaml at your chosen absolute path.

model_list:
  - model_name: validation-no-inference
    litellm_params:
      model: openai/validation-no-inference
      api_base: http://127.0.0.1:9/v1
      api_key: local-validation-placeholder
      timeout: 1
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  disable_prisma_schema_update: true
  coordination_redis:
    host: 127.0.0.1
    port: 6395
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6395
  num_retries: 0
  timeout: 2

The Redis command was

/opt/homebrew/bin/redis-server --bind 127.0.0.1 --port 6395 --save '' --appendonly no

The exact proxy command in the validation checkout was

.venv/bin/python litellm/proxy/proxy_cli.py \
  --config /Users/tin/Documents/Codex/2026-11-18/can/work/validation52787/live/proxy-config.yaml \
  --host 127.0.0.1 --port 4352 --num_workers 2 --use_v2_migration_resolver

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 42888f89250f26c3d50f7d81e6488bbe31ae8da4 or its backend-equivalent final f7504bed90f74a2155164cd2e0a54012f2796a1e, 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.

import json
import os
import subprocess
import time
from datetime import datetime, timedelta, timezone

import httpx
import psycopg

assert os.environ["VALIDATION_PROXY_URL"] == "http://127.0.0.1:4352"
assert "/codex_app_budget_validation_" in os.environ["DATABASE_URL"]
client = httpx.Client(
    base_url=os.environ["VALIDATION_PROXY_URL"],
    headers={"Authorization": "Bearer " + os.environ["LITELLM_MASTER_KEY"]},
    timeout=30,
)
db = psycopg.connect(os.environ["DATABASE_URL"], autocommit=True)
db.execute("SET TIME ZONE 'UTC'")
prefix = "/management/v1"
run = "pr52787-" + str(time.time_ns())
policy = {
    "max_budget": 500, "budget_duration": "1mo", "tpm_limit": 1700, "rpm_limit": 17,
    "budget_limits": [{"budget_duration": "12mo", "max_budget": 6000}],
    "cap_policy": "pause_allow_increase",
}
owned, apps, teams = set(), [], []


def retain(value):
    if isinstance(value, dict):
        for key, item in value.items():
            if (key == "budget_id" or key.endswith("_budget_id") or key == "default_budget_template_id") and item:
                owned.add(item)
            retain(item)
    elif isinstance(value, list):
        for item in value:
            retain(item)


def call(method, path, body=None, *, expected=None, track=True):
    response = client.request(method, path, json=body)
    data = response.json() if response.content else {}
    accepted = response.status_code == expected if expected is not None else 200 <= response.status_code < 300
    assert accepted, (method, path, response.status_code, data)
    if track:
        retain(data)
    if method != "GET":
        time.sleep(0.1)
    return data


def api(method, path, body=None, **kwargs):
    return call(method, prefix + path, body, **kwargs)


def show(label, rows):
    print(label, json.dumps([
        {
            "base": row.get("budget", {}).get("max_budget") if row.get("budget") else None,
            "effective": row["effective_budget"]["max_budget"],
            "duration": row["effective_budget"]["budget_duration"],
            "rpm": row["effective_budget"]["rpm_limit"],
            "tpm": row["effective_budget"]["tpm_limit"],
        }
        for row in rows
    ]), flush=True)


def reset(budget_id):
    return db.execute(
        'SELECT budget_reset_at FROM "LiteLLM_BudgetTable" WHERE budget_id=%s', (budget_id,)
    ).fetchone()[0]


def update_groups(add=None, remove=None):
    groups = api("GET", "/customer_organization_budget_groups", track=False)
    default_name = next(
        (group["name"] for group in groups["default_budgets"]
         if group["budget_id"] == groups["default_budget_template_id"]), None
    )
    return api("PATCH", "/customer_organization_budget_groups", {
        "expected_revision": groups["budget_groups_revision"], "default_budget_template": default_name,
        "default_budgets": [group for group in groups["default_budgets"] if group["budget_id"] != remove]
        + ([add] if add else []),
    }, track=False)


print("SOURCE", subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), flush=True)
api("PUT", "/apps/definition", {"resource_type": "team"})
groups = update_groups(add={"name": run, **policy})
preset = next(group["budget_id"] for group in groups["default_budgets"] if group["name"] == run)
owned.add(preset)
api("POST", "/customer_organizations", {
    "customer_org_id": run, "default_budgets": [{"name": run, **policy, "max_budget": 111}],
})
try:
    api("POST", "/customer_teams", {"customer_team_id": run, "parent_org_id": run})
    api("POST", "/customer_members", {"customer_member_id": run, "parent_team_ids": [run]})
    for maximum in (201, 202):
        team = call("POST", "/team/new", {"team_alias": run + str(maximum)})
        teams.append(team["team_id"])
        app = api("POST", "/apps", {
            "resource_id": team["team_id"], "default_tier_budget_id": preset,
            "default_customer_member_budget": {**policy, "max_budget": maximum},
        })
        apps.append(app)
        api("PUT", f"/apps/{app['app_id']}/customer_organizations/{run}", {"tier_budget_id": preset})
    paths = (
        f"/apps/{apps[0]['app_id']}/customer_organizations/{run}",
        f"/apps/{apps[0]['app_id']}/customer_members/{run}",
    )
    initial = [api("GET", path) for path in paths]
    show("INHERITED", initial)
    resets = [reset(preset), reset(apps[0]["default_customer_member_budget_id"])]
    attempts = [client.put(prefix + path, json={"budget": {"max_budget": maximum}})
                for path, maximum in zip(paths, (750, 350))]
    print("PERMANENT PUT", [response.status_code for response in attempts], flush=True)
    supported = all(response.status_code == 200 for response in attempts)
    if supported:
        time.sleep(0.1)
        copied = [response.json() for response in attempts]
        retain(copied)
        for row, source, maximum in zip(copied, initial, (750, 350)):
            assert row["budget"] == {**source["effective_budget"], "max_budget": maximum}
        assert [reset(row["budget_id"]) for row in copied] == resets
        changed = [api("PUT", path, {"budget": {"rpm_limit": 19}}) for path in paths]
        assert [row["budget_id"] for row in changed] == [row["budget_id"] for row in copied]
        print("COPIED LIMITS / RESET / SAME IDS", True, flush=True)
        expires = datetime.now(timezone.utc) + timedelta(seconds=4)
        show("TEMPORARY", [api("PUT", path, {
            "budget_override": {"max_budget": maximum}, "budget_override_expires_at": expires.isoformat(),
        }) for path, maximum in zip(paths, (1000, 600))])
        show("EDIT BASE UNDER GRANT", [
            api("PUT", path, {"budget": {"max_budget": maximum}}) for path, maximum in zip(paths, (800, 400))
        ])
        time.sleep(max(0, (expires - datetime.now(timezone.utc)).total_seconds()) + 0.3)
        expired = [api("GET", path) for path in paths]
        show("EXPIRED", expired)
        assert [row["effective_budget"]["max_budget"] for row in expired] == [800, 400]
    else:
        assert all(response.status_code == 422 for response in attempts)
        print("PERMANENT ERRORS", [response.json() for response in attempts], flush=True)
    for path in paths:
        api("PUT", path, {"budget_override": None})
    legacy = [api("PUT", path, {"budget_override": {"max_budget": 700, "rpm_limit": 29}}) for path in paths]
    show("LEGACY NONEXPIRING", legacy)
    edited = [api("PUT", path, {"budget": {"max_budget": 850}}, expected=200 if supported else 422) for path in paths]
    print("LEGACY PERMANENT EDIT", "HTTP 200" if supported else "HTTP 422", flush=True)
    if supported:
        show("OMITTED LEGACY OVERRIDE PRESERVED", edited)
        assert all(row["budget"]["max_budget"] == 850 and row["effective_budget"]["max_budget"] == 700 for row in edited)
        converted = [api("PUT", path, {"budget": {"max_budget": 850}, "budget_override": None}) for path in paths]
        show("EXPLICIT NULL CONVERTS LEGACY POLICY", converted)
        assert all(row["effective_budget"]["max_budget"] == 850 and row["budget"]["rpm_limit"] == 29 for row in converted)
    else:
        expires = datetime.now(timezone.utc) + timedelta(seconds=4)
        for path in paths:
            api("PUT", path, {"budget_override": {"max_budget": 900},
                             "budget_override_expires_at": expires.isoformat()}, expected=422)
        print("EXPIRING OVERRIDE", "HTTP 422", flush=True)
        for row in legacy:
            db.execute(
                'UPDATE "LiteLLM_BudgetTable" SET temp_budget_increase=50,temp_budget_expiry=%s WHERE budget_id=%s',
                (expires, row["budget_override_id"]),
            )
        show("OLD TEMP COLUMNS ACTIVE", [api("GET", path) for path in paths])
        time.sleep(max(0, (expires - datetime.now(timezone.utc)).total_seconds()) + 0.3)
        show("OLD TEMP COLUMNS EXPIRED", [api("GET", path) for path in paths])
    isolated = [api("GET", f"/apps/{apps[1]['app_id']}/customer_members/{run}"),
                api("GET", f"/customer_members/{run}")]
    show("OTHER APP / GLOBAL MEMBER", isolated)
    assert [row["effective_budget"]["max_budget"] for row in isolated] == [202, 111]
    member_path = f"/customer_members/{run}"
    member_attempt = client.patch(prefix + member_path, json={"budget": {"max_budget": 350}})
    print("GLOBAL MEMBER PERMANENT PATCH", member_attempt.status_code, flush=True)
    if member_attempt.status_code == 200:
        member_custom = member_attempt.json()
        retain(member_custom)
        assert member_custom["budget"] == {**isolated[1]["budget"], "max_budget": 350}
        member_edited = api("PATCH", member_path, {"budget": {"rpm_limit": 31}})
        assert member_edited["budget_id"] == member_custom["budget_id"]
        expires = datetime.now(timezone.utc) + timedelta(seconds=4)
        filed = api("POST", "/customer_budget_increase_requests", {
            "customer_member_id": run, "requested_max_budget": 900, "expires_at": expires.isoformat(),
        })
        api("PUT", f"/customer_budget_increase_requests/{filed['request_id']}/approve")
        show("GLOBAL MEMBER APPROVED GRANT", [api("GET", member_path)])
        under_grant = api("PATCH", member_path, {"budget": {"max_budget": 400}})
        assert under_grant["budget"]["max_budget"] == 400 and under_grant["effective_budget"]["max_budget"] == 900
        time.sleep(max(0, (expires - datetime.now(timezone.utc)).total_seconds()) + 0.3)
        member_expired = api("GET", member_path)
        show("GLOBAL MEMBER APPROVED GRANT EXPIRED", [member_expired])
        assert member_expired["effective_budget"]["max_budget"] == 400
        assert member_expired["effective_budget"]["rpm_limit"] == 31
    else:
        assert member_attempt.status_code == 422, member_attempt.text
        print("GLOBAL MEMBER PERMANENT ERROR", member_attempt.json(), flush=True)
finally:
    api("DELETE", f"/customer_organizations/{run}?cascade=true", expected=204)
    for team_id in teams:
        call("POST", "/team/delete", {"team_ids": [team_id]})
    for app in apps:
        db.execute('DELETE FROM "LiteLLM_AppTable" WHERE app_id=%s', (app["app_id"],))
    update_groups(remove=preset)
    for budget_id in owned:
        db.execute('DELETE FROM "LiteLLM_BudgetTable" WHERE budget_id=%s', (budget_id,))
    print("FIXTURE CLEANUP COMPLETE", flush=True)

Before 37a637dc163e8d9e9ff18befb8bd71f1de2e386c

Permanent app budget and global member budget requests 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
SOURCE 37a637dc163e8d9e9ff18befb8bd71f1de2e386c
INHERITED [{"base": null, "effective": 500.0, "duration": "1mo", "rpm": 17, "tpm": 1700}, {"base": null, "effective": 201.0, "duration": "1mo", "rpm": 17, "tpm": 1700}]
PERMANENT PUT [422, 422]
PERMANENT ERRORS [{'type': 'urn:litellm:error:invalid-request-body', 'title': 'Invalid request body', 'status': 422, 'detail': 'budget: Extra inputs are not permitted'}, {'type': 'urn:litellm:error:invalid-request-body', 'title': 'Invalid request body', 'status': 422, 'detail': 'budget: Extra inputs are not permitted'}]
LEGACY NONEXPIRING [{"base": null, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}, {"base": null, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}]
LEGACY PERMANENT EDIT HTTP 422
EXPIRING OVERRIDE HTTP 422
OLD TEMP COLUMNS ACTIVE [{"base": null, "effective": 750.0, "duration": null, "rpm": 29, "tpm": null}, {"base": null, "effective": 750.0, "duration": null, "rpm": 29, "tpm": null}]
OLD TEMP COLUMNS EXPIRED [{"base": null, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}, {"base": null, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}]
OTHER APP / GLOBAL MEMBER [{"base": null, "effective": 202.0, "duration": "1mo", "rpm": 17, "tpm": 1700}, {"base": null, "effective": 111.0, "duration": "1mo", "rpm": 17, "tpm": 1700}]
GLOBAL MEMBER PERMANENT PATCH 422
GLOBAL MEMBER PERMANENT ERROR {'type': 'urn:litellm:error:invalid-request-body', 'title': 'Invalid request body', 'status': 422, 'detail': 'budget: Extra inputs are not permitted'}
FIXTURE CLEANUP COMPLETE

After 42888f89250f26c3d50f7d81e6488bbe31ae8da4, backend equivalent to f7504bed90f74a2155164cd2e0a54012f2796a1e

The 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:null converted 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
SOURCE 42888f89250f26c3d50f7d81e6488bbe31ae8da4
INHERITED [{"base": null, "effective": 500.0, "duration": "1mo", "rpm": 17, "tpm": 1700}, {"base": null, "effective": 201.0, "duration": "1mo", "rpm": 17, "tpm": 1700}]
PERMANENT PUT [200, 200]
COPIED LIMITS / RESET / SAME IDS True
TEMPORARY [{"base": 750.0, "effective": 1000.0, "duration": "1mo", "rpm": 19, "tpm": 1700}, {"base": 350.0, "effective": 600.0, "duration": "1mo", "rpm": 19, "tpm": 1700}]
EDIT BASE UNDER GRANT [{"base": 800.0, "effective": 1000.0, "duration": "1mo", "rpm": 19, "tpm": 1700}, {"base": 400.0, "effective": 600.0, "duration": "1mo", "rpm": 19, "tpm": 1700}]
EXPIRED [{"base": 800.0, "effective": 800.0, "duration": "1mo", "rpm": 19, "tpm": 1700}, {"base": 400.0, "effective": 400.0, "duration": "1mo", "rpm": 19, "tpm": 1700}]
LEGACY NONEXPIRING [{"base": 800.0, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}, {"base": 400.0, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}]
LEGACY PERMANENT EDIT HTTP 200
OMITTED LEGACY OVERRIDE PRESERVED [{"base": 850.0, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}, {"base": 850.0, "effective": 700.0, "duration": null, "rpm": 29, "tpm": null}]
EXPLICIT NULL CONVERTS LEGACY POLICY [{"base": 850.0, "effective": 850.0, "duration": null, "rpm": 29, "tpm": null}, {"base": 850.0, "effective": 850.0, "duration": null, "rpm": 29, "tpm": null}]
OTHER APP / GLOBAL MEMBER [{"base": null, "effective": 202.0, "duration": "1mo", "rpm": 17, "tpm": 1700}, {"base": 111.0, "effective": 111.0, "duration": "1mo", "rpm": 17, "tpm": 1700}]
GLOBAL MEMBER PERMANENT PATCH 200
GLOBAL MEMBER APPROVED GRANT [{"base": 350.0, "effective": 900.0, "duration": "1mo", "rpm": 31, "tpm": 1700}]
GLOBAL MEMBER APPROVED GRANT EXPIRED [{"base": 400.0, "effective": 400.0, "duration": "1mo", "rpm": 31, "tpm": 1700}]
FIXTURE CLEANUP COMPLETE

The full acceptance run used .venv/bin/python -u /Users/tin/Documents/Codex/2026-11-18/can/work/validation52787/live/validate.py final42888-acceptance --acceptance and reported RESULT 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/delete requests 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_budgets once, 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

  • Send explicit nulls when clearing app association policies.
  • Detach customer/app references before calling /budget/delete.

Low

  • Inference probes verify budget gating, not provider completions.

Final Attestation

  • Final automated review and required checks are complete.

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 expiring budget_override grants. A migration and Prisma schema add nullable budget_id and budget_override_expires_at on app association tables with FKs to LiteLLM_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 permanent budget_id when clients send explicit budget plus budget_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 call preserve_member_custom_budget so grants do not wipe permanent limits. /budget/delete uses delete_unattached_customer_budget and returns 409 when a budget is still referenced by customer or app entities.

API & UI: Member and app PUT/PATCH models accept budget with validators rejecting preset + custom in one request. Dashboard forms send permanent limits as budget (not only budget_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.

@veria-ai

veria-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 3 · PR risk: 0/10

Reviews

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review the permanent member budget separation, legacy override preservation, and temporary increase expiry behavior on the latest commit.

@tin-berri

Copy link
Copy Markdown
Contributor Author

@cursor review the permanent member budget separation, ownership checks, and temporary increase expiry behavior on the latest commit.

@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The reviewed revision appears safe to merge, with no new blocking issues found.

Summary

This PR separates permanent customer budgets from temporary increases, preserves inherited limits on custom edits, and cleans up unused private budgets.

  • Customer and app budgets keep permanent limits separate from temporary increases.
  • Customer cleanup reclaims unused app budgets and blocks deletion of attached budgets.

Tests were inspected but not run during this review.

Reviews (7) · Last reviewed commit: "fix(customer-budgets): build immutable p..." · Reviewed by Greptile

greptile-apps[bot]

This comment was marked as resolved.

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review the latest commit. Creation now locks the organization before capacity, with a failing-before and passing-after PostgreSQL regression.

@tin-berri

Copy link
Copy Markdown
Contributor Author

@cursor review the latest commit, including consistent organization-first capacity locking and the PostgreSQL regression for concurrent member creation and moves.

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

devin-ai-integration[bot]

This comment was marked as resolved.

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review this update. First custom member edits now copy preset settings in the backend, preserving explicit nulls and temporary grants.

@tin-berri

Copy link
Copy Markdown
Contributor Author

@cursor bugbot run. Please review backend preset copying on first custom edits, explicit null handling, reset dates, and independent temporary grants.

@cursor

cursor Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Unable to authenticate your request. Please make sure to connect your GitHub account to Cursor. Go to Cursor

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Please review this update for preset snapshot correctness, explicit clears, unchanged reset dates, and temporary override isolation.

veria-ai[bot]

This comment was marked as resolved.

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

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review the latest fixes. Legacy promotion preserves expiring deltas, and organization deletion follows organization-first locking with failing-before regressions.

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Please review legacy budget promotion and cascading deletion on the latest commit, including the expiry and PostgreSQL contention regressions.

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

@devin-ai-integration
devin-ai-integration Bot requested a review from a team November 19, 2026 08:56
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review the latest commit, especially shared presets, private custom budgets, temporary expiry, app scope isolation, and migration compatibility.

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Please review the latest app association budget changes for ownership, expiry, isolation, and legacy compatibility regressions.

veria-ai[bot]

This comment was marked as resolved.

greptile-apps[bot]

This comment was marked as resolved.

cursor[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

veria-ai[bot]

This comment was marked as resolved.

@tin-berri tin-berri changed the title fix(customer-management): preserve custom budgets across temporary increases fix(customer-management)!: preserve permanent budgets across temporary increases Nov 19, 2026
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review 7f7d325. Updated migration notes and real dashboard/API proof cover permanent budgets, inherited limits, expiry, and isolation.

@CLAassistant

CLAassistant commented Nov 19, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

tin-berri and others added 17 commits November 19, 2026 18:40
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>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_customer_member_base_budget branch from 77d3975 to d33df0f Compare November 19, 2026 18:41
@tin-berri
tin-berri merged commit 4563cde into main Nov 19, 2026
52 checks passed
@tin-berri
tin-berri deleted the litellm_customer_member_base_budget branch November 19, 2026 18:55
yuneng-berri added a commit that referenced this pull request Nov 19, 2026
…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/.
yuneng-berri added a commit that referenced this pull request Nov 23, 2026
…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)
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.

3 participants