Repository navigation
fix(proxy): track team member spend when the member has no budget - #41349
Conversation
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Greptile SummaryThis 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.
Confidence Score: 5/5The 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
Reviews (7): Last reviewed commit: "fix(proxy): skip members already on the ..." | Re-trigger Greptile |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
|
bugbot run |
|
bugbot run |
|
bugbot 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}}, |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
|
also can you rebase this? |
d3cdcf2 to
24ed3ba
Compare
|
Rebased onto main, tip is now 24ed3ba with both review fixes included, and the branch no longer conflicts with main |
|
bugbot run |
|
bugbot run |
|
bugbot run |
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
dc49001 to
c21e86a
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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 |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit dc49001. Configure here.
…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.


TLDR
Problem this solves:
How it solves it:
/team/member_deletenever recreates the removed rowUser Flow
Before: an admin adds a member with no budget, the member makes calls, and the admin never sees that member's spend
{"team_alias": "member-spend"}and gets back ateam_id{"team_id": "<team_id>", "member": {"user_id": "alice", "role": "user"}}and gets back"updated_team_memberships": []{"team_id": "<team_id>", "user_id": "alice"}and hands the key to alicespendwent up butteam_membershipsis[]-After: the same steps, alice's spend shows up, and the admin can reset it from the dashboard
{"team_alias": "member-spend"}and gets back ateam_id"updated_team_memberships": [{"user_id": "alice", "team_id": "<team_id>", "budget_id": null, "spend": 0, "total_spend": 0}]{"team_id": "<team_id>", "user_id": "alice"}and hands the key to aliceteam_membershipsnow lists alice withspendequal to the cost of her call-and her Total Spend is unchangedRelevant 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
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@greptileaito 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.yamlsharing one Postgres, with real AWS Bedrock calls through thebedrock-converse-haiku-4-5deployment. The Before side runs the merge base from a second worktree withPYTHONPATHpointed 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$LEGisbaseorheadThe last case needs one call that costs more than the $0.01 member budget, so it uses
bedrock-converse-opus-4-8for 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 asnpm run devon port 3349, which serves the same page athttp://localhost:3349/teams/?team=<team_id>Before (a262672)
Member with no budget makes a real call
/team/member_addreturns no membershipThe chat call succeeds
/team/infoshows the team was charged but has no member rows, and the table is emptyMember rostered with no membership row makes a real call
The member is on the roster and the delete finds nothing to remove, since the base never wrote a row
The chat call succeeds
The flush charges the team and leaves the member with no row
Member removed before the spend flush
The member is added, makes a call, and is removed before the flush
The flush charges the team and writes no member row
Budgeted member listed again in a bulk member add
The member gets a budget of 7 and makes a call, and the flush lands on their row
The bulk add that lists them next to a new member fails on the primary key, so the new member is never added
Admin resets a member's spend from the Members tab
Alice makes a real call while she has no member budget, and her row carries the cost
The admin sets
team_member_budgetto 0.01 on the team. Every row gets the budget and alice keeps her spendAlice's next call is blocked
The admin opens
http://localhost:4000/ui/teams/?team=ab61a1cb-d42e-4758-a984-da94ed1bf6e7and 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 handAfter (dc49001)
Member with no budget makes a real call
/team/member_addreturns a membership with no budgetThe chat call succeeds
/team/infoshows the member's spend equals the team's spend, and the row carries both counters withbudget_idNULLMember rostered with no membership row makes a real call
The member is on the roster and the row this side wrote is deleted by hand to mimic a member added before the fix
The chat call succeeds
The flush recreates the row with that call's cost
Member removed before the spend flush
The member is added, makes a call, and is removed before the flush
The flush does not bring the removed member back
Budgeted member listed again in a bulk member add
The member gets a budget of 7 and makes a call, and the flush lands on their row
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
Admin resets a member's spend from the Members tab
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-da94ed1bf6e7and 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 resetThe admin clicks the Reset spend icon and the "Reset Team Member Spend" dialog shows who is being reset and her current cycle spend
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.02Alice's next call goes through, and her row shows
spendat 0 withtotal_spendkeptType
🆕 New Feature
🐛 Bug Fix
Caveats (if any)
Medium
spend, and nothing clears it, because the budget reset job only touches rows linked to a budget. When an admin later setsteam_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 withPOST /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#1548Low
max_budget_in_team,allowed_modelsandbudget_durationonly apply to the new names, and the existing member's row, budget and spend are left as they were$0.00andUnlimitedon the Members tab instead of-LiteLLM_TeamMembershipandLiteLLM_TeamTabletables, so a rename of either table or ofmembers_with_roleshas to touch it toouser_idcounts even if the rest of the entry would fail model validation/team/member_deleteremoves both together, so this only affects rows left behind by direct database editspg_advisory_xact_lock(hashtext(team_id))) until it commits, so/team/member_add,/team/member_deleteand/team/deleteon 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/deleteuses, and takes no row lock, since the access-group endpoints lock a team row after an access-group lockAudit against the review taxonomy
Checked on the current diff after merging
main. Item ids follow the litellm PR-review caveat taxonomyupdate_manymatched zero rows without any signal. The singleINSERT ... ON CONFLICTwrites every row in one statement, so a failure fails the whole flush and the existing retry loop replays itbudget_idis written only when a budget resolves, andNoneis stored as NULL rather than swallowed by anorfallback._budget_id is not Noneis the checkteam_idanduser_idfrom the request's own identity; this PR only changes where the row lands(team_id, user_id)order, not composite-key string order, which puteng2ahead ofengunder the old sort_write_team_member_spendagainst a fake transaction that recordsexecute_rawcalls and asserts the lock order and row order it saw, and the helper tests assert the upsertwhere,createandupdatepayloads on the injected table rather than re-deriving them. Mutating the upsertupdateto carrybudget_idfailstest_add_new_member_creates_new_budget_when_max_budget_provided, and switching the row sort back to composite-key order failstest_commit_spend_updates_to_db_orders_team_member_rows_by_team_then_userTeamMemberTab.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 rowdb_spend_update_writer.pyexplain the lock choice, the roster gate and the key format of a raw SQL block; no diff-narration comments were added. H4: noOptional, baredictorAnyadded, all new locals carryFinal, and no line passes 120 columns. H8 not applicable, no schema change. No budget file is touchedFinal Attestation
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_memberalways upserts aLiteLLM_TeamMembershiprow (budget optional)./team/member_adduses 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_manywith_write_team_member_spend: per-team transaction advisory locks (same pattern as roster endpoints), rows sorted by(team_id, user_id), then oneINSERT … ON CONFLICTthat incrementsspend/total_spendand only creates a missing row if the user is still inmembers_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_spendwithreset_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.