Skip to content

fix(team): make membership insert idempotent on /team/member_add - #39821

Closed
devin-ai-integration[bot] wants to merge 5 commits into
mainfrom
litellm_fix_team_member_add_membership_unique
Closed

devin-ai-integration[bot] wants to merge 5 commits into
mainfrom
litellm_fix_team_member_add_membership_unique

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • /team/member_add returns 500 "Unique constraint failed" when a membership row already exists
  • Concurrent first-use adds of one user still reach the insert after the lock
  • A roster/membership desync wedges the user forever, every add fails
  • Each failed attempt cloned an extra per-member budget row

How it solves it:

  • Look up the (user_id, team_id) membership row before resolving the budget
  • Return the existing membership instead of inserting, so the add is idempotent
  • The caller still re-appends the missing roster entry, which heals wedged users
  • No budget clone when the membership already exists

User Flow

Before: a developer whose IdP group entitles them to a team with a per-member budget gets most of their first-use requests rejected, and a user with a mismatched account is rejected forever

  1. They send several concurrent POST https://litellm-domain/v1/chat/completions with their JWT for a team they have never used on the gateway
  2. One request returns 200. The others come back {"error": "Unable to add user - user_id='...', to team - '...', for reason - Unique constraint failed on the fields: (user_id,team_id)", "type": "auth_error", "code": "500"}
  3. They retry and it works, because the successful request put them on the team roster
  4. A user whose roster entry went missing while their membership record stayed sees the same 500 on every request, and only an operator editing the database gets them out

After: the same first-use burst puts them on the team once and all requests are served

  1. They send the same concurrent POST https://litellm-domain/v1/chat/completions with the same JWT
  2. Every request returns 200, and GET https://litellm-domain/user/info?user_id= shows exactly one membership in that team with one budget
  3. A user whose roster entry and membership record disagree is repaired by their next request instead of being rejected by it

Relevant issues

Linear ticket

Resolves LIT-6983

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

Local proxy on Postgres: uv run --no-sync litellm --config litellm/proxy/dev_config.yaml --detailed_debug --port 4000, master key sk-1234. Each leg creates a team with a per-member budget, which is what gates the membership insert:

curl -sS -X POST localhost:4000/team/new -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"team_alias":"<alias>","team_member_budget":10}'

Then fires five concurrent adds of one new user:

for i in 1 2 3 4 5; do
  curl -s -o r$i.json -w "req$i http=%{http_code}\n" -X POST localhost:4000/team/member_add \
    -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
    -d '{"team_id":"<team_id>","member":{"user_id":"<user>","role":"user"}}' &
done; wait

Then drops only the roster entry, leaving the membership row (the desynced state older versions could produce), and retries a single add:

UPDATE "LiteLLM_TeamTable" SET members_with_roles = (SELECT jsonb_agg(m) FROM jsonb_array_elements(members_with_roles) m WHERE m->>'user_id' <> '<user>') WHERE team_id='<team_id>';

Requests that read the roster after the first add committed get the pre-existing 400 team_member_already_in_team, on both legs. That check is unchanged here; the difference is what happens to the requests that get past it

Before (d23bec8)

Concurrent adds, team with per-member budget

  1. /team/new -> team_id=832672bb-1499-40b4-8eb0-2f1f97f91dea, metadata.team_member_budget_id=team-lit-6983-before-budget-...; SELECT count(*) FROM "LiteLLM_BudgetTable" -> 4
  2. Burst for lit6983-user-b:
    req3 http=400
    req4 http=400
    req1 http=400
    req2 http=200
    req5 http=500
    
  3. req5 body: {"detail":{"error":"Unable to add user - user_id='lit6983-user-b' user_email=None role='user', to team - 832672bb-1499-40b4-8eb0-2f1f97f91dea, for reason - Unique constraint failed on the fields: (user_id,team_id)"}}
  4. SELECT count(*) FROM "LiteLLM_BudgetTable" -> 6. Two new rows for one member: the failed request cloned a budget before its insert blew up

Wedged roster/membership desync

  1. Run the roster UPDATE for lit6983-user-b -> UPDATE 1
  2. Single /team/member_add for lit6983-user-b -> http=500, body {"detail":{"error":"Unable to add user - ... for reason - Unique constraint failed on the fields: (user_id,team_id)"}}. Every retry returns the same

After (b00e9e8, the fix commit; later commits b41302e and earlier only touch test mocks and a type-gate condition, no behavior change)

Concurrent adds, team with per-member budget

  1. /team/new -> team_id=d78bd31e-b818-487c-9fb0-49c3755d7a72, metadata.team_member_budget_id=team-lit-6983-after-budget-...; SELECT count(*) FROM "LiteLLM_BudgetTable" -> 2
  2. Burst for lit6983-user-a:
    req3 http=200
    req4 http=200
    req1 http=400
    req2 http=400
    req5 http=400
    
    No 500. Both 200 responses carry the same membership budget_id=a7963fb1-6dc8-4ce4-9c93-868d6913fb90
  3. GET /user/info?user_id=lit6983-user-a -> "teams":["d78bd31e-..."], one entry in team_memberships with budget_id=a7963fb1-...
  4. SELECT count(*) FROM "LiteLLM_TeamMembership" WHERE user_id='lit6983-user-a' -> 1; SELECT count(*) FROM "LiteLLM_BudgetTable" -> 3, exactly one new row

Wedged roster/membership desync

  1. Run the roster UPDATE for lit6983-user-a -> UPDATE 1
  2. Single /team/member_add for lit6983-user-a -> http=200; response members_with_roles contains lit6983-user-a again and the membership reuses budget_id=a7963fb1-...

Type

🐛 Bug Fix

Caveats (if any)

Low

  • proxy-infra (Python 3.10) fails on test_http_parsing_utils.py::TestNumericFormFields::test_qualifiers_and_optionality_are_unwrapped, which also fails on litellm_internal_staging at d23bec8 (run 33925150414), unrelated to this change

  • An existing membership keeps its budget even if the request passes max_budget_in_team or allowed_models; the add is a no-op for that row, matching the existing roster-only behavior

  • The pre-lock roster duplicate check still returns 400 for late concurrent requests; that is unchanged and tracked separately from the 500

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

Link to Devin session: https://app.devin.ai/sessions/ba5b0b0b5f1e43cf942453cb51a57891
Open in Devin Desktop: https://app.devin.ai/desktop/session/ba5b0b0b5f1e43cf942453cb51a57891?variant=devin
Requested by: @shivamrawat1

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@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

@codspeed

codspeed Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_fix_team_member_add_membership_unique (b41302e) with litellm_internal_staging (b3c867c)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds an existing-membership lookup so team-member insertion can reuse the current membership and avoid duplicate budget creation

  • Returns an existing membership before resolving or cloning its budget
  • Adds tests for existing and absent membership rows
  • Introduces a direct critical-path database query that violates repository access rules

Confidence Score: 4/5

The behavior appears correct, but the repository’s explicit database-access requirement must be satisfied before merging

The transaction-scoped team lock makes the membership reuse effective for production callers, but the implementation adds a prohibited direct database request in a critical request path

Files Needing Attention: litellm/proxy/management_helpers/utils.py

Important Files Changed

Filename Overview
litellm/proxy/management_helpers/utils.py Adds idempotent membership reuse, but does so through a new direct database query in the first-use request path
tests/test_litellm/proxy/management_helpers/test_management_helpers_utils.py Covers existing-membership reuse, skipped budget cloning, and normal creation when no membership exists

Reviews (1): Last reviewed commit: "fix(team): make membership insert idempo..." | Re-trigger Greptile

Comment on lines +463 to +466
existing_membership: Final[_PrismaRecord | None] = await membership_table.find_unique(
where={"user_id_team_id": {"user_id": returned_user.user_id, "team_id": team_id}},
include={"litellm_budget_table": True},
)

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.

P2 Direct Critical-Path Database Read

This adds a direct membership query to the first-use request path. Repository rules prohibit new database requests there and require database access through the approved object helpers, so this requirement must be satisfied before merging

Rule Used: What: In critical path of request, there should be... (source)

Knowledge Base Used: Database access and migrations

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@codecov

codecov Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/management_helpers/utils.py 88.88% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

shivamrawat1 and others added 4 commits September 4, 2026 23:22
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>
@yuneng-berri
yuneng-berri deleted the branch main September 13, 2026 04:49
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:43
@yuneng-berri

Copy link
Copy Markdown
Contributor

Closing as superseded by #41349, which already made the membership write an upsert and shipped in v1.103.0

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.

2 participants