Skip to content

fix(proxy): track team member spend when the member has no budget - #41349

Merged
ryan-crabbe-berri merged 11 commits into
mainfrom
litellm_team_member_spend_without_budget
Sep 18, 2026
Merged

ryan-crabbe-berri merged 11 commits into
mainfrom
litellm_team_member_spend_without_budget

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Team member spend is only tracked when the member has a budget
  • Members without a budget silently show no spend on the Members tab
  • Re-adding a member who already has a row fails on the primary key
  • Resetting a team member's spend is API only, the dashboard has no action for it

How it solves it:

  • Every member add now writes a membership row, budget or not
  • A member add skips names already on the team, so their row and budget stay untouched and no stray budget is created
  • The spend writer upserts the membership row instead of updating one that may not exist
  • Members added before this fix get their row on their next request
  • The flush takes the same per-team advisory lock the team endpoints hold, then writes all member rows in one SQL upsert that only creates a row when the stored team roster still lists the user, so a flush that lands after /team/member_delete never recreates the removed row
  • The Members tab gets a Reset spend action that calls the existing reset endpoint

User Flow

Before: an admin adds a member with no budget, the member makes calls, and the admin never sees that member's spend

  1. Admin sends POST https://litellm-domain/team/new with {"team_alias": "member-spend"} and gets back a team_id
  2. Admin sends POST https://litellm-domain/team/member_add with {"team_id": "<team_id>", "member": {"user_id": "alice", "role": "user"}} and gets back "updated_team_memberships": []
  3. Admin sends POST https://litellm-domain/key/generate with {"team_id": "<team_id>", "user_id": "alice"} and hands the key to alice
  4. Alice sends POST https://litellm-domain/v1/chat/completions with that key and gets a normal 200 response
  5. Admin sends GET https://litellm-domain/team/info?team_id=<team_id> and sees the team's spend went up but team_memberships is []
  6. Admin opens https://litellm-domain/ui/teams/?team=<team_id>, Members tab, and alice's Current Cycle Spend and Total Spend both read -
  7. Admin wants to clear a member's spend, finds no action for it on the Members tab, and has to send POST https://litellm-domain/team/<team_id>/member/<user_id>/reset_spend by hand

After: the same steps, alice's spend shows up, and the admin can reset it from the dashboard

  1. Admin sends POST https://litellm-domain/team/new with {"team_alias": "member-spend"} and gets back a team_id
  2. Admin sends POST https://litellm-domain/team/member_add with the same body and gets back "updated_team_memberships": [{"user_id": "alice", "team_id": "<team_id>", "budget_id": null, "spend": 0, "total_spend": 0}]
  3. Admin sends POST https://litellm-domain/key/generate with {"team_id": "<team_id>", "user_id": "alice"} and hands the key to alice
  4. Alice sends POST https://litellm-domain/v1/chat/completions with that key and gets a normal 200 response
  5. Admin sends GET https://litellm-domain/team/info?team_id=<team_id> and team_memberships now lists alice with spend equal to the cost of her call
  6. Admin opens https://litellm-domain/ui/teams/?team=<team_id>, Members tab, and alice's Current Cycle Spend and Total Spend show the same amount
  7. Admin clicks the Reset spend icon on alice's row, confirms in the "Reset Team Member Spend" dialog, and sees "Team member spend reset to $0". Alice's Current Cycle Spend reads - and her Total Spend is unchanged

Relevant issues

Affected release

Linear ticket

Resolves LIT-7030

Also covers LIT-5502, the per-member spend report this depth item was opened for

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

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

Setup: two local proxies on litellm/proxy/dev_config.yaml sharing one Postgres, with real AWS Bedrock calls through the bedrock-converse-haiku-4-5 deployment. The Before side runs the merge base from a second worktree with PYTHONPATH pointed at it on port 4350, and the After side runs the PR tip on port 4349. The first four cases use the same script on both sides, where $LEG is base or head

The last case needs one call that costs more than the $0.01 member budget, so it uses bedrock-converse-opus-4-8 for that call. Its API steps only run on the PR tip, because the merge base never records spend for a member with no budget (that is the first case). What differs between its two sides is the dashboard: Before is the Members tab built from the merge base, After is the Members tab built from the PR tip, both pointed at the same proxy and the same team. The dashboard ran as npm run dev on port 3349, which serves the same page at http://localhost:3349/teams/?team=<team_id>

