Repository navigation
fix(scim): write a group's roster in one locked transaction instead of one member at a time - #45197
Conversation
…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
…m_scim_bulk_group_roster
…ter cell with two workers
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
Merging this PR will not alter performance
|
… 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
…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.
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.
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
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo 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.
…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.
|
bugbot run |
|
@litereview code-review |
|
bugbot run |
|
@litereview code-review |
…te locking and the eviction broadcast
|
bugbot run |
|
@litereview code-review |
| ) | ||
| except Exception: | ||
| _ = await _table(TeamRepository(prisma_client)).delete(where={"team_id": group_id}) | ||
| raise |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 059d3b8. Configure here.
There was a problem hiding this comment.
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
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 059d3b8. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Judge: skipped, the rules alone decided. Pushes do not re-run this check. Comment |


TLDR
Problem this solves:
How it solves it:
/scim/v2/Groupsall use itDecisions
create_manyonly when the team scopes member models; otherwise members link the team's shared budget after one lookupcreate_many(skip_duplicates=True)and the users'teamsarrays oneupdate_manyguarded byNOT teams has, so a retry after a partial IdP push is idempotentarray_removeUPDATE plusdelete_manycalls, and removed members' team keys are deleted with tombstones, as the per-member path diduser_id COLLATE "C", through the sharedUSER_ROWS_LOCK_SQLor a sortedINsubquery: a group push,/team/delete,/team/member_addwith 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'ssorted()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)meta.lastModifiedreflects the roster writeupdated_atis bumped in UTC, the instant Prisma stores, so a client sorting users byupdated_atsees the detachlitellm.repositories.chunked_inin slices ofIN_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 itDELETE /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 neitheridnorexternalId/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/user/delete, SCIMDELETE /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/deletestill deletes the users' keys before this step, and SCIMDELETE /Users/{id}still blocks them and keeps them. Reading the teams only before the lock left the pushed group listing users the delete had removedmembersin 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 ordercreated_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. Withscim_upsert_userfalse 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_ensure_group_member_user, the call the merge base made one member at a time, not through onebulk_create_userscall, 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 limitscim_admin_groupis 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 lockUser Flow
Before: Okta's push of an 850-member group runs past the load balancer's timeout and fails
membersAfter: the same pushes answer in about a second, and Okta shows them as successful
Linear ticket
Resolves LIT-9629
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreDelays 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
/user/deleteOkta 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
After: the removal PUT answers in 0.72 s, and Okta logs a success
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_cacheon, and cases 6, 9 and S6 make real gpt-5.4-nano calls. Every SCIM call iscurl -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 keyBefore
After
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-adminsand pushes that group to 850 members, then down to 99 (751 to 849)Before
After
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
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 pathsBefore
After
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
After
Observations, all pre-existing:
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 areround_base,round_head1,round_head2andround_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/user/delete/user/deleteof 1 of 3/team/deleteEvery 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/deleteanswered 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 itAt 63914d2, I12 answered 503 once on the head.
delete_team_modelsopens 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 caveatsNode ids
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.pyandtest_warmed_policy.pyType
🐛 Bug Fix
Caveats (if any)
Low
Five low caveats, plus eight from earlier rounds
DELETE /Groupsstill detaches members one at a timeteamsin sequence, so 850 members means about 1,700 round trips. The path is unchanged from the merge base, and a follow-up is filedDELETE /Users/{id}now deletes a team key it used to block when the user'steamslists a team whose roster does not list the usercreatedaudit row with no members, then oneupdatedrow with the rostercreatedrow listing the members. A PATCH with several operations now writes one row instead of one per operation, per decision 19/team/deleteof 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 databaseFrom earlier rounds, still standing
/team/deletealready does/user/updateon a member a push is changing waits for the push to commit, under 2 s for 500 membersremoveof a member another push added after the pre-lock read does nothing, as on the merge basenew_team's side rows, the same rowsDELETE /scim/v2/Groups/{id}leavesFinal Attestation
/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/deleteand SCIMDELETE /Usersset the team members gauge with an emptyteam_alias, so a second series showed up next to the team's real one._remove_members_from_teambuilt the team without its alias. Fixed in a10f0a3, after which all three delete routes update the aliased series/user/deleteanswered 404 "Team not found" and kept the user when a/team/deleteof 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 userPUT /Groups/{id}whose group was deleted while the push waited on a member's row lock answered 200 and left 3 membership rows and 3teamsentries 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
DELETE /Users/{id}deletes a team key it used to block when the user'steamslists 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 acceptRegression risk
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/deleteof 1,500 keys left every key answering 401 on the other proxy here, where the merge base answered 404 for 170 of them. SCIMDELETE /Usersracing a group delete answers 400 in 4 of 15 rounds here and 3 of 15 at the merge base, which is pre-existingNot verified
Bugbot summary