Skip to content

fix(scim): write a group's roster in one locked transaction instead of one member at a time - #45197

Merged
mateo-berri merged 31 commits into
mainfrom
litellm_scim_bulk_group_roster
Oct 15, 2026
Merged

mateo-berri merged 31 commits into
mainfrom
litellm_scim_bulk_group_roster

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A SCIM group push enrolled its members one at a time
  • 500 members meant thousands of database round trips
  • The load balancer gave up, so the IdP saw a 504

How it solves it:

Decisions
  1. The team row is read once under a per-team advisory lock, so two IdP pushes for the same group serialize instead of interleaving
  2. PUT and PATCH replace carry the whole roster as a target; POST and PATCH add/remove carry deltas, so a PATCH never drops members it did not name
  3. Per-member budgets are created in one create_many only when the team scopes member models; otherwise members link the team's shared budget after one lookup
  4. Memberships use create_many(skip_duplicates=True) and the users' teams arrays one update_many guarded by NOT teams has, so a retry after a partial IdP push is idempotent
  5. Removals run one array_remove UPDATE plus delete_many calls, and removed members' team keys are deleted with tombstones, as the per-member path did
  6. The roster sync answers a tagged outcome: a vanished team maps to 404, and a member whose user row is gone at the locked write goes through decision 23
  7. The PUT response is built from the roster after the write rather than from the request body
  8. A PATCH that names no members (a rename) opens no transaction and takes no lock; it reads the team and answers
  9. Every writer that changes many user rows at once takes them in one order, user_id COLLATE "C", through the shared USER_ROWS_LOCK_SQL or a sorted IN subquery: a group push, /team/delete, /team/member_add with a list, the three user deletes, the team member bulk delete, the SCIM admin-group role update, and the budget reset. Byte order is also Python's sorted() order, which the spend writer uses. On Postgres 18, a push raced against team delete deadlocked in 20 of 20 rounds and against the role update in 17 of 20 before this rule, and in 0 of 20 after (script and output)
  10. A delta naming nobody reads the team from the writer, so a PUT echoing the current roster is never served from a lagging read replica
  11. A group rename evicts the team cached under its id and its old alias and broadcasts the eviction, so auth and the dashboard see the new name at once instead of after the cache TTL
  12. A plan already matching the roster returns inside the lock without a write, an eviction, or a metric, so an IdP's repeated identical push is a read
  13. The response is built from the written row, so meta.lastModified reflects the roster write
  14. Removed members' updated_at is bumped in UTC, the instant Prisma stores, so a client sorting users by updated_at sees the detach
  15. Every member list the write binds goes through litellm.repositories.chunked_in in slices of IN_LIST_CHUNK_SIZE, and member lookup is perf(scim): batch group member identity lookups into one query per push #46412's batched read, kept as main has it
  16. Bulk key evictions (team, user, organization and session deletes, and the removed members' keys here) drop every entry from this worker's memory first, then from Redis in one chunked DEL, then tell the other workers in one pipelined Redis round trip, waiting at most 2 s on each step. A publish task per key would pass the publisher's 1,024 pending cap on a roster of a few hundred members and drop evictions, and a message carrying many keys would not parse on older subscribers during a rolling restart, so the pipeline still sends one message per key
  17. Before evicting, a push waits for any membership load already reading one of its members, so a read that started before the commit cannot put the old row back in the cache after the eviction
  18. A POST whose roster write fails deletes the empty team it just created, the same raw delete DELETE /scim/v2/Groups/{id} uses, so the IdP's retry creates the group again instead of getting a 409, or a second team of the same name when the POST had neither id nor externalId
  19. A push writes one audit row with the roster before and after, where the per-member path wrote one per member. That matches /team/member_add, which writes one row per request whatever the member count. One row per member would store a full roster snapshot each time, so an N-member push would write N full rosters
  20. The three user deletes, /user/delete, SCIM DELETE /Users/{id} and the bulk user delete, share one locked step. It takes every affected team's lock and then the user rows in that same order, the order a push takes them in, so a user delete and a group push that share a member serialize. Under those row locks it reads the users' teams again, and when a push committed in between and added them to a team it had not locked, it starts over with that team locked, up to 3 tries. After that the bulk delete reports those users as not deleted, and the other two answer 500 so the caller or the IdP retries. /user/delete still deletes the users' keys before this step, and SCIM DELETE /Users/{id} still blocks them and keeps them. Reading the teams only before the lock left the pushed group listing users the delete had removed
  21. A team that vanishes between the endpoint's existence check and the roster lock answers 404, which RFC 7644 section 3.12 gives for a missing resource. The merge base answered 404, 400 or 500 for that same race, depending on which adds and removes the push carried
  22. members in a response lists the members the team kept in their stored order, then the ones the push added sorted by id, not request order. SCIM defines no order for a multi-valued attribute, and the merge base also added members in sorted order
  23. A roster write lands every member or none, and a failure answers 500 with "Retry the request." so the IdP retries the whole push, the per-member failure contract from LIT-5381. The merge base kept the members written before the failure, and the IdP's retry then skipped them. A member whose user row is deleted between the push resolving its members and the locked write is created again under the same id and the verb's own created_via, and the write runs again, as the merge base's per-member write did. It keeps retrying while each try finds newly deleted members, and answers 500 only when a member it already created again is deleted a second time. With scim_upsert_user false that member is refused with the 400 "does not exist" any unknown member gets, where the merge base created it anyway through /team/member_add's upsert
  24. Members the gateway has never seen are created 10 at a time through _ensure_group_member_user, the call the merge base made one member at a time, not through one bulk_create_users call, so each new user gets the same defaults and audit row as before. Before creating any of them the push checks the whole batch against the license seat limit, as bulk user creation does, and answers 403 if the batch would pass it. The check counts users only when the license sets a limit. The merge base's per-user check let a push reach one user past the limit
  25. When scim_admin_group is set, the role update after a push locks the members' user rows in decision 9's order, then reads their teams and writes their roles under that lock, so two pushes that share members leave each member the role its committed teams give. The merge base read and wrote one member at a time with no lock

User Flow

Before: Okta's push of an 850-member group runs past the load balancer's timeout and fails

  1. An admin assigns an 850-member group to an Okta SCIM app pointed at https://litellm-domain/scim/v2, which sends group changes only as PUT
  2. After an earlier push of 550, Okta sends PUT https://litellm-domain/scim/v2/Groups/{id} with all 850 in members
  3. With the database 20 ms away, the 200 takes 100 s, so a 60 s load balancer timeout returns a 504 and Okta retries
  4. The admin removes 751 people, and Okta sends PUT https://litellm-domain/scim/v2/Groups/{id} with the 99 who stay
  5. That PUT takes 225 s, and Okta shows the push as failed

After: the same pushes answer in about a second, and Okta shows them as successful

  1. Okta sends the same PUT https://litellm-domain/scim/v2/Groups/{id} with all 850 members
  2. The 200 comes back in about 1 s and lists all 850
  3. Okta sends the same PUT with the 99 who stay
  4. That PUT answers 200 in about 1 s with the 99, and Okta shows the push as successful
  5. A removed member's key gets 401 from every pod

Linear ticket

Resolves LIT-9629

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/unit/<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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

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

Last updated: 059d3b8. QA ran on 9937bd6, and /live-pr-risk checked the three later fixes live at 63914d2. After that, dffeb01 adds only audit cells and 059d3b8 merges main with no conflicts, so neither changes what this proof shows

Before ran at 35970c3 on main. Statuses are 2xx unless shown. Race rows show the slowest request, or the rounds that passed when one failed. Full output is in this gist

Case Before After
Okta removal push Error Success, 0.72 s
1. POST 5 0.06 s 0.07 s
2. POST 500 2.02 s 0.13 s
3. POST 500, 5 ms 500, 5.15 s 0.34 s
4. PUT 500 12.49 s 0.11 s
5. PATCH add 500 11.72 s 0.17 s
6. Removed member's key 401 401
7. Rename 0.02 s 0.02 s
8. PUT 550 to 850, 20 ms 99.33 s 0.53 s
9. PUT 850 to 99, 20 ms 203.11 s 0.58 s
10. POST 1,000 4.03 s 0.20 s
11. PUT 200 new, 20 ms 104.60 s 6.10 s
12. Admins to 850, 20 ms 404.72 s 0.98 s
12. Admins to 99, 20 ms 293.93 s 0.76 s
13a. Push, team delete 143.0 s 1.68 s
13b. Two admin pushes 100.1 s 1.03 s
13c. Push, /user/delete 0 of 3 10 of 10
13d. Push, member_add 115.1 s 0.82 s
13e. Push, bulk delete 4 of 5 5 of 5
13f. Strict push, bulk delete 200, users back 400
13g. Push, SCIM user delete 0 of 3 10 of 10
L1. Push past 5 seats 200, 6 users 403, 5 users
T1. Strict, unknown member 400 400
S1 to S8 pass pass

Okta removal push, 850 to 8 members

Curl grew the pushed group to 850 users, as the Okta org caps at 10. An admin removed one user and clicked Push now

Before, at f50f141: the PUT runs 309 s, and Okta times out, retries 3 times and shows Error

04:10:03.590  PUT  /scim/v2/Groups/1e684fe5-...  req=69844B  200    0.351s
04:10:04.119  PUT  /scim/v2/Groups/1e684fe5-...  req=  800B  200  308.812s
04:11:06.096  PUT  /scim/v2/Groups/1e684fe5-...  req=  800B  200  247.114s
04:12:10.012  PUT  /scim/v2/Groups/1e684fe5-...  req=  800B  200  183.041s
04:13:16.392  PUT  /scim/v2/Groups/1e684fe5-...  req=  800B  200  116.739s
Okta System Log: Error while updating user group membership for group lit9629-push: Read timed out. FAILURE

pr45197-f50f14117f-base_c_pushgroups.png
pr45197-f50f14117f-base_c_systemlog_failures.png

After: the removal PUT answers in 0.72 s, and Okta logs a success

11:19:26.487  PUT  /scim/v2/Groups/916c491b-...  req=69844B  200  0.293s
11:19:26.880  PUT  /scim/v2/Groups/916c491b-...  req=  800B  200  0.719s
GET /scim/v2/Groups/916c491b-... -> 200, 8 members
Okta System Log: Group Push group lit9629-push updated in app. SUCCESS

pr45197-9937bd60a5-head_c_pushgroups.png
pr45197-9937bd60a5-head_c_systemlog.png

Cases 8 to 10, the reported pushes over curl

Every proxy runs 2 workers, and A and B are two proxies sharing Redis and Postgres behind a delay relay. The proxies run with enable_redis_auth_cache on, and cases 6, 9 and S6 make real gpt-5.4-nano calls. Every SCIM call is curl -s --max-time 600 -X <method> '<url>' -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/scim+json' --data-binary @<body> -w '%{http_code} %{time_total}'. r is lit9629-user-100 (removed by case 9) and k is lit9629-user-800 (kept), each with a team key

Before

8  PUT A (550 -> 850, 20 ms)  -> 200 99.332042, body lists the 550 from before the write; GET B -> 850
9  PUT B (850 -> 99, 20 ms)   -> 200 203.107655, body lists 850; GET A -> 99, r absent, k present
9  chat r on A, B, A, B       -> 401 x4, "token_not_found_in_db"; chat k on A, B -> 200 x2
10 POST A (1,000 members)     -> 201 4.030335; GET B -> 1000

After

8  PUT A (550 -> 850, 20 ms)  -> 200 0.534, body lists 850; GET B -> 850
9  chat r and k on A and B before -> 200 x4, "content": "OK"
9  PUT B (850 -> 99, 20 ms)   -> 200 0.583, body lists 99; GET A -> 99, r absent, k present
9  chat r on A, B, A, B       -> 401 x4, "token_not_found_in_db"
9  chat k on A, B             -> 200 x2
10 POST A (1,000 members)     -> 201 0.200; GET B -> 1000
Cases 11 and 12, new users and the admin group at 20 ms

11 PUTs 200 member ids no user has onto an empty group, so the push creates them. 12 sets scim_admin_group: lit9629-admins and pushes that group to 850 members, then down to 99 (751 to 849)

Before

11 PUT B (200 new, 20 ms)  -> 200 104.600734, body lists 0; GET A -> 200 listed; GET /scim/v2/Users fresh-000, 100, 199 -> 200
12 PUT B (0 -> 850, 20 ms) -> 200 404.716040, body lists 0; user 000 and 849 -> proxy_admin
12 PUT A (850 -> 99, 20 ms) -> 200 293.925161, body lists 850; 100 -> internal_user_viewer, 800 -> proxy_admin

After

11 PUT B (200 new, 20 ms)  -> 200 6.100, body lists 200; GET A -> 200 listed; GET /scim/v2/Users fresh-000, 100, 199 -> 200 x3
12 PUT B (0 -> 850, 20 ms) -> 200 0.978; GET /user/info 000 and 849 -> "user_role": "proxy_admin"
12 PUT A (850 -> 99, 20 ms) -> 200 0.757; 100 -> "internal_user_viewer", 800 -> "proxy_admin"
Races 13a to 13h, two writers over the same users

Each round starts both requests at the same instant, delay 0, and passes when both answer as stated, the read-back matches one of the two serial orders, and no listed member answers 404. Times are push, then the other writer. The race users are lit9629-race-000 to 849

13a PUT grow-N (850) on A vs POST /team/delete del-N on B; read back grow-N 850, users in grow-N and not del-N
    before: 78.0/0.42, 79.5/0.37, 84.4/0.34, 92.5/0.55, 143.0/0.50 s, all 200, 5 of 5 pass
    after:  0.46/0.41, 0.78/0.52, 0.81/0.43, 0.88/0.38, 1.68/0.44 s, all 200, 5 of 5 pass
13b PUT lit9629-admins (850) on A vs PUT another group (850) on B; grant, then revoke; read back both 850, admin role matches the admin group
    before: grant 50.7/50.3 to 66.7/66.3 s, revoke 61.4/66.1 to 97.9/100.1 s, all 200, 10 of 10 pass
    after:  grant 0.38 to 0.95 s, revoke 0.34 to 1.03 s, all 200, 40 of 40 pass (20 grant, 20 revoke)
13c PUT r13c-N (850) on A vs POST /user/delete (race 019..000) on B; pass is 830 or 850 listed and the listed users exist
    before: 27.7/0.12, 29.5/0.28, 32.7/0.17 s, all 200; 849, 838, 843 listed; listed users answering 404: 3, 2, 0; 0 of 3 pass
    after:  0.30 to 0.78 s / 0.07 to 1.17 s, all 200; 3 push-first rounds list 830 and the 20 answer 404; 7 delete-first rounds list 850 and the push created the 20 again; 10 of 10 pass
13d PUT r13d-N (850) on A vs POST /team/member_add (race 849..750) on B; read back 850 and 100
    before: 88.7/0.61, 102.7/0.65, 115.1/0.99 s, all 200; group 850, team 100 plus its creator; 3 of 3 pass
    after:  0.77/0.58, 0.80/0.60, 0.82/0.63 s, all 200; group 850, team 100 plus its creator; 3 of 3 pass
13e PUT r13e-N (850) on A vs POST /management/v1/users/bulk_delete (race 019..000) on B, then the same as POST and as PATCH add
    before: PUT 102.6/0.94, 114.9/0.13, 116.4/0.12 s, POST 82.1/0.52 s, PATCH 132.3/0.11 s, all 2xx; PUT round 1 lists 5 users answering 404; 4 of 5 pass
    after:  PUT 0.57/0.14, 0.43/0.09, 0.45/0.13 s, POST 0.50/0.11 s, PATCH 0.53/0.12 s, all 2xx; the push creates the 20 again, 850 listed, all 20 answer 200; 5 of 5 pass
13f 13e with scim_upsert_user false
    before: PUT 200 151.7/0.12, 123.9/0.21, 105.3/0.12 s; the push creates the 20 deleted users again despite strict mode
    after:  PUT 400 0.13/0.15, 0.08/0.07, 0.09/0.09 s and PATCH 400 0.10/0.12 s, "User with ID 'lit9629-race-000' does not exist"; group 0 members, the 20 answer 404
13g PUT r13g-N (850) on A vs five DELETE /scim/v2/Users/lit9629-race-00{0..4} on B
    before: 33.9, 36.2, 40.0 s / 204 x5 within 0.17 s; the group lists 1, 3, 3 users answering 404; 0 of 3 pass
    after:  0.27 to 0.48 s / 204 x5 within 0.60 s; 845 or 850 listed, 847 in round 1 where 2 of the 5 were created again; no listed user answers 404; 10 of 10 pass
13h PUT r13h-N (850) on A vs POST /management/v1/teams/{id}/members/bulk_delete (race 049..000) on B, run at 9937bd60a5 only
    after:  0.26 to 0.57 s / 0.02 to 0.10 s, all 200, 50 of 50 rows succeed; 850 listed and the team keeps none of the 50; 20 of 20 pass, 10 of them with the delete started 100 to 340 ms late
L1, T1 and P1 to P3, license limit, strict mode and short paths

L1 runs a 5-seat license with 3 users already, and T1 sets scim_upsert_user: false. P1 to P3 check the short POST, PATCH and PUT paths

Before

L1a PATCH add 3 new ids      -> 200 0.176082; /user/list total 6, past the 5 seats
L1b PUT 2 new ids            -> 200 0.027799, body lists 3
L1c PATCH add 1 new id       -> 200 0.030268; /user/list total 6
T1  PUT with an unknown id   -> 400 0.010714; GET the user -> 404
P1  POST with 3 new ids      -> 201 0.092961; GET B -> 3; each user -> 200
P2  PATCH add 5 new ids      -> 200 0.169079; GET A -> 5; each user -> 200
P3  PUT 3 -> 2               -> 200 0.025584, body lists 3; GET A -> 2

After

L1a PATCH add 3 new ids      -> 403 0.120776, "License is over limit"; the 3 answer 404; group 0 members
L1b PUT 2 new ids            -> 200 0.250848, body lists 2; both answer 200
L1c PATCH add 1 new id       -> 403 0.032; group 2 members; new-3 answers 404
T1  PUT with an unknown id   -> 400 0.146, "does not exist"; GET the user -> 404
P1  POST with 3 new ids      -> 201 0.194; GET B -> 3; each user -> 200
P2  PATCH add 5 new ids      -> 200 0.208; GET A -> 5; each user -> 200
P3  PUT 3 -> 2               -> 200 0.063; GET A -> 2
Cases 1 to 7 and S1 to S9

A and B alternate, delay 0 except case 3 (5 ms). S9 ran at 9937bd6 only

Before

1 POST A (5)                 -> 201 0.061; GET B -> 5
2 POST A (500, 0 ms)         -> 201 2.023; GET B -> 500
3 POST A (500, 5 ms)         -> 500 5.146, "Transaction already closed"; list B -> 1 group, 0 members
4 PUT B (500 onto empty)     -> 200 12.486; GET A -> 500
5 PATCH A (add 500)          -> 200 11.717; GET B -> 500
6 PATCH B (remove u)         -> 200 0.080; u's key on A, B, A, B -> 401 x4; kept key on A, B -> 200 x2
7 PATCH A (rename only)      -> 200 0.018; GET B -> new name
S1 POST /team/delete x (one of 3 teams) -> 200 0.041, user teams [a, x, b] -> [a, b]; delete a and b -> 200 0.055, teams []
S2 POST group lit9629-admins (u1, u2, u3) -> 201 0.057, all proxy_admin; PUT with u1 only -> 200 0.048, u2 and u3 back to internal_user_viewer
S3 PATCH add 5 unknown ids -> 200 0.160; GET -> 5 members; GET /scim/v2/Users each -> 200 x5
S4 POST /team/member_add [user_id, user_email, new user_id] -> 200 0.042; GET /team/info -> the 3 plus the creator
S5 POST /user/delete 2 users -> 200 0.048; both gone from both teams; /user/info -> 404 x2
S6 budget reset job: 2 users spend > 0 after real calls, both reset within 30 s
S7 DELETE /scim/v2/Users/{id} -> 204 0.070; GET -> 404; gone from both teams; its key on A and B -> 401
S8 POST /scim/v2/placeholders/{email}/merge -> 200 0.057; placeholder -> 404; the team lists the real user

After

1 POST A (5)                 -> 201 0.074; GET B -> 5
2 POST A (500, 0 ms)         -> 201 0.133; GET B -> 500
3 POST A (500, 5 ms)         -> 201 0.343; GET B -> 500
4 PUT B (500 onto empty)     -> 200 0.113; GET A -> 500
5 PATCH A (add 500)          -> 200 0.171; GET B -> 500
6 PATCH B (remove u)         -> 200 0.086; u's key on A, B, A, B -> 401 x4; kept key on A, B -> 200 x2, "content": "OK"
7 PATCH A (rename only)      -> 200 0.017; GET B -> new name
S1 POST /team/delete x (one of 3 teams) -> 200 0.059, user teams [a, x, b] -> [a, b]; delete a and b -> 200 0.075, teams []
S2 POST group lit9629-admins (u1, u2, u3) -> 201 0.060, all proxy_admin; PUT with u1 only -> 200 0.036, u2 and u3 back to internal_user_viewer
S3 PATCH add 5 unknown ids -> 200 0.079; GET -> 5 members; GET /scim/v2/Users each -> 200 x5
S4 POST /team/member_add [user_id, user_email, new user_id] -> 200 0.047; GET /team/info -> the 3 plus the creator
S5 POST /user/delete 2 users -> 200 0.061; both gone from both teams; /user/info -> 404 x2
S6 budget reset job: 2 users spend > 0 after real calls, both reset within 30 s
S7 DELETE /scim/v2/Users/{id} -> 204 0.101; GET -> 404; gone from both teams; its key on A and B -> 401
S8 POST /scim/v2/placeholders/{email}/merge -> 200 0.098; placeholder -> 404; the team lists the real user
S9 POST /management/v1/teams/{id}/members/bulk_delete [user_id, user_email] -> 200 0.223, 2 of 2 rows succeed; the team keeps its creator only, the member keeps its other team, and its key for this team -> 401 on A and B

Observations, all pre-existing:

  • Budget reset leaves 3.4e-21 spend, not 0
  • A strict-mode 400 still bumps the team row first

Audit round 1 of 3

16 cells red on the merge base where expected and green twice on the head, 119 controls green

Base is the merge base 958cba7 and head is 059d3b8, whose cells came in dffeb01. Each leg ran on its own rig on a dedicated GCE box with its own Postgres database, Redis, scripted upstream and a second proxy as the peer, the management group's two pytest workers, and INTEGRATION_PROXY_READY_SECONDS=240. The run ids are round_base, round_head1, round_head2 and round_ctl. Both head runs used seed 9629 and order seed 4519, collected the same 16 cells, passed the same 16, and had no skips and no retries

Row Surface Scenario Base Head 1 Head 2 Result
I1 SCIM pushes 500 members, statement count green green green PASS
I2 SCIM PUT Two groups trading rosters green green green PASS
I3 SCIM PUT Group deleted mid push green green green PASS
I4 SCIM PUT One membership write fails red green green PASS
I5 SCIM PUT Member value int green green green PASS
I5 SCIM PUT Member value list green green green PASS
I5 SCIM PUT Member value empty green green green PASS
I5 SCIM PUT Member value 5 KB green green green PASS
I5 SCIM PUT Member listed twice green green green PASS
I6 SCIM PATCH Okta remove by filter green green green PASS
I6 SCIM PATCH Entra remove by list green green green PASS
I6 SCIM PATCH Replace members green green green PASS
I7 SCIM PUT chaos Worker killed mid push red green green PASS
I8 Auth after removal Every client, both proxies green green green PASS
I9 Auth after removal Response cache hit green green green PASS
I10 /user/delete Team deleted mid wait red green green PASS
I11 Team members gauge /user/delete of 1 of 3 red green green PASS
I12 /team/delete 2,500 keys warmed on peer red green green PASS
I13, I14 Management controls 104 node ids, 122 cells green PASS
I15 SCIM seat limit, live Real 5-seat license 200 past limit 403 PASS

Every base red is the old behavior the ticket describes. I4 and I7 leave a partial roster where the head keeps the old one and the retry lands. I10's base never waits on the team lock and keeps the user. I11's base leaves the aliased gauge at 3. On I12 the base dropped 1,383 of the 2,500 eviction publishes past the 1,024 pending cap, and its /team/delete answered after about 18 s, past the client's 15 s timeout. I1 to I3, I5, I6, I8 and I9 are green on base because they guard against regressions this PR could cause. The controls skipped 3 cells that main already marks as known bugs. I1 and I2 ran in the control lane. I15 is the live row from 63914d2, carried since only tests and a clean main merge came after it

At 63914d2, I12 answered 503 once on the head. delete_team_models opens a 5 s Prisma transaction after the eviction work, and it expired at 5,445 ms while the shared database was slow. That code is outside this diff, and the merge base hit the same expiry at 16,250 ms in this round, so it is an inherited flake listed under Low caveats

Node ids
tests/integration/management/test_scim_group_bulk_roster.py::test_a_group_deleted_while_its_push_waits_on_a_member_row_answers_404_and_writes_nothing
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_whose_membership_write_fails_answers_5xx_keeps_the_old_roster_and_a_retry_lands
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent[int]
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent[list]
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent[empty]
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent[five-kilobytes]
tests/integration/management/test_scim_group_bulk_roster.py::test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent[duplicate]
tests/integration/management/test_scim_group_bulk_roster.py::test_patch_member_operation_shapes_land_the_expected_roster[okta-remove-by-filter]
tests/integration/management/test_scim_group_bulk_roster.py::test_patch_member_operation_shapes_land_the_expected_roster[entra-remove-by-value-list]
tests/integration/management/test_scim_group_bulk_roster.py::test_patch_member_operation_shapes_land_the_expected_roster[replace-members]
tests/integration/management/test_scim_group_bulk_roster.py::test_a_worker_killed_mid_push_leaves_the_old_roster_and_a_retry_lands_the_new_one
tests/integration/management/test_team_delete_member_cache_eviction.py::test_scim_removal_refuses_the_removed_members_team_key_for_every_client_on_both_proxies
tests/integration/management/test_team_delete_member_cache_eviction.py::test_scim_removal_refuses_a_cached_response_for_the_removed_members_key
tests/integration/management/test_user_delete_revokes_keys.py::test_user_delete_deletes_a_user_whose_team_is_deleted_while_it_waits_on_the_team_lock
tests/integration/management/test_team_delete_prometheus.py::test_user_delete_moves_the_aliased_team_members_gauge
tests/integration/management/test_team_delete_large_membership.py::test_deleting_a_team_with_more_keys_than_the_publish_cap_revokes_every_key_on_a_warmed_peer

The control lane ran every other cell in those five files plus test_access_group_team_sync.py, test_scim_admin_group.py, test_scim_group_member_not_yet_provisioned.py, test_scim_group_pathless_patch.py, test_scim_user_lifecycle.py, test_team_bulk_member_add.py, test_team_bulk_member_delete.py and test_warmed_policy.py

Type

🐛 Bug Fix

Caveats (if any)

Low

Five low caveats, plus eight from earlier rounds
  • The real Okta proof covers only the removal push, not the adds
    • The Okta org caps at 10 users, so curl grew the group to 850 first. The 550 to 850 grow and the 200 new users ran over curl in the PUT shape Okta sends, and Okta's own 9-member POST and PUT answered 201 and 200
  • SCIM DELETE /Groups still detaches members one at a time
    • For each member it reads the user and writes teams in sequence, so 850 members means about 1,700 round trips. The path is unchanged from the merge base, and a follow-up is filed
  • SCIM DELETE /Users/{id} now deletes a team key it used to block when the user's teams lists a team whose roster does not list the user
    • That only happens after the two fields drift apart. The user row is gone either way, so every key of the user answers 401 on both
  • A SCIM group create writes a created audit row with no members, then one updated row with the roster
    • The merge base wrote one created row listing the members. A PATCH with several operations now writes one row instead of one per operation, per decision 19
  • A /team/delete of a team with thousands of keys can answer 503 after its keys are already gone, when its 5 s model cleanup transaction expires on a slow database
    • The merge base hits the same expiry, and a retry finishes the delete. A follow-up is filed, since fixing it here would pull team model cleanup into this PR

From earlier rounds, still standing

  • PATCH still reads the team from the replica before the lock, as the merge base does, and the IdP's next full push corrects a skipped change
  • Bulk Redis evictions stop waiting after 2 s, so a slow Redis keeps a deleted key cached until its 60 s TTL
  • The roster transaction times out at 60 s instead of Prisma's 5 s default, since 850 members need more
  • A worker killed mid-push keeps the team lock until that 60 s timeout, as /team/delete already does
  • /user/update on a member a push is changing waits for the push to commit, under 2 s for 500 members
  • A PATCH remove of a member another push added after the pre-lock read does nothing, as on the merge base
  • A role recompute that fails after commit is not redone on the retry, as on the merge base
  • A rolled-back POST deletes its team but leaves new_team's side rows, the same rows DELETE /scim/v2/Groups/{id} leaves

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
/live-pr-risk at 63914d2

Two proxies sharing Redis and Postgres ran each scenario at the head and at the merge base, 35970c3

Breaking, all three fixed

  • /user/delete and SCIM DELETE /Users set the team members gauge with an empty team_alias, so a second series showed up next to the team's real one. _remove_members_from_team built the team without its alias. Fixed in a10f0a3, after which all three delete routes update the aliased series
  • /user/delete answered 404 "Team not found" and kept the user when a /team/delete of one of its teams committed while it waited on that team's lock, in 2 of 30 rounds against 0 of 30 at the merge base. Fixed in 09c64e4 by reading the team rows again under the lock, and 90 of 90 rounds then deleted the user
  • A SCIM PUT /Groups/{id} whose group was deleted while the push waited on a member's row lock answered 200 and left 3 membership rows and 3 teams entries pointing at the deleted group, in 5 of 6 rounds. The merge base answered 404 and wrote nothing in 6 of 6. Bugbot flagged it. Fixed in 63914d2, which rolls the push back and answers 404, and 6 of 6 rounds then left nothing behind (rows)

Backward incompatible

  • SCIM DELETE /Users/{id} deletes a team key it used to block when the user's teams lists a team that does not list the user. Every key of a deleted user answers 401 either way. Listed as a Low caveat for the reviewer to accept
  • Group creates and multi-operation PATCHes write a different set of audit rows, per decision 19. Listed as a Low caveat for the reviewer to accept
  • Response member order, per decision 22

Regression risk

  • Entra and OneLogin PATCH shapes reach the changed code only through unit tests, since no tenant of either was available

Dependency graph

Four scouts walked the SCIM write path, the user delete path, cache eviction, and the Prometheus and audit writers. Every HTTP dependent is either covered by a test that runs the changed code or was driven live. At 09c64e4 the 37 integration files that reach the changed code ran 373 tests, and the 5 that failed on the loaded box all passed on a rerun, one of them failing on the merge base too. At 63914d2 the 12 SCIM and roster files passed again, 97 tests with 3 skipped (rows). A /team/delete of 1,500 keys left every key answering 401 on the other proxy here, where the merge base answered 404 for 170 of them. SCIM DELETE /Users racing a group delete answers 400 in 4 of 15 rounds here and 3 of 15 at the merge base, which is pre-existing

Not verified

  • Outbound recorders, since the changed paths make no provider, guardrail or exporter call
  • Real Entra and OneLogin tenants
Bugbot summary

[!NOTE]
High Risk
Changes security-critical paths (SCIM provisioning, multi-worker auth cache eviction, and transactional user/team membership deletes) with complex locking and race retry logic; regressions could leave stale keys cached or partial rosters.

Overview
SCIM POST/PUT/PATCH on /scim/v2/Groups no longer enrolls members one-by-one through /team/member_add. Membership is reconciled in one advisory-locked transaction via new sync_team_roster (team_roster_sync.py), updating roster JSON, membership rows, user teams arrays, and removed members' team keys together. Group create fills the roster after new_team; failed roster writes roll back the empty team; license seat limits are checked once per batch of auto-created members.

User deletion (/user/delete, bulk delete, SCIM DELETE /Users) is centralized in delete_users_from_current_teams, with team locks taken in sorted order, USER_ROWS_LOCK_SQL before writes, re-read of teams under lock, and up to three retries when concurrent group pushes add teams mid-delete.

Auth cache invalidation for bulk key deletes switches from per-key work to evict_local → evict_shared → pipelined broadcast_evictions, so large team/user deletes do not hit the pending-publish cap and local/Redis copies drop before waiting on Redis. Team membership spend invalidation reuses await_inflight_team_membership_load.

Concurrency hardening: shared USER_ROWS_LOCK_SQL and ordered user-row locking on /team/member_add, team delete sweeps, and SCIM admin-role recompute (batched update_many under lock). Team delete strips deleted team IDs from users in one SQL statement. Air-gapped license exposes user_seat_limit() for reuse in SCIM checks.

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

…f one member at a time

POST, PUT and PATCH /scim/v2/Groups resolve every member in one query and write the roster, the
membership rows and the users' team tags in one transaction under the team's advisory lock, so a
500-member push runs a fixed number of statements instead of thousands. PUT now answers with the
roster it just wrote
@devin-ai-integration

devin-ai-integration Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

@greptile-apps

greptile-apps Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Rewrites group membership sync to use locked database transactions.

The PR appears safe to merge, with the remaining numbered finding fully addressed

Summary

SCIM group POST, PUT and PATCH now write memberships together in one locked transaction instead of updating each member separately

  • Member lookups and writes run in batches
  • User rows are locked in a shared order before writes
  • Cache cleanup clears local entries before pacing broadcasts
  • The latest commit removes the redundant module overview. No new issues were found in that change

Reviews (9) · Last reviewed commit: "docs(proxy): drop the module docstring t..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_scim_bulk_group_roster (059d3b8) with main (958cba7)

Open in CodSpeed

… rows in id order before the roster write

A PATCH naming no members opened the roster transaction and took the team advisory lock for nothing. A SIGKILLed worker then left its orphaned query engine holding that lock until the 60 s transaction timeout, and /team/delete, which takes the same lock, timed out behind it. An empty delta is now answered from a plain team read, with no transaction and no lock

Two groups trading members in parallel locked user rows in opposite orders, and one request died with a Postgres deadlock. Every user row a push touches is now locked with SELECT ... ORDER BY user_id FOR UPDATE before the first write, so the two requests serialize

The bulk roster cell gets a 120 s client through a new owned_proxy_process client_timeout, so an unfixed push fails on the statement count instead of the harness clock, requires positive counts on both pushes, and gains a parallel roster-trade test that answered 500 before the lock
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…oster from the writer

A rename-only PUT or PATCH wrote the new alias and left the team cached under
its id and old alias on every worker, so keys kept logging spend against the
old team alias until the TTL expired. The group write now evicts the cached
team (and broadcasts the eviction) right after the alias or metadata update.

sync_team_roster reads the team from the writer when the plan names nobody,
so a replica cannot hand back the pre-rename row; a plan already matching the
roster returns inside the lock without writing, evicting, or emitting the
members metric; the response is built from the written row, so lastModified
reflects the roster write; and detaching a removed member bumps the user's
updated_at like every other user write.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

The detach UPDATE wrote updated_at = CURRENT_TIMESTAMP, which Postgres casts
into Prisma's naive timestamp column in the session timezone, so on a database
whose session is not UTC the removed member's row landed hours away from the
UTC instants Prisma itself writes. Write NOW() AT TIME ZONE 'UTC' instead, and
have the bulk roster cell assert the bumped row sits between two reads of the
database's own UTC clock taken around the replace.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Every Prisma "in" filter the group write issues bound one parameter per
member with nothing bounding the list, which check_unbounded_in_lists
reports as 11 new findings. The single-field lookups now go through
litellm.repositories.chunked_in (caller_transaction inside the roster
transaction, per_chunk_ok for the role recompute), and the one
cross-field OR read slices its values at IN_LIST_CHUNK_SIZE and records
the bound. A push of IN_LIST_CHUNK_SIZE + 1 members now reads in two
slices, and a member named only in the last slice still resolves.
…up_roster

# Conflicts:
#	litellm/proxy/management_endpoints/scim/scim_v2.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@veria-ai

veria-ai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

Security review

No open security issues remain on this pull request.

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

…ops none

Veria pointed out that the invalidation publisher caps its pending tasks at
1,024 and drops the excess with a warning, and that a group push now detaches
every removed member's keys in one call instead of one member at a time, so a
removal of more than roughly 340 members (three cache keys each) silently left
stale key objects on the other replicas. The merge base never hit the cap
because each member was a separate request.

Bulk evictions (team, user, organization, and session key deletes, plus the
roster settle) now publish in slices of 256 and wait, bounded at two seconds,
for the backlog already handed to the event loop before each slice. A Redis
that never answers costs a bulk caller at most that wait per slice instead of
wedging the request, and single-key callers are untouched. Regression tests
push 1,500 keys and a 500-member removal through a slow publisher and assert
every eviction reaches Redis; both fail against the previous tip.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/proxy/auth/auth_checks.py Resolved
…adcasts

Greptile pointed out that pacing the broadcasts in slices also paced the
local eviction: a bulk delete waited for the publish backlog before dropping
the next slice from this worker's own memory, so on a Redis that accepts
connections but never answers a key deleted from the database kept
authenticating on the handling worker for up to two seconds per slice. The
merge base cleared every key locally at once.

Bulk evictions now drop every affected entry from this worker's memory first,
through the cache's own partition lookup since key objects live apart from
the other auth objects, and only then publish in paced slices. The roster
settle does the same for the deleted tokens, the JWT mapping keys and every
changed member's user and membership entries before any step that can wait.
Regression tests run both paths against a publisher that never answers and
check that nothing is still cached on this worker before the first bound
elapses; both fail with the local eviction removed.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

)
except Exception:
_ = await _table(TeamRepository(prisma_client)).delete(where={"team_id": group_id})
raise

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.

POST deletes team after committed roster

Medium Severity

_fill_new_group deletes the team on any exception from _sync_group_roster, including failures after sync_team_roster has already committed the roster. Validating the written row or settling caches can still raise, so a successful POST can drop the group while memberships and teams entries still point at it. The IdP retry then creates another team or hits a 409, and those leftover rows are not swept.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 059d3b8. Configure here.

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.

Nothing after the commit raises. Its cache, broadcast, metric and audit steps each catch their own errors, and the row was validated under the lock

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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.

✅ Bugbot reviewed your changes and found no new issues!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 059d3b8. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at 059d3b8. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • high: 1372 changed source lines is over the 500 line cap (tests, docs, cookbook and markdown are not counted)

Judge: skipped, the rules alone decided.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 15, 2026
@mateo-berri
mateo-berri enabled auto-merge (squash) October 15, 2026 17:28

This branch was successfully deployed

No deployments
e2e-changed — 059d3b83 Deployed Oct 15, 2026 by mateo-berri via oauth #5274
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants