Skip to content

fix(scim): sync team roster and dedup teams for existing-user email upsert - #34183

Merged
yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_scim_existing_user_email_roster
Jul 22, 2026
Merged

yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_scim_existing_user_email_roster

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Follow-up to #34162

Linear ticket

Part of LIT-4676

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • 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

Independent e2e (Devin): existing-user-by-email POST with duplicated groups dedups user.teams and syncs the roster (members_with_roles populated).

proof

Admin UI user detail Teams panel: the team is listed once (parent listed it twice, with an empty roster).

proof

SCIM management endpoints, no LLM call needed. Live proxy on localhost:4290 backed by a real Postgres 16, litellm_settings.scim_upsert_user: true

Repro: create user ua (email e@t.com), create team T via POST /scim/v2/Groups with an empty roster, then POST /scim/v2/Users with a different userName but the same email and groups=[{value: T}]. The user then lists T on their profile but is absent from T's roster

Before (unfixed, commit 2b2ae4ca49)

$ curl -s -X POST $BASE/scim/v2/Users ... userName=ua-eu  email=e-eu@t.com
id= ua-eu groups= []
$ curl -s -X POST $BASE/scim/v2/Groups ... id=T-eu members=[]
id= T-eu members= []
$ curl -s -X POST $BASE/scim/v2/Users ... userName=ua2-eu  email=e-eu@t.com  groups=[{value:T-eu}]
id= ua2-eu userName= e-eu@t.com groups= [{'value': 'T-eu', 'display': 'Team EU', 'type': 'direct'}]

Database and SCIM API afterward show the user in the group but not in the roster:

LiteLLM_UserTable  : ua2-eu | {T-eu}
LiteLLM_TeamTable  : T-eu   | []          <-- members_with_roles empty
LiteLLM_TeamMembership for T-eu : (none)

GET /scim/v2/Groups/T-eu -> members= []   <-- roster empty

After (fixed, commit e5f9d1e10c)

Same flow, plus a deliberately duplicated group in the POST to exercise dedup (groups=[{value:T-fix},{value:T-fix}]):

$ curl -s -X POST $BASE/scim/v2/Users ... userName=ua-fix  email=e-fix@t.com
id= ua-fix groups= []
$ curl -s -X POST $BASE/scim/v2/Groups ... id=T-fix members=[]
id= T-fix members= []
$ curl -s -X POST $BASE/scim/v2/Users ... userName=ua2-fix email=e-fix@t.com groups=[{value:T-fix},{value:T-fix}]
id= ua2-fix userName= e-fix@t.com groups= [{'value': 'T-fix', 'display': 'Team Fix', 'type': 'direct'}]

Database and SCIM API afterward show the user in the roster, teams deduped, and the old primary key renamed away:

LiteLLM_UserTable  : ua2-fix | {T-fix}                                   <-- single entry, deduped
LiteLLM_TeamTable  : T-fix   | [{"role":"user","user_id":"ua2-fix","user_email":"e-fix@t.com"}]
count(user_id='ua-fix') : 0                                              <-- rename preserved

GET /scim/v2/Groups/T-fix -> members= [{'value': 'e-fix@t.com', 'display': 'e-fix@t.com'}]

A LiteLLM_TeamMembership row is only written when a team budget applies, which matches the existing PUT update_user behavior this change now reuses; members_with_roles is the roster source of truth and is now correct.

Roster-sync failure now surfaces (fixed, commit d498cf07de)

The roster sync used to swallow genuine team_member_add failures, so a failed add still reported success and persisted a teams array the roster never received. The upsert now runs the sync strictly and only persists the deduped teams once it succeeds. A POST whose group points at a team that does not exist returns an error instead of a false 201, and the user's teams array is left untouched so it cannot diverge from the roster; the IdP retries and converges:

$ curl ... -X POST $BASE/scim/v2/Users ... userName=ua-s2 email=s2@t.com               # existing user
$ curl -w '%{http_code}' -X POST $BASE/scim/v2/Users ... userName=ua2-s2 email=s2@t.com groups=[{value:NO-SUCH-TEAM}]
POST status=404
{"detail":{"error":"Team doesn't exist in db. Team=NO-SUCH-TEAM. Create team via `/team/new` call."}}

LiteLLM_UserTable : ua2-s2 | {}          <-- teams NOT set to a team the roster never received

The happy path (a group pointing at a real team) still returns 201 and adds the user to members_with_roles, verified on the same head. The benign "already a member" case stays a no-op

Type

🐛 Bug Fix

Changes

UserProvisionerHelpers.handle_existing_user_by_email now routes the existing-user team assignment through the same _handle_team_membership_changes helper the PUT update_user handler already uses, so members_with_roles, LiteLLM_TeamMembership, and the user's teams array stay in sync instead of the roster being silently skipped. The teams derived from user.groups are deduped before they are written or diffed

The roster sync runs strictly for this path via a new opt-in raise_on_error flag on patch_team_membership and _handle_team_membership_changes: a genuine add or remove failure propagates so the deduped teams array is only persisted once the roster actually received the change. Adds and removes are treated symmetrically; the idempotent no-ops (the user is already in the team on add, or already absent on remove) stay no-ops even under the strict path. The flag defaults to False, so the PUT update_user, PATCH patch_user, and group callers keep their existing best-effort behavior

The user_id rewrite to the new userName is left intact so this stays a single isolated fix; it is sequenced as its own update before the roster sync so the roster keys off the final primary key, and the authoritative field write runs last so the returned SCIM user and the persisted teams array reflect the deduped set. On a mid-flight failure the endpoint returns an error and the IdP retries; because the second attempt finds the already-renamed user by email, the rename is idempotent and the teams array and roster converge without diverging. Making the primary-key rename plus its foreign-key cascade a single atomic transaction is a broader concern that predates this change (the prior code renamed the same way) and belongs with the transactional-write work, so it is intentionally out of scope here

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

…psert

When POST /scim/v2/Users matched an already-existing user by email,
handle_existing_user_by_email raw-wrote the user's teams array but never
touched the team roster, so the user appeared in the group on their profile
yet was absent from the team directly (members_with_roles stayed empty). It
also did not dedup the teams built from repeated SCIM groups.

Route the existing-user team assignment through the same
_handle_team_membership_changes / team_member_add path the PUT update_user
handler uses, so members_with_roles, LiteLLM_TeamMembership, and the user's
teams array stay in sync, and dedup the teams derived from user.groups. The
user_id rewrite to the new userName is preserved and sequenced before the
roster sync so the roster never references a stale primary key.
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR keeps SCIM user teams and team rosters in sync during existing-email upserts. The main changes are:

  • Deduplicate requested teams before reconciliation and persistence
  • Reconcile membership through the shared team helper
  • Propagate genuine add and removal failures in strict mode
  • Preserve idempotent already-present and already-absent behavior
  • Add focused tests for successful and failed reconciliation

Confidence Score: 5/5

This looks safe to merge.

  • Genuine add and removal failures now stop the final teams write
  • Idempotent membership operations remain successful
  • Tests cover the changed success and failure paths
  • No blocking issue was found in the latest changes

Important Files Changed

Filename Overview
litellm/proxy/management_endpoints/scim/scim_v2.py Adds deduplicated roster reconciliation and strict, symmetric error propagation for existing-email upserts.
tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py Adds tests for roster synchronization, duplicate teams, genuine failures, and idempotent membership operations.

Reviews (4): Last reviewed commit: "fix(scim): surface roster removal failur..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR synchronizes team rosters during existing-email SCIM user upserts. The main changes are:

  • Deduplicates requested team IDs while preserving order
  • Renames an existing user's ID before syncing memberships
  • Reuses the shared team-membership helper
  • Adds focused tests for rename sequencing and deduplication

Confidence Score: 4/5

The existing-email upsert can leave the user record and team roster inconsistent when a write fails.

  • The rename, roster sync, and final update commit separately.
  • Membership failures can be suppressed before the new teams are persisted.
  • The normal successful path deduplicates teams and uses the new user ID correctly.

litellm/proxy/management_endpoints/scim/scim_v2.py

Important Files Changed

Filename Overview
litellm/proxy/management_endpoints/scim/scim_v2.py Adds team deduplication and roster synchronization, but the separate writes and suppressed membership failures can leave inconsistent state.
tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py Adds focused assertions for deduplication, rename order, and membership-helper invocation.

Reviews (1): Last reviewed commit: "fix(scim): sync team roster and dedup te..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/management_endpoints/scim/scim_v2.py 75.00% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_scim_existing_user_email_roster (aeb2240) with litellm_internal_staging (2b2ae4c)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (20a4666) during the generation of this report, so 2b2ae4c was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

Route the existing-email upsert's roster sync through patch_team_membership
with a new opt-in raise_on_error flag so a genuine team_member_add failure
propagates instead of being swallowed, and the deduped teams array is only
persisted after the roster sync succeeds. Without this, a failed add left the
endpoint reporting success while user.teams listed a team members_with_roles
never received.

The benign already-a-member case stays a no-op even under the strict path, and
the flag defaults to False so the PUT update_user, PATCH patch_user, and group
callers keep their existing best-effort behavior. SCIM POST is idempotent, so
surfacing the error lets the IdP retry and converge.
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current head d498cf0

Comment on lines +103 to +107
if new_user_request.user_id != existing_user.user_id:
await UserRepository(prisma_client).table.update(
where={"user_id": existing_user.user_id},
data={"user_id": new_user_request.user_id},
)

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.

P1 Rename remains partially committed

This update commits the new user ID before roster synchronization and the final field update. If synchronization fails, the request returns an error after the ID changed, leaving the user's previous teams and profile fields in place. If synchronization succeeds but the final update fails, the rename and roster changes remain committed without the authoritative teams write. These operations need a shared transaction or explicit rollback so later failures cannot leave partial state.

Make team_member_delete failures fail loud under the strict roster sync used by
the existing-email upsert, mirroring the add path, so a swallowed removal can no
longer let the user's teams array drop a team the roster still holds. The
idempotent case where the user is already absent from the team stays a no-op,
matching how an add treats the user already being in the team. Best-effort
behavior is preserved for the default raise_on_error=False callers.
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

Addressed the removal half of the roster-consistency finding in aeb2240: team_member_delete failures now fail loud under the strict path exactly like adds, with the idempotent "user already absent from the team" case kept as a no-op (mirroring the "already a member" no-op on add). So the teams array can no longer drop a team the roster still holds.

On the remaining point (the user-ID rename committing before the later writes): closing that fully means wrapping the primary-key rename and its foreign-key cascade in a single transaction. That rename orphaning is not introduced here; the prior code performed the same single-write rename, and any reordering within this function that renames without cascading the roster keys would orphan members_with_roles on the success path rather than shrink the failure window. This path is already a strict improvement over the previous behavior, which never synced the roster at all, and on a mid-flight failure the endpoint returns an error so the IdP retries; the retry matches the already-renamed user by email, making the rename idempotent so the teams array and roster converge without diverging. Full atomic adoption of the primary-key rename belongs with the transactional-write work rather than this isolated roster-sync fix, so it is intentionally left out of scope

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current head aeb2240

@yassin-berriai
yassin-berriai merged commit 5abe5f8 into litellm_internal_staging Jul 22, 2026
82 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_scim_existing_user_email_roster branch July 22, 2026 20:59
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