H=(-H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json")
BASE=http://localhost:4349   # http://localhost:4350 for the Before side
CHAT='{"model":"bedrock-converse-haiku-4-5","messages":[{"role":"user","content":"Say hi in one word"}],"max_tokens":5}'
new_team() { curl -s "$BASE/team/new" "${H[@]}" -d "{\"team_alias\":\"$1-$LEG\"}" | jq -r .team_id; }
add_member() { curl -s "$BASE/team/member_add" "${H[@]}" -d "{\"team_id\":\"$1\",\"member\":{\"user_id\":\"$2\",\"role\":\"user\"}}"; }
member_key() { curl -s "$BASE/key/generate" "${H[@]}" -d "{\"team_id\":\"$1\",\"user_id\":\"$2\"}" | jq -r .key; }
chat() { curl -s "$BASE/v1/chat/completions" -H "Authorization: Bearer $1" -H "Content-Type: application/json" -d "$CHAT" | jq -c '{model, content: .choices[0].message.content, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}'; }
team_info() { curl -s "$BASE/team/info?team_id=$1" "${H[@]}" | jq -c '{team_spend: .team_info.spend, team_memberships: [.team_memberships[] | {user_id, budget_id, spend}]}'; }
rows() { psql "$DATABASE_URL" -c "select user_id, budget_id, spend, total_spend from \"LiteLLM_TeamMembership\" where team_id = '$1';"; }
budget_rows() { psql "$DATABASE_URL" -c "select user_id, budget_id is not null as has_budget, spend, total_spend from \"LiteLLM_TeamMembership\" where team_id = '$1' order by user_id;"; }
orphan_budgets() { psql "$DATABASE_URL" -tAc "select count(*) from \"LiteLLM_BudgetTable\" b where b.created_at >= now() - interval '5 minutes' and not exists (select 1 from \"LiteLLM_TeamMembership\" m where m.budget_id = b.budget_id) and not exists (select 1 from \"LiteLLM_TeamTable\" t where t.metadata->>'team_member_budget_id' = b.budget_id);"; }

# case 1: member added with no budget
T1=$(new_team member-spend); add_member "$T1" "alice-$LEG" | jq -c '{updated_team_memberships}'
chat "$(member_key "$T1" "alice-$LEG")"; sleep 15; team_info "$T1"; rows "$T1"

# case 2: member rostered before the fix, so no membership row yet
T2=$(new_team member-missing-row); add_member "$T2" "carol-$LEG" | jq -c '{members: [.members_with_roles[].user_id]}'
psql "$DATABASE_URL" -c "delete from \"LiteLLM_TeamMembership\" where team_id = '$T2' and user_id = 'carol-$LEG';"
chat "$(member_key "$T2" "carol-$LEG")"; sleep 15; team_info "$T2"; rows "$T2"

# case 3: member removed before the spend flush
T3=$(new_team member-delete-race); add_member "$T3" "bob-$LEG" | jq -c '{members: [.members_with_roles[].user_id]}'
chat "$(member_key "$T3" "bob-$LEG")"
curl -s "$BASE/team/member_delete" "${H[@]}" -d "{\"team_id\":\"$T3\",\"user_id\":\"bob-$LEG\"}" | jq -c '{members: [.members_with_roles[].user_id]}'
sleep 15; team_info "$T3"; rows "$T3"

# case 4: member with a budget of 7 is listed again in a bulk member_add with a budget of 9 alongside a new member
T4=$(new_team readd-budget)
curl -s "$BASE/team/member_add" "${H[@]}" -d "{\"team_id\":\"$T4\",\"member\":{\"user_id\":\"hank-$LEG\",\"role\":\"user\"},\"max_budget_in_team\":7}" \
  | jq -c '{updated_team_memberships: [.updated_team_memberships[] | {user_id, has_budget: (.budget_id != null), max_budget: .litellm_budget_table.max_budget}]}'
chat "$(member_key "$T4" "hank-$LEG")"; sleep 15
echo "# before re-add"; budget_rows "$T4"; echo "orphan budgets created this run: $(orphan_budgets)"
curl -s "$BASE/team/member_add" "${H[@]}" -d "{\"team_id\":\"$T4\",\"member\":[{\"user_id\":\"hank-$LEG\",\"role\":\"user\"},{\"user_id\":\"ivy-$LEG\",\"role\":\"user\"}],\"max_budget_in_team\":9}" \
  | jq -c '{status: (.detail // "ok"), members: [.members_with_roles[]?.user_id]}'
echo "# after re-add"; budget_rows "$T4"; echo "orphan budgets created this run: $(orphan_budgets)"

# case 5: admin resets a member's spend (PR tip proxy only, see the setup note above)
SFX=$(date +%H%M%S)
memberships() { curl -s "$BASE/team/info?team_id=$1" "${H[@]}" | jq -c '[.team_memberships[] | {user_id, max_budget: .litellm_budget_table.max_budget, spend, total_spend}]'; }
hi() { curl -s "$BASE/v1/chat/completions" -H "Authorization: Bearer $1" -H "Content-Type: application/json" -d "$CHAT" | jq -c '{content: .choices[0].message.content, error: (.error.message // null)}'; }
T5=$(curl -s "$BASE/team/new" "${H[@]}" -d "{\"team_alias\":\"late-member-budget-$SFX\"}" | jq -r .team_id)
curl -s "$BASE/team/member_add" "${H[@]}" -d "{\"team_id\":\"$T5\",\"member\":[{\"user_id\":\"alice-$SFX\",\"role\":\"user\"},{\"user_id\":\"bob-$SFX\",\"role\":\"user\"}]}" | jq -c '{members: [.members_with_roles[].user_id]}'
K5=$(member_key "$T5" "alice-$SFX")
curl -s "$BASE/v1/chat/completions" -H "Authorization: Bearer $K5" -H "Content-Type: application/json" -d '{"model":"bedrock-converse-opus-4-8","messages":[{"role":"user","content":"Write a 500 word story about a lighthouse keeper"}],"max_tokens":900}' \
  | jq -c '{model, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}, error: (.error.message // null)}'
sleep 15; memberships "$T5"
curl -s "$BASE/team/update" "${H[@]}" -d "{\"team_id\":\"$T5\",\"team_member_budget\":0.01}" > /dev/null; memberships "$T5"
hi "$K5"
# reset alice's spend (dashboard steps below), then
hi "$K5"; memberships "$T5"

Before (a262672)

Member with no budget makes a real call

  1. /team/member_add returns no membership

    {"updated_team_memberships":[]}
    
  2. The chat call succeeds

    {"model":"bedrock-converse-haiku-4-5","content":"Hi!","usage":{"prompt_tokens":12,"completion_tokens":5}}
    
  3. /team/info shows the team was charged but has no member rows, and the table is empty

    {"team_spend":0.0000407,"team_memberships":[]}
     user_id | budget_id | spend | total_spend
    ---------+-----------+-------+-------------
    (0 rows)
    

Member rostered with no membership row makes a real call

  1. The member is on the roster and the delete finds nothing to remove, since the base never wrote a row

    {"members":["default_user_id","carol-base"]}
    DELETE 0
    
  2. The chat call succeeds

    {"model":"bedrock-converse-haiku-4-5","content":"Hi","usage":{"prompt_tokens":12,"completion_tokens":4}}
    
  3. The flush charges the team and leaves the member with no row

    {"team_spend":0.0000352,"team_memberships":[]}
     user_id | budget_id | spend | total_spend
    ---------+-----------+-------+-------------
    (0 rows)
    

Member removed before the spend flush

  1. The member is added, makes a call, and is removed before the flush

    {"members":["default_user_id","bob-base"]}
    {"model":"bedrock-converse-haiku-4-5","content":"Hi","usage":{"prompt_tokens":12,"completion_tokens":4}}
    {"members":["default_user_id"]}
    
  2. The flush charges the team and writes no member row

    {"team_spend":0.0000352,"team_memberships":[]}
     user_id | budget_id | spend | total_spend
    ---------+-----------+-------+-------------
    (0 rows)
    

Budgeted member listed again in a bulk member add

  1. The member gets a budget of 7 and makes a call, and the flush lands on their row

    {"updated_team_memberships":[{"user_id":"hank-base","has_budget":true,"max_budget":7.0}]}
    {"model":"bedrock-converse-haiku-4-5","content":"Hi!","usage":{"prompt_tokens":12,"completion_tokens":5}}
    # before re-add
      user_id  | has_budget |  spend   | total_spend
    -----------+------------+----------+-------------
     hank-base | t          | 4.07e-05 |    4.07e-05
    (1 row)
    
    orphan budgets created this run: 0
    
  2. The bulk add that lists them next to a new member fails on the primary key, so the new member is never added

    {"status":{"error":"Unable to add user - user_id='hank-base' user_email=None role='user', to team - 2aa5e02c-eff7-43e5-a3b2-8fad32d6ad89, for reason - Unique constraint failed on the fields: (`user_id`,`team_id`)"},"members":[]}
    # after re-add
      user_id  | has_budget |  spend   | total_spend
    -----------+------------+----------+-------------
     hank-base | t          | 4.07e-05 |    4.07e-05
    (1 row)
    
    orphan budgets created this run: 0
    

Admin resets a member's spend from the Members tab

  1. Alice makes a real call while she has no member budget, and her row carries the cost

    {"members":["default_user_id","alice-124519","bob-124519"]}
    {"model":"bedrock-converse-opus-4-8","usage":{"prompt_tokens":24,"completion_tokens":900},"error":null}
    [{"user_id":"default_user_id","max_budget":null,"spend":0.0,"total_spend":0.0},{"user_id":"bob-124519","max_budget":null,"spend":0.0,"total_spend":0.0},{"user_id":"alice-124519","max_budget":null,"spend":0.02262,"total_spend":0.02262}]
    
  2. The admin sets team_member_budget to 0.01 on the team. Every row gets the budget and alice keeps her spend

    [{"user_id":"default_user_id","max_budget":0.01,"spend":0.0,"total_spend":0.0},{"user_id":"bob-124519","max_budget":0.01,"spend":0.0,"total_spend":0.0},{"user_id":"alice-124519","max_budget":0.01,"spend":0.02262,"total_spend":0.02262}]
    
  3. Alice's next call is blocked

    {"content":null,"error":"Budget has been exceeded! TeamMember=alice-124519:ab61a1cb-d42e-4758-a984-da94ed1bf6e7 Current cost: 0.02262, Max budget: 0.01"}
    
  4. The admin opens http://localhost:4000/ui/teams/?team=ab61a1cb-d42e-4758-a984-da94ed1bf6e7 and clicks the Members tab. Alice is over her budget and her row only offers Edit and Delete, so the admin has to call the reset endpoint by hand

    Members tab at the merge base, alice's row has only Edit and Delete

After (dc49001)

Member with no budget makes a real call

  1. /team/member_add returns a membership with no budget

    {"updated_team_memberships":[{"user_id":"alice-head","team_id":"8a4f9f93-4537-4d8e-a701-989b9c48ba88","budget_id":null,"spend":0.0,"total_spend":0.0,"litellm_budget_table":null}]}
    
  2. The chat call succeeds

    {"model":"bedrock-converse-haiku-4-5","content":"Hi","usage":{"prompt_tokens":12,"completion_tokens":4}}
    
  3. /team/info shows the member's spend equals the team's spend, and the row carries both counters with budget_id NULL

    {"team_spend":0.0000352,"team_memberships":[{"user_id":"default_user_id","budget_id":null,"spend":0.0},{"user_id":"alice-head","budget_id":null,"spend":0.0000352}]}
         user_id     | budget_id |  spend   | total_spend
    -----------------+-----------+----------+-------------
     default_user_id |           |        0 |           0
     alice-head      |           | 3.52e-05 |    3.52e-05
    (2 rows)
    

Member rostered with no membership row makes a real call

  1. The member is on the roster and the row this side wrote is deleted by hand to mimic a member added before the fix

    {"members":["default_user_id","carol-head"]}
    DELETE 1
    
  2. The chat call succeeds

    {"model":"bedrock-converse-haiku-4-5","content":"Hey!","usage":{"prompt_tokens":12,"completion_tokens":5}}
    
  3. The flush recreates the row with that call's cost

    {"team_spend":0.0000407,"team_memberships":[{"user_id":"default_user_id","budget_id":null,"spend":0.0},{"user_id":"carol-head","budget_id":null,"spend":0.0000407}]}
         user_id     | budget_id |  spend   | total_spend
    -----------------+-----------+----------+-------------
     default_user_id |           |        0 |           0
     carol-head      |           | 4.07e-05 |    4.07e-05
    (2 rows)
    

Member removed before the spend flush

  1. The member is added, makes a call, and is removed before the flush

    {"members":["default_user_id","bob-head"]}
    {"model":"bedrock-converse-haiku-4-5","content":"Hi","usage":{"prompt_tokens":12,"completion_tokens":4}}
    {"members":["default_user_id"]}
    
  2. The flush does not bring the removed member back

    {"team_spend":0.0000352,"team_memberships":[{"user_id":"default_user_id","budget_id":null,"spend":0.0}]}
         user_id     | budget_id | spend | total_spend
    -----------------+-----------+-------+-------------
     default_user_id |           |     0 |           0
    (1 row)
    

Budgeted member listed again in a bulk member add

  1. The member gets a budget of 7 and makes a call, and the flush lands on their row

    {"updated_team_memberships":[{"user_id":"hank-head","has_budget":true,"max_budget":7.0}]}
    {"model":"bedrock-converse-haiku-4-5","content":"Hey!","usage":{"prompt_tokens":12,"completion_tokens":5}}
    # before re-add
         user_id     | has_budget |  spend   | total_spend
    -----------------+------------+----------+-------------
     default_user_id | f          |        0 |           0
     hank-head       | t          | 4.07e-05 |    4.07e-05
    (2 rows)
    
    orphan budgets created this run: 0
    
  2. The bulk add succeeds, the existing member keeps their budget and spend, only the new member gets a budget of 9, and no budget is left unlinked

    {"status":"ok","members":["default_user_id","hank-head","ivy-head"]}
    # after re-add
         user_id     | has_budget |  spend   | total_spend
    -----------------+------------+----------+-------------
     default_user_id | f          |        0 |           0
     hank-head       | t          | 4.07e-05 |    4.07e-05
     ivy-head        | t          |        0 |           0
    (3 rows)
    
    orphan budgets created this run: 0
    

Admin resets a member's spend from the Members tab

  1. Same team and same blocked member as steps 1 to 3 on the Before side. The admin opens http://localhost:4000/ui/teams/?team=ab61a1cb-d42e-4758-a984-da94ed1bf6e7 and clicks the Members tab. Alice's row now has a Reset spend icon between Edit and Delete. Bob's row does not, because he has no spend to reset

    Members tab at the PR tip, alice's row has a Reset spend icon

  2. The admin clicks the Reset spend icon and the "Reset Team Member Spend" dialog shows who is being reset and her current cycle spend

    Reset Team Member Spend dialog

  3. The admin clicks Reset. The dashboard sends the request below, the toast reads "Team member spend reset to $0", the page stays on the Members tab, alice's Current Cycle Spend reads -, and her Total Spend still reads $0.02

    POST http://localhost:4349/team/ab61a1cb-d42e-4758-a984-da94ed1bf6e7/member/alice-124519/reset_spend
    {"reset_to":0}
    200 {"team_id":"ab61a1cb-d42e-4758-a984-da94ed1bf6e7","user_id":"alice-124519","spend":0,"previous_spend":0.02262,"max_budget":0.01}
    

    Members tab after the reset

  4. Alice's next call goes through, and her row shows spend at 0 with total_spend kept

    {"content":"Hi!","error":null}
    [{"user_id":"alice-124519","max_budget":0.01,"spend":0.0,"total_spend":0.02262},{"user_id":"default_user_id","max_budget":0.01,"spend":0.0,"total_spend":0.0},{"user_id":"bob-124519","max_budget":0.01,"spend":0.0,"total_spend":0.0}]
    

Type

🆕 New Feature
🐛 Bug Fix

Caveats (if any)

Medium

  • A member with no budget now accrues spend, and nothing clears it, because the budget reset job only touches rows linked to a budget. When an admin later sets team_member_budget, that existing spend counts against the new budget right away, so a member can be blocked on their very next call. The last proof case shows it. Before this PR that member had no row, so a late budget started from zero. The admin clears it with the new Reset spend action or with POST /team/{team_id}/member/{user_id}/reset_spend. Docs for both are in docs(proxy): document team member spend reset in the UI and late budget edge case litellm-docs#1548

Low

  • Spend accrued by budget-less members before this fix is not recoverable; it was never written anywhere per member
  • A member add that lists someone already on the team skips them: the request's max_budget_in_team, allowed_models and budget_duration only apply to the new names, and the existing member's row, budget and spend are left as they were
  • Members with no budget now show $0.00 and Unlimited on the Members tab instead of -
  • Spend for a member who was removed from the team before the flush wrote it is dropped from the per-member counters, the same as before this PR. Team spend and spend logs still record it
  • The member spend write is one raw SQL statement on the LiteLLM_TeamMembership and LiteLLM_TeamTable tables, so a rename of either table or of members_with_roles has to touch it too
  • The roster check reads the stored JSON directly and does not validate it, so a roster entry with a matching user_id counts even if the rest of the entry would fail model validation
  • A membership row that outlived its roster entry still gets incremented; /team/member_delete removes both together, so this only affects rows left behind by direct database edits
  • The flush holds the per-team advisory lock (pg_advisory_xact_lock(hashtext(team_id))) until it commits, so /team/member_add, /team/member_delete and /team/delete on a touched team wait for the flush. It locks each distinct team with its own statement, in sorted team id order, the same order /team/delete uses, and takes no row lock, since the access-group endpoints lock a team row after an access-group lock
  • Live A/B ran a single uvicorn worker per side. The SCIM and JWT auto-add paths that also call the member add helper are covered by their unit suites, not by the live run
  • The Reset spend action only shows on rows whose current cycle spend is above zero. A team admin does not see it on their own row, because the endpoint only lets a proxy admin reset their own spend
  • The Reset spend action always resets to $0. Resetting to any other value stays API only
  • The dashboard action widens this PR beyond the backend fix. It lives here because the backend fix is what makes the late budget case above possible

Audit against the review taxonomy

Checked on the current diff after merging main. Item ids follow the litellm PR-review caveat taxonomy

  • E4 and AA5 confirmed as the bug being fixed: the team counter moved while the member entry was never written, and update_many matched zero rows without any signal. The single INSERT ... ON CONFLICT writes every row in one statement, so a failure fails the whole flush and the existing retry loop replays it
  • E5 not applicable: budget_id is written only when a budget resolves, and None is stored as NULL rather than swallowed by an or fallback. _budget_id is not None is the check
  • E8 not applicable: the member key already carries team_id and user_id from the request's own identity; this PR only changes where the row lands
  • AA4 not applicable: the increment runs inside one transaction with the advisory lock, and a retry only happens after the transaction rolled back, so no partial increment survives a replay
  • B1 confirmed and handled: the flush reads the roster to decide whether to create a row, so it takes the same per-team advisory lock the roster endpoints hold, in sorted distinct team id order. Rows are written in (team_id, user_id) order, not composite-key string order, which put eng2 ahead of eng under the old sort
  • T2, T3 and T4 checked: the writer test drives the real _write_team_member_spend against a fake transaction that records execute_raw calls and asserts the lock order and row order it saw, and the helper tests assert the upsert where, create and update payloads on the injected table rather than re-deriving them. Mutating the upsert update to carry budget_id fails test_add_new_member_creates_new_budget_when_max_budget_provided, and switching the row sort back to composite-key order fails test_commit_spend_updates_to_db_orders_team_member_rows_by_team_then_user
  • T5 and T10 not applicable: the tests inject fakes instead of patching module globals and create no live rows
  • T17 covered: no-budget upsert, roster-aware backfill, removed-member skip, and mixed bulk add each have a mapped test. The dashboard action has its own cases in TeamMemberTab.test.tsx: the confirm flow posts {"reset_to": 0} to the reset endpoint exactly once and refreshes the team, a failed reset keeps the dialog open, cancel sends nothing, and the action is hidden on rows with no spend and on a team admin's own row
  • H2 checked: the three comments in db_spend_update_writer.py explain the lock choice, the roster gate and the key format of a raw SQL block; no diff-narration comments were added. H4: no Optional, bare dict or Any added, all new locals carry Final, and no line passes 120 columns. H8 not applicable, no schema change. No budget file is touched

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

ran /live-pr-risk and found no regressions/backward incompatible risks

Link to Devin session: https://app.devin.ai/sessions/53cfe213549c464d8dfba8d1db9ef553
Open in Devin Desktop: https://app.devin.ai/desktop/session/53cfe213549c464d8dfba8d1db9ef553?variant=devin


Note

Medium Risk
Changes billing-adjacent team membership writes and spend flush concurrency (raw SQL + advisory locks); incorrect roster gating or upsert semantics could mis-attribute spend or block roster operations under load.

Overview
Fixes LIT-5502 / LIT-7030: team members without a budget no longer lose per-member spend, and bulk re-adds no longer break on duplicate membership rows.

Backend — membership on add: add_new_member always upserts a LiteLLM_TeamMembership row (budget optional). /team/member_add uses one loop for single or bulk adds and skips users already on the roster so existing budgets/spend are not overwritten and orphan budgets are not created.

Backend — spend flush: Team-member spend commits replace per-row Prisma update_many with _write_team_member_spend: per-team transaction advisory locks (same pattern as roster endpoints), rows sorted by (team_id, user_id), then one INSERT … ON CONFLICT that increments spend/total_spend and only creates a missing row if the user is still in members_with_roles (or a row already exists), so post-removal flushes do not resurrect members.

Dashboard: Team Members tab adds a Reset spend control (confirm dialog) calling POST /team/{team_id}/member/{user_id}/reset_spend with reset_to: 0, with visibility rules for zero spend and team-admin self-reset.

Tests are updated/added for the SQL flush, upsert behavior, mixed bulk add, and UI reset flow.

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

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 16, 2026 01:27
@codspeed

codspeed Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_team_member_spend_without_budget (c21e86a) with main (6fa34a2)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes team-member spend visible for members without budgets and for older roster entries that are missing membership rows. It also removes an unused Rust framing crate and several older request and stream hook paths.

  • Creates membership rows for every added team member.
  • Flushes member spend with a roster-aware SQL upsert under per-team advisory locks.
  • Removes unused framing, request-budget, and stream-hook code.

Confidence Score: 5/5

The PR appears safe to merge. No new issue remains after the latest changes.

The current code fixes the missing member spend row and guards the delete race. All three earlier findings were manually resolved without explanation.

Important Files Changed
Filename Overview
litellm/proxy/db/db_spend_update_writer.py The member spend flush now locks touched teams and uses one roster-checked upsert. This fixes missing rows without bringing back deleted members.
litellm/proxy/management_endpoints/team_endpoints.py Member adds now skip helper writes for users already on the roster. This avoids creating unused budgets when a mixed request includes an existing member.
litellm/proxy/management_helpers/utils.py add_new_member now upserts a membership even when no budget applies. Existing membership spend and budget links stay unchanged.
tests/test_litellm/proxy/db/test_db_spend_update_writer.py The tests cover the raw upsert, roster check, row order, and team lock order.
tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py The tests cover mixed member adds and confirm that existing roster members do not create unused budgets.

Reviews (7): Last reviewed commit: "fix(proxy): skip members already on the ..." | Re-trigger Greptile

@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@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

bugbot run

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@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

bugbot run

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

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

budget_link: Final[Mapping[str, object]] = {"budget_id": _budget_id} if _budget_id is not None else {}
_returned_team_membership: Final = await membership_table.upsert(
where={"user_id_team_id": membership_key},
data={"create": {**membership_key, **budget_link}, "update": {**budget_link}},

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.

Mixed-list or bulk member_add calls this for members already on the team, so this update silently replaces their existing budget_id. Should update stay empty?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, update is now empty so an existing membership keeps its budget_id and spend on re-add. The budget link only lands in create

# keeping lock order consistent across pods to prevent deadlocks
keys: Final = tuple(sorted(spend_by_member_key))
team_ids: Final = [key.split("::")[1] for key in keys]
for team_id in dict.fromkeys(team_ids):

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.

Sorting the composite keys orders team ids like eng2 before eng, but /team/delete uses sorted(team_ids), so they can deadlock. Sort team ids directly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Rows are now sorted by (team_id, user_id) and locks follow sorted distinct team ids, matching /team/delete. Regression test pins eng before eng2

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor

also can you rebase this?

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_team_member_spend_without_budget branch from d3cdcf2 to 24ed3ba Compare September 17, 2026 00:50
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

Rebased onto main, tip is now 24ed3ba with both review fixes included, and the branch no longer conflicts with main

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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

Stale Bugbot comment from a previous run.

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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

Stale Bugbot comment from a previous run.

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor

bugbot run

ryan-crabbe-berri and others added 11 commits September 18, 2026 13:54
add_new_member only wrote a LiteLLM_TeamMembership row when a budget id
resolved, and the spend writer used update_many so a missing row failed
silently. Members without a budget therefore never accrued per-member spend.

The membership row is now always upserted (budget_id NULL when no budget
applies) and the spend write is an upsert so members added before this fix
start accruing on their next request.

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>
…e a spend flush

Take the team advisory lock in the spend flush transaction and read the roster
through it, so a delayed flush after /team/member_delete cannot recreate the
deleted LiteLLM_TeamMembership row. TEAM_ADVISORY_LOCK_SQL moves to
team_repository so the spend writer can import it without a circular import

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…thon 3.10

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ement

Replaces the per team advisory lock and Pydantic roster parse in the spend flush
with a single INSERT ... ON CONFLICT statement that checks the stored roster in
SQL, so malformed roster JSON cannot fail the whole flush and large batches no
longer issue two queries per team inside the fixed transaction deadline

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>
…sert

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…er budgets on re-add

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ay within the type discipline budget

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ember budget

A mixed /team/member_add list that names an existing member used to run
add_new_member for them, which created or cloned a budget that the empty
upsert update branch never linked to their membership row. Filter the
requested members against the freshly locked roster first so budgets and
membership rows are only written for members who are actually new

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Every member now carries a membership row, so a member who spent with no budget is over budget the moment a member budget is added later. The only fix was POST /team/{team_id}/member/{user_id}/reset_spend, which had no UI.

The Members tab gets a Reset spend action on rows that have current cycle spend. It confirms in a dialog, posts reset_to 0 through the typed client, and refreshes the team without remounting the page so the tab stays open. A team admin does not see it on their own row because the backend rejects that reset
@ryan-crabbe-berri
ryan-crabbe-berri force-pushed the litellm_team_member_spend_without_budget branch from dc49001 to c21e86a Compare September 18, 2026 20:54

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit dc49001. Configure here.

)
for m in requested_members:
if _member_already_in_team(m, complete_team_data):
continue

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.

Skip misses create orphan member budgets

Medium Severity

The already-on-team skip only consults the roster from before this request, so a bulk member_add that names the same person twice, or by the identifier the roster does not carry, still calls add_new_member. That helper allocates a budget first, then upserts with an empty update, so the new budget is never linked and the request still succeeds.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit dc49001. Configure here.

@ryan-crabbe-berri
ryan-crabbe-berri merged commit 006080e into main Sep 18, 2026
88 of 90 checks passed
@ryan-crabbe-berri
ryan-crabbe-berri deleted the litellm_team_member_spend_without_budget branch September 18, 2026 21:04
tech-carrement pushed a commit to tech-carrement/litellm that referenced this pull request Sep 20, 2026
…eam default

Backport of BerriAI#41347 to rc/1.102.0.
Cherry-picked from merge commit 4bb1ae1 (main), originally by app/devin-ai-integration.

Conflicts: main's BerriAI#41349 (membership rows written through upsert) is not on this line, so add_new_member keeps its create call and still writes no membership row when no budget resolves. The picked tests are adapted to that and to this line's _check_team_member_budget, which loads the membership itself.
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