Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

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

Mateo Wang622daf3cdf13
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 85c3f741efb..8b32eb450e8 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -95,7 +95,12 @@ from litellm.proxy.auth.model_access_denied import (
model_access_denied_client_message,
)
from litellm.proxy.auth.route_checks import RouteChecks
-from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import publish_auth_cache_invalidation
+from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import (
+ broadcast_evictions,
+ evict_local,
+ evict_shared,
+ publish_auth_cache_invalidation,
+)
from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
from litellm.proxy.common_utils.http_parsing_utils import ( # noqa: F401 # legacy module exports
_safe_get_request_headers, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
@@ -3132,6 +3137,16 @@ async def _invalidate_usage_cache_entry(
)
+async def await_inflight_team_membership_load(user_id: str, team_id: str) -> None:
+ """Wait for a membership load already reading the DB, so a load that read the row before a
+ write committed cannot re-cache the old row after the write's eviction."""
+ inflight: Final[object] = _team_membership_inflight.pop(
+ team_membership_reservation_cache_key(user_id=user_id, team_id=team_id), None
+ )
+ if isinstance(inflight, asyncio.Task) and inflight is not asyncio.current_task():
+ await asyncio.wait((inflight,))
+
+
@with_service_target(SPEND_COUNTERS_TARGET)
async def invalidate_team_member_spend_state(
user_id: str,
@@ -3189,11 +3204,7 @@ async def invalidate_team_member_spend_state(
publish_auth_cache_invalidation,
)
- inflight: Final[object] = _team_membership_inflight.pop(
- team_membership_reservation_cache_key(user_id=user_id, team_id=team_id), None
- )
- if isinstance(inflight, asyncio.Task) and inflight is not asyncio.current_task():
- await asyncio.wait((inflight,))
+ await await_inflight_team_membership_load(user_id=user_id, team_id=team_id)
if new_spend is not None:
from litellm.proxy.proxy_server import SPEND_DB_FLOOR_CACHE_TTL_SECONDS, spend_counter_cache
@@ -3369,26 +3380,19 @@ async def delete_cache_key_objects(
Best-effort per key: the rows are already deleted by the time this runs, so an unreachable
cache backend must not abort the caller partway through its own cascade.
- """
- results: Final = await asyncio.gather(
- *(
- delete_cache_key_object(
- hashed_token=hashed_token,
- user_api_key_cache=user_api_key_cache,
- proxy_logging_obj=proxy_logging_obj,
- )
- for hashed_token in hashed_tokens
- ),
- return_exceptions=True,
- )
- for hashed_token, result in zip(hashed_tokens, results):
- if isinstance(result, BaseException):
- verbose_proxy_logger.warning(
- "Failed to evict cached key entry for %s; a deleted key may authenticate until its TTL expires: %s",
- hashed_token,
- result,
- )
+ Every token is dropped from this worker's memory first, then from the auth cache and the
+ internal usage cache in one batch each, so a deleted key stops authenticating here the instant
+ its rows are gone instead of refilling from Redis on the next miss. Every other worker then
+ gets the eviction in one pipelined broadcast: a publish per key would pass the publisher's
+ pending cap on a bulk delete, and the dropped keys would keep authenticating there until their
+ TTL.
+ """
+ evict_local(cache_keys=hashed_tokens, user_api_key_cache=user_api_key_cache)
+ await evict_shared(cache_keys=hashed_tokens, cache=user_api_key_cache)
+ if proxy_logging_obj is not None:
+ await evict_shared(cache_keys=hashed_tokens, cache=proxy_logging_obj.internal_usage_cache.dual_cache)
+ await broadcast_evictions(cache_keys=hashed_tokens)
class _TeamNotFoundDetail(TypedDict):
diff --git a/litellm/proxy/auth/litellm_license.py b/litellm/proxy/auth/litellm_license.py
index 242c2d75c7e..e1d6b2e090c 100644
--- a/litellm/proxy/auth/litellm_license.py
+++ b/litellm/proxy/auth/litellm_license.py
@@ -130,17 +130,18 @@ class LicenseCheck:
except Exception:
return False
+ def user_seat_limit(self) -> int | None:
+ if self.airgapped_license_data is None:
+ return None
+ max_users: Final = self.airgapped_license_data.get("max_users")
+ return max_users if isinstance(max_users, int) else None
+
def is_over_limit(self, total_users: int) -> bool:
"""
Check if the license is over the limit
"""
- if self.airgapped_license_data is None:
- return False
- if "max_users" not in self.airgapped_license_data or not isinstance(
- self.airgapped_license_data["max_users"], int
- ):
- return False
- return total_users > self.airgapped_license_data["max_users"]
+ seat_limit: Final = self.user_seat_limit()
+ return seat_limit is not None and total_users > seat_limit
def is_team_count_over_limit(self, team_count: int) -> bool:
"""
diff --git a/litellm/proxy/common_utils/auth_cache_invalidation_pubsub.py b/litellm/proxy/common_utils/auth_cache_invalidation_pubsub.py
index 2d874f7b473..40cdb117476 100644
--- a/litellm/proxy/common_utils/auth_cache_invalidation_pubsub.py
+++ b/litellm/proxy/common_utils/auth_cache_invalidation_pubsub.py
@@ -16,6 +16,7 @@ from litellm.proxy.common_utils.config_sync_pubsub import ( # noqa: F401 # leg
from litellm.proxy.common_utils.user_api_key_cache import AUTH_OBJECTS_TARGET
if TYPE_CHECKING:
+ from litellm.caching.dual_cache import DualCache
from litellm.caching.in_memory_cache import InMemoryCache
from litellm.caching.redis_cache import RedisCache
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
@@ -24,6 +25,7 @@ AUTH_CACHE_INVALIDATION_CHANNEL: Final = "litellm_proxy.auth_cache_invalidation"
_POLL_TIMEOUT_SECONDS: Final = 1.0
_MAX_PENDING_PUBLISHES: Final = 1024
_MAX_IN_FLIGHT_PUBLISHES: Final = 16
+_BULK_EVICTION_WAIT_SECONDS: Final = 2.0
_pending_publishes: Final[set[asyncio.Task[None]]] = set() # mutable-ok: strong refs keep background publishes alive
_in_flight_publishes: Final = asyncio.Semaphore(_MAX_IN_FLIGHT_PUBLISHES)
_BACKOFF_INITIAL_SECONDS: Final = 5.0
@@ -84,6 +86,32 @@ async def _publish_to_redis(redis_cache: "RedisCache", cache_key: str, message:
verbose_proxy_logger.warning("auth cache invalidation publish for %s failed: %s", cache_key, e)
+async def _publish_batch_to_redis(redis_cache: "RedisCache", cache_keys: tuple[str, ...]) -> None:
+ try:
+ client: Final = pubsub_capable_client(redis_cache)
+ channel: Final = auth_cache_invalidation_channel(redis_cache)
+ pipeline: Final = client.pipeline(transaction=False)
+ for cache_key in cache_keys:
+ _ = pipeline.publish(channel, _cache_invalidation_message_json(cache_key))
+ async with _in_flight_publishes:
+ _ = await pipeline.execute()
+ except Exception as e: # noqa: BLE001 # best-effort publish; mutations must never fail on redis errors
+ verbose_proxy_logger.warning("auth cache invalidation publish for %d keys failed: %s", len(cache_keys), e)
+
+
+def _has_room_for_publish(key_count: int) -> bool:
+ _pending_publishes.difference_update({task for task in _pending_publishes if task.done()})
+ if len(_pending_publishes) < _MAX_PENDING_PUBLISHES:
+ return True
+ verbose_proxy_logger.warning(
+ "auth cache invalidation publish for %d keys dropped: %d publishes already waiting on redis; "
+ "other workers keep their cached copy until its TTL expires",
+ key_count,
+ len(_pending_publishes),
+ )
+ return False
+
+
async def publish_auth_cache_invalidation(
cache_key: str, new_value: float | None = None, ttl: float | None = None
) -> None:
@@ -107,16 +135,7 @@ async def publish_auth_cache_invalidation(
drain the shared connection pool.
"""
redis_cache: Final = coordination_redis_cache()
- if redis_cache is None:
- return
- _pending_publishes.difference_update({task for task in _pending_publishes if task.done()})
- if len(_pending_publishes) >= _MAX_PENDING_PUBLISHES:
- verbose_proxy_logger.warning(
- "auth cache invalidation publish for %s dropped: %d publishes already waiting on redis; "
- "other workers keep their cached copy until its TTL expires",
- cache_key,
- len(_pending_publishes),
- )
+ if redis_cache is None or not _has_room_for_publish(1):
return
task: Final = asyncio.create_task(
_publish_to_redis(
@@ -127,6 +146,62 @@ async def publish_auth_cache_invalidation(
await asyncio.sleep(0)
+@with_service_target(AUTH_OBJECTS_TARGET)
+async def broadcast_evictions(cache_keys: Sequence[str]) -> None:
+ """
+ Tell every other worker to drop these keys, in one pipelined Redis round trip.
+
+ For bulk callers that already dropped the keys here and from Redis (``evict_local`` and
+ ``evict_shared``). A publish task per key would pass the pending cap above on a roster of a few
+ hundred members, and every dropped key would stay cached on the other workers until its TTL.
+ The caller waits for the round trip at most ``_BULK_EVICTION_WAIT_SECONDS``, so a Redis that
+ never answers cannot hang the request.
+ """
+ redis_cache: Final = coordination_redis_cache()
+ if redis_cache is None or not cache_keys or not _has_room_for_publish(len(cache_keys)):
+ return
+ task: Final = asyncio.create_task(_publish_batch_to_redis(redis_cache, tuple(cache_keys)))
+ _pending_publishes.add(task)
+ _ = await asyncio.wait((task,), timeout=_BULK_EVICTION_WAIT_SECONDS)
+
+
+def evict_local(cache_keys: Sequence[str], user_api_key_cache: "UserApiKeyCache") -> None:
+ """
+ Drop cached objects from this worker's memory alone, before any Redis round trip, so a deleted
+ key stops authenticating on the handling worker the instant its rows are gone, whatever Redis
+ is doing.
+ """
+ for cache_key in cache_keys:
+ _drop_from_memory(cache_key, user_api_key_cache)
+
+
+def _drop_from_memory(cache_key: str, user_api_key_cache: "UserApiKeyCache") -> None:
+ user_api_key_cache.in_memory_cache_for(cache_key).delete_cache(cache_key)
+
+
+@with_service_target(AUTH_OBJECTS_TARGET)
+async def evict_shared(cache_keys: Sequence[str], cache: "DualCache") -> None:
+ """
+ Drop cached objects from the cache's memory and, when it has one, its Redis layer, in one
+ chunked round trip.
+
+ Runs right after ``evict_local``: with ``enable_redis_auth_cache`` on, a miss on this worker
+ refills from Redis, so an entry dropped from memory alone comes straight back. Best-effort and
+ bounded like ``broadcast_evictions``: the rows are already gone, so a Redis that errors or never
+ answers must not fail the caller.
+ """
+ if not cache_keys:
+ return
+ try:
+ await asyncio.wait_for(cache.async_delete_cache_keys(cache_keys), timeout=_BULK_EVICTION_WAIT_SECONDS)
+ except Exception as e: # noqa: BLE001 # best-effort: a Redis error must not fail a committed write
+ verbose_proxy_logger.warning(
+ "Failed to drop %d cached entries from Redis; stale objects may be served until their TTL expires: %s",
+ len(cache_keys),
+ e,
+ )
+
+
@with_service_target(AUTH_OBJECTS_TARGET)
async def evict_and_broadcast(cache_keys: Sequence[str], user_api_key_cache: "UserApiKeyCache") -> None:
"""
@@ -219,7 +294,7 @@ class AuthCacheInvalidationSubscriber:
for additional_cache in self._additional_in_memory_caches:
additional_cache.set_cache(parsed.cache_key, parsed.new_value, ttl=parsed.ttl)
return
- self._user_api_key_cache.in_memory_cache_for(parsed.cache_key).delete_cache(parsed.cache_key)
+ _drop_from_memory(parsed.cache_key, self._user_api_key_cache)
for additional_cache in self._additional_in_memory_caches:
additional_cache.delete_cache(parsed.cache_key)
diff --git a/litellm/proxy/common_utils/config_sync_pubsub.py b/litellm/proxy/common_utils/config_sync_pubsub.py
index 579db290190..af5441c2e94 100644
--- a/litellm/proxy/common_utils/config_sync_pubsub.py
+++ b/litellm/proxy/common_utils/config_sync_pubsub.py
@@ -24,11 +24,19 @@ class _ConfigSyncPubSub(Protocol):
ConfigSyncPubSub = _ConfigSyncPubSub
+class _PublishPipeline(Protocol):
+ def publish(self, channel: str, message: str) -> object: ...
+
+ def execute(self) -> Awaitable[object]: ...
+
+
class _ConfigSyncPubSubClient(Protocol):
def publish(self, channel: str, message: str) -> Awaitable[int]: ...
def pubsub(self) -> ConfigSyncPubSub: ...
+ def pipeline(self, transaction: bool = True) -> _PublishPipeline: ...
+
CONFIG_SYNC_CHANNEL: Final = "litellm_proxy.config_change"
CONFIG_SYNC_DEBOUNCE_SECONDS: Final = 1.0
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index 4e1001a4430..63cc8f0e3ba 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -75,6 +75,7 @@ from litellm.proxy.management_endpoints.key_management_endpoints import ( # noq
generate_key_helper_fn,
prepare_metadata_fields,
)
+from litellm.proxy.management_helpers.bulk_user_deletion import delete_users_from_current_teams
from litellm.proxy.management_helpers.object_permission_utils import ( # noqa: F401 # legacy module exports
_set_object_permission, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
handle_update_object_permission_common,
@@ -85,9 +86,7 @@ from litellm.proxy.utils import handle_exception_on_proxy, hash_password
from litellm.repositories.organization_repository import OrganizationRepository
from litellm.repositories.prisma_protocols import TableActions
from litellm.repositories.table_repositories import (
- InvitationLinkRepository,
OrganizationMembershipRepository,
- TeamMembershipRepository,
)
from litellm.repositories.team_repository import TeamRepository
from litellm.repositories.user_repository import UserRepository
@@ -160,15 +159,6 @@ def _organization_membership_table(
return membership_table
-def _invitation_link_table(
- prisma_client: "PrismaClient | None",
-) -> "TableActions[prisma_models.LiteLLM_InvitationLink]":
- invitation_table: Final[TableActions[prisma_models.LiteLLM_InvitationLink]] = InvitationLinkRepository(
- prisma_client
- ).table
- return invitation_table
-
-
def _organization_table(
prisma_client: "PrismaClient | None",
) -> "TableActions[prisma_models.LiteLLM_OrganizationTable]":
@@ -178,15 +168,6 @@ def _organization_table(
return organization_table
-def _team_membership_table(
- prisma_client: "PrismaClient | None",
-) -> "TableActions[prisma_models.LiteLLM_TeamMembership]":
- team_membership_table: Final[TableActions[prisma_models.LiteLLM_TeamMembership]] = TeamMembershipRepository(
- prisma_client
- ).table
- return team_membership_table
-
-
async def _hash_password_in_dict(
data: dict,
general_settings: Mapping[str, object],
@@ -2431,9 +2412,6 @@ async def delete_user(
Parameters:
- user_ids: List[str] - The list of user id's to be deleted.
"""
- from litellm.proxy.management_endpoints.team_endpoints import (
- cleanup_members_with_roles,
- )
from litellm.proxy.management_helpers.audit_logs import (
get_audit_log_changed_by,
is_audit_logging_enabled,
@@ -2542,31 +2520,6 @@ async def delete_user(
)
)
- ## CLEANUP MEMBERS_WITH_ROLES
- fetch_all_teams: Sequence[prisma_models.LiteLLM_TeamTable] = await TeamRepository(
- prisma_client
- ).table.find_many(where={"team_id": {"in": user_row.teams}})
- teams_to_update: list[tuple[str, str]] = []
- for team in fetch_all_teams:
- removed_team_members, new_team_members = cleanup_members_with_roles(
- existing_team_row=LiteLLM_TeamTable.model_validate(team.model_dump()),
- data=TeamMemberDeleteRequest(
- team_id=team.team_id,
- user_id=user_row.user_id,
- user_email=user_row.user_email,
- ),
- )
- if removed_team_members:
- _db_new_team_members: list[dict] = [m.model_dump() for m in new_team_members]
- teams_to_update.append((team.team_id, json.dumps(_db_new_team_members)))
-
- ## update teams
-
- for team_id, members_with_roles in teams_to_update:
- await TeamRepository(prisma_client).table.update(
- where={"team_id": team_id},
- data={"members_with_roles": members_with_roles},
- )
# End of Audit logging
## DELETE ASSOCIATED KEYS
@@ -2591,27 +2544,16 @@ async def delete_user(
)
await evict_and_broadcast(cache_keys=jwt_mapping_cache_keys, user_api_key_cache=user_api_key_cache)
- ## DELETE ASSOCIATED INVITATION LINKS
- await _invitation_link_table(prisma_client).delete_many(
- where={
- "OR": [
- {"user_id": {"in": data.user_ids}},
- {"created_by": {"in": data.user_ids}},
- {"updated_by": {"in": data.user_ids}},
- ]
- }
+ deleted_users: Final = await delete_users_from_current_teams(
+ prisma_client=prisma_client,
+ user_ids=data.user_ids,
+ user_api_key_dict=user_api_key_dict,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ litellm_changed_by=litellm_changed_by,
)
-
- ## DELETE ASSOCIATED ORGANIZATION MEMBERSHIPS
- await _organization_membership_table(prisma_client).delete_many(where={"user_id": {"in": data.user_ids}})
-
- ## DELETE ASSOCIATED TEAM MEMBERSHIPS
- await _team_membership_table(prisma_client).delete_many(where={"user_id": {"in": data.user_ids}})
-
- ## DELETE USERS
- deleted_users: Final = await _user_table(prisma_client).delete_many(where={"user_id": {"in": data.user_ids}})
- await evict_and_broadcast(cache_keys=tuple(data.user_ids), user_api_key_cache=user_api_key_cache)
-
+ if isinstance(deleted_users, str):
+ raise HTTPException(status_code=500, detail={"error": deleted_users})
return deleted_users
diff --git a/litellm/proxy/management_endpoints/scim/scim_v2.py b/litellm/proxy/management_endpoints/scim/scim_v2.py
index a4ffa5cfd4d..ea3628e86d6 100644
--- a/litellm/proxy/management_endpoints/scim/scim_v2.py
+++ b/litellm/proxy/management_endpoints/scim/scim_v2.py
@@ -49,6 +49,7 @@ from litellm.proxy._types import (
from litellm.proxy.auth.auth_checks import ( # noqa: F401 # legacy module exports
_delete_cache_key_object, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
delete_cache_key_object,
+ delete_cache_team_object,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import evict_and_broadcast
@@ -56,6 +57,7 @@ from litellm.proxy.common_utils.http_parsing_utils import ( # noqa: F401 # leg
_safe_get_request_headers, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
safe_get_request_headers,
)
+from litellm.proxy.litellm_pre_call_utils import sanitize_for_log
from litellm.proxy.management_endpoints.internal_user_endpoints import new_user
from litellm.proxy.management_endpoints.scim.scim_transformations import (
ScimTransformations,
@@ -65,6 +67,25 @@ from litellm.proxy.management_endpoints.team_endpoints import (
team_member_add,
team_member_delete,
)
+from litellm.proxy.management_helpers.access_group_team_sync import USER_ROWS_LOCK_SQL
+from litellm.proxy.management_helpers.bulk_user_creation import (
+ BULK_NEW_USER_CONCURRENCY,
+ _bounded, # pyright: ignore[reportPrivateUsage] # the bounded gather /user/bulk_new runs its row writes through
+)
+from litellm.proxy.management_helpers.bulk_user_deletion import delete_users_from_current_teams
+from litellm.proxy.management_helpers.team_roster_sync import (
+ ROSTER_TX_TIMEOUT,
+ MembersMissing,
+ RosterDelta,
+ RosterPlan,
+ RosterSync,
+ RosterSyncOutcome,
+ RosterTarget,
+ TeamGone,
+ sync_team_roster,
+ team_tx_db,
+ user_tx_db,
+)
from litellm.proxy.utils import ( # noqa: F401 # legacy module exports
PrismaClient,
_premium_user_check, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
@@ -72,11 +93,6 @@ from litellm.proxy.utils import ( # noqa: F401 # legacy module exports
premium_user_check,
)
from litellm.repositories.chunked_in import find_many_in
-from litellm.repositories.table_repositories import (
- InvitationLinkRepository,
- OrganizationMembershipRepository,
- TeamMembershipRepository,
-)
from litellm.repositories.team_repository import TeamRepository
from litellm.repositories.user_repository import UserRepository
from litellm.repositories.verification_token_repository import (
@@ -89,6 +105,12 @@ if TYPE_CHECKING:
from prisma.models import LiteLLM_VerificationToken as PrismaVerificationToken
+_SET_USER_ROLE_SQL: Final = (
+ "UPDATE \"LiteLLM_UserTable\" SET user_role = $1, updated_at = (NOW() AT TIME ZONE 'UTC') "
+ "WHERE user_id = ANY($2::text[])"
+)
+
+
class _UserTableClient(Protocol):
async def find_first(self, where: Mapping[str, object]) -> LiteLLM_UserTable | None: ...
@@ -104,7 +126,7 @@ class _UserTableClient(Protocol):
async def update(self, where: Mapping[str, object], data: Mapping[str, object]) -> LiteLLM_UserTable: ...
- async def delete(self, where: Mapping[str, object]) -> LiteLLM_UserTable | None: ...
+ async def update_many(self, where: Mapping[str, object], data: Mapping[str, object]) -> int: ...
async def count(self, where: Mapping[str, object] | None = None) -> int: ...
@@ -135,10 +157,6 @@ class _VerificationTokenTableClient(Protocol):
) -> "PrismaVerificationToken | None": ...
-class _UserReferencingTableClient(Protocol):
- async def delete_many(self, where: Mapping[str, object]) -> int: ...
-
-
@overload
def _table(repository: UserRepository) -> _UserTableClient: ...
@@ -151,19 +169,8 @@ def _table(repository: TeamRepository) -> _TeamTableClient: ...
def _table(repository: VerificationTokenRepository) -> _VerificationTokenTableClient: ...
-@overload
def _table(
- repository: InvitationLinkRepository | OrganizationMembershipRepository | TeamMembershipRepository,
-) -> _UserReferencingTableClient: ...
-
-
-def _table(
- repository: UserRepository
- | TeamRepository
- | VerificationTokenRepository
- | InvitationLinkRepository
- | OrganizationMembershipRepository
- | TeamMembershipRepository,
+ repository: UserRepository | TeamRepository | VerificationTokenRepository,
) -> object:
return repository.table
@@ -473,26 +480,40 @@ async def _recompute_scim_member_roles(prisma_client: PrismaClient, user_ids: It
Recompute and persist each user's global proxy role from their resulting team
membership. No-op unless scim_admin_group is configured, so a SCIM group write
that drops a member from the admin group demotes them just like the user
- endpoints do, and the role is left untouched when the feature is off.
+ endpoints do, and the role is left untouched when the feature is off. The users'
+ rows are locked through ``USER_ROWS_LOCK_SQL`` before their teams are read, the
+ same lock a roster write takes, so a concurrent group push cannot change a
+ member's teams between the read and the role write.
"""
admin_group: Final = await _get_scim_admin_group()
if admin_group is None:
return
+ ids: Final = tuple(dict.fromkeys(user_ids))
+ if not ids:
+ return
default_role: Final = _default_scim_user_role()
- for user_id in user_ids:
- user = await _table(UserRepository(prisma_client)).find_unique(where={"user_id": user_id})
- if user is None:
- continue
- resolved_role = _resolve_scim_user_role(
- await _scim_groups_from_team_ids(prisma_client, user.teams or []),
- admin_group,
- default_role,
- )
- await _table(UserRepository(prisma_client)).update(
- where={"user_id": user_id},
- data={"user_role": resolved_role},
+ async with prisma_client.tx(timeout=ROSTER_TX_TIMEOUT) as tx:
+ await tx.query_raw(USER_ROWS_LOCK_SQL, sorted(ids))
+ rows: Final = await find_many_in(user_tx_db(tx), "user_id", ids)
+ team_ids: Final = tuple(dict.fromkeys(chain.from_iterable(row.teams for row in rows)))
+ teams: Final = await find_many_in(team_tx_db(tx), "team_id", team_ids)
+ alias_of: Final = MappingProxyType({team.team_id: team.team_alias for team in teams})
+ resolved: Final = tuple(
+ (
+ row.user_id,
+ _resolve_scim_user_role(
+ [SCIMUserGroup(value=team_id, display=alias_of.get(team_id)) for team_id in row.teams],
+ admin_group,
+ default_role,
+ ),
+ )
+ for row in rows
)
+ for role in dict.fromkeys(role for _, role in resolved):
+ await tx.execute_raw(
+ _SET_USER_ROLE_SQL, role, sorted(user_id for user_id, user_role in resolved if user_role == role)
+ )
class _ResolvedUserMember(NamedTuple):
@@ -885,6 +906,54 @@ async def _ensure_group_member_user(
raise HTTPException(status_code=500, detail=detail)
+async def _raise_if_batch_over_license_limit(new_user_count: int, prisma_client: PrismaClient) -> None:
+ from litellm.proxy.proxy_server import (
+ _license_check, # pyright: ignore[reportPrivateUsage] # same proxy license singleton /user/new reads
+ )
+
+ if _license_check.user_seat_limit() is None:
+ return
+ billable_users: Final = await UserRepository(prisma_client).count_billable_users()
+ if _license_check.is_over_limit(total_users=billable_users + new_user_count):
+ detail: Final[_ScimErrorDetail] = {
+ "error": "License is over limit. Please contact [email protected] to upgrade your license."
+ }
+ raise HTTPException(status_code=403, detail=detail)
+
+
+def _member_not_provisioned_error(user_id: str) -> HTTPException:
+ detail: Final[_ScimErrorDetail] = {
+ "error": f"User with ID '{user_id}' does not exist. "
+ "Please create the user first via POST /Users before adding to group."
+ }
+ return HTTPException(status_code=400, detail=detail)
+
+
+async def _create_group_member_users(
+ user_ids: Sequence[str], created_via: str, prisma_client: PrismaClient
+) -> tuple[NewUserResponse, ...]:
+ """Create the group members' user rows, ``BULK_NEW_USER_CONCURRENCY`` at a time, after
+ checking the license seat limit once for the whole batch, as bulk user creation does.
+
+ Raises:
+ HTTPException: 403 when the batch would push the deployment over its license seat
+ limit, 500 when a user can neither be created nor found.
+ """
+ if user_ids:
+ await _raise_if_batch_over_license_limit(len(user_ids), prisma_client)
+ creations: Final = await _bounded(
+ BULK_NEW_USER_CONCURRENCY,
+ tuple(
+ _ensure_group_member_user(user_id=user_id, created_via=created_via, prisma_client=prisma_client)
+ for user_id in user_ids
+ ),
+ )
+ failure: Final = next((outcome for outcome in creations if isinstance(outcome, BaseException)), None)
+ if failure is not None:
+ raise failure
+ return tuple(created for created in creations if isinstance(created, NewUserResponse))
+
+
def _roster_entries_named_by(value: str, roster: frozenset[str], resolved: tuple[str, ...]) -> tuple[str, ...]:
"""The members of this group a removal value names.
@@ -1000,13 +1069,7 @@ async def _resolve_group_member_ids(
)
if partition.unknown_ids and not await _get_scim_upsert_user_setting():
- raise HTTPException(
- status_code=400,
- detail={
- "error": f"User with ID '{partition.unknown_ids[0]}' does not exist. "
- "Please create the user first via POST /Users before adding to group."
- },
- )
+ raise _member_not_provisioned_error(partition.unknown_ids[0])
unique_unknown_ids: Final = tuple(dict.fromkeys(partition.unknown_ids))
for user_id in unique_unknown_ids:
@@ -1016,16 +1079,7 @@ async def _resolve_group_member_ids(
user_id,
)
- creations: Final = tuple(
- [
- (
- user_id,
- await _ensure_group_member_user(user_id=user_id, created_via=created_via, prisma_client=prisma_client),
- )
- for user_id in unique_unknown_ids
- ]
- )
- created_users: Final = tuple(created for _, created in creations if created is not None)
+ created_users: Final = await _create_group_member_users(unique_unknown_ids, created_via, prisma_client)
return GroupMemberExtractionResult(
existing_member_ids=partition.resolved_ids,
@@ -1059,15 +1113,15 @@ async def _extract_group_member_ids(group: SCIMGroup) -> GroupMemberExtractionRe
async def _get_team_members_display(member_ids: list[str]) -> list[SCIMMember]:
"""Get SCIMMember objects with display names for a list of member IDs."""
prisma_client: Final = await _get_prisma_client_or_raise_exception()
- members: Final[list[SCIMMember]] = []
-
- for member_id in member_ids:
- user = await _table(UserRepository(prisma_client)).find_unique(where={"user_id": member_id})
- if user:
- display_name = user.user_email or user.user_id
- members.append(SCIMMember(value=user.user_id, display=display_name, type="User"))
-
- return members
+ if not member_ids:
+ return []
+ rows: Final = await find_many_in(_table(UserRepository(prisma_client)), "user_id", member_ids)
+ user_of: Final = MappingProxyType({row.user_id: row for row in rows})
+ return [
+ SCIMMember(value=user.user_id, display=user.user_email or user.user_id, type="User")
+ for user in (user_of.get(member_id) for member_id in member_ids)
+ if user is not None
+ ]
async def _handle_team_membership_changes(
@@ -1165,26 +1219,6 @@ async def _set_user_keys_blocked(user_id: str, blocked: bool) -> int:
return len(affected_keys)
-async def _delete_rows_referencing_user(prisma_client: PrismaClient, *, user_id: str) -> None:
- """Drop rows whose foreign keys reference ``LiteLLM_UserTable.user_id``.
-
- Required before deleting the user row itself, otherwise Postgres rejects
- the user delete with an FK constraint violation (e.g.
- ``LiteLLM_InvitationLink_user_id_fkey``).
- """
- await _table(InvitationLinkRepository(prisma_client)).delete_many(
- where={
- "OR": [
- {"user_id": user_id},
- {"created_by": user_id},
- {"updated_by": user_id},
- ]
- }
- )
- await _table(OrganizationMembershipRepository(prisma_client)).delete_many(where={"user_id": user_id})
- await _table(TeamMembershipRepository(prisma_client)).delete_many(where={"user_id": user_id})
-
-
def _scim_active_value(metadata: Mapping[str, object] | None) -> bool | None:
"""Read the SCIM active flag from a user's metadata dict, if present."""
if not metadata:
@@ -1972,14 +2006,18 @@ async def delete_user(
await _set_user_keys_blocked(user_id=user_id, blocked=True)
- await _delete_rows_referencing_user(prisma_client, user_id=user_id)
+ from litellm.proxy.proxy_server import proxy_logging_obj, user_api_key_cache
- # Delete user
- await _table(UserRepository(prisma_client)).delete(where={"user_id": user_id})
-
- from litellm.proxy.proxy_server import user_api_key_cache
-
- await evict_and_broadcast(cache_keys=(user_id,), user_api_key_cache=user_api_key_cache)
+ deleted: Final = await delete_users_from_current_teams(
+ prisma_client=prisma_client,
+ user_ids=(user_id,),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ litellm_changed_by=None,
+ )
+ if isinstance(deleted, str):
+ raise HTTPException(status_code=500, detail={"error": deleted})
return Response(status_code=204)
except Exception as e:
@@ -2679,23 +2717,23 @@ async def create_group(
# Extract and validate group members (all users must exist)
member_result: Final = await _extract_group_member_ids(group)
- members_with_roles = [Member(user_id=member_id, role="user") for member_id in member_result.all_member_ids]
- # Create team in database
created_team: Final = await new_team(
data=_new_team_request_with_defaults(
team_id=team_id,
team_alias=group.displayName,
- members_with_roles=members_with_roles,
+ members_with_roles=(),
),
http_request=Request(scope={"type": "http", "path": "/scim/v2/Groups"}),
user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
)
-
+ team: Final = (
+ (await _fill_new_group(team_id, frozenset(member_result.all_member_ids), prisma_client)).team
+ if member_result.all_member_ids
+ else LiteLLM_TeamTable.model_validate(created_team)
+ )
await _recompute_scim_member_roles(prisma_client, member_result.all_member_ids)
-
- scim_group: Final = await ScimTransformations.transform_litellm_team_to_scim_group(created_team)
- return scim_group
+ return await ScimTransformations.transform_litellm_team_to_scim_group(team)
except Exception as e:
raise handle_exception_on_proxy(e)
@@ -2741,35 +2779,27 @@ async def update_group(
}
# Update team in database
- updated_team: Final = await _table(TeamRepository(prisma_client)).update(
+ await _table(TeamRepository(prisma_client)).update(
where={"team_id": group_id},
data=update_data,
)
+ await _evict_group_cache(group_id, existing_team.team_alias)
- # Handle user-team relationship changes
- current_members: Final = set(await _get_team_member_user_ids_from_team(existing_team))
- verbose_proxy_logger.debug("SCIM PUT GROUP current_members: %s", current_members)
- final_members: Final = set(member_result.all_member_ids)
- verbose_proxy_logger.debug("SCIM PUT GROUP final_members: %s", final_members)
-
- await _handle_group_membership_changes(
- group_id=group_id,
- current_members=current_members,
- final_members=final_members,
+ sync: Final = await _sync_group_roster(
+ group_id,
+ RosterTarget(member_ids=frozenset(member_result.all_member_ids)),
+ "scim_group_membership",
+ prisma_client,
)
# A rename can flip whether this group matches scim_admin_group by display
# name, so retained members must be re-resolved too, not just the ones whose
# membership changed.
alias_changed: Final = existing_team.team_alias != group.displayName
- await _recompute_scim_member_roles(
- prisma_client,
- (current_members | final_members if alias_changed else current_members ^ final_members),
- )
+ await _recompute_scim_member_roles(prisma_client, _roles_to_recompute(sync, alias_changed))
# Convert to SCIM format and return
- scim_group: Final = await ScimTransformations.transform_litellm_team_to_scim_group(updated_team)
- return scim_group
+ return await ScimTransformations.transform_litellm_team_to_scim_group(sync.team)
except Exception as e:
raise handle_exception_on_proxy(e)
@@ -2996,72 +3026,127 @@ async def _process_group_patch_operations(
return update_data, final_members, replace_target
-async def _apply_group_patch_updates(group_id: str, update_data: dict[str, object], prisma_client: PrismaClient):
+async def _evict_group_cache(group_id: str, team_alias: str | None) -> None:
+ from litellm.proxy.proxy_server import proxy_logging_obj, user_api_key_cache
+
+ await delete_cache_team_object(
+ team_id=group_id,
+ team_alias=team_alias,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+async def _apply_group_patch_updates(
+ group_id: str, update_data: dict[str, object], prisma_client: PrismaClient, team_alias: str | None
+):
"""Apply the group's metadata/displayName patch updates to the database.
Membership itself is not written here; it is reconciled onto the source of
- truth (members_with_roles and each member's user.teams) by
- _handle_group_membership_changes via team_member_add/team_member_delete.
- Writing the legacy `members` column here too would create a second, unread
- copy of membership that could drift from the source of truth.
+ truth (members_with_roles, each member's user.teams and the membership table)
+ by ``_sync_group_roster`` in one bulk transaction. Writing the legacy `members`
+ column here too would create a second, unread copy of membership that could
+ drift from the source of truth. A write evicts the team cached under its id and
+ its old alias, so a rename-only PATCH is not served from the stale copy until
+ its TTL expires.
"""
if "metadata" in update_data and isinstance(update_data["metadata"], dict):
update_data["metadata"] = safe_dumps(update_data["metadata"])
- if update_data:
- return await TeamRepository(prisma_client).table.update(
- where={"team_id": group_id},
- data=update_data,
- )
- return await TeamRepository(prisma_client).table.find_unique(where={"team_id": group_id})
+ if not update_data:
+ return await TeamRepository(prisma_client).table.find_unique(where={"team_id": group_id})
+ updated: Final = await TeamRepository(prisma_client).table.update(where={"team_id": group_id}, data=update_data)
+ await _evict_group_cache(group_id, team_alias)
+ return updated
-async def _handle_group_membership_changes(group_id: str, current_members: set[str], final_members: set[str]) -> None:
- """Reconcile the group roster, attempting every member before reporting failures.
+def _roster_ids(team: LiteLLM_TeamTable) -> frozenset[str]:
+ return frozenset(member.user_id for member in team.members_with_roles if member.user_id is not None)
- Aborting on the first failure would leave the remaining members unattempted on top
- of unrolled-back, so every member is written and the ones that failed are named for
- the IdP's next push to reconcile.
- """
- members_to_add: Final = sorted(final_members - current_members)
- members_to_remove: Final = sorted(current_members - final_members)
- verbose_proxy_logger.debug("members_to_add: %s", members_to_add)
- verbose_proxy_logger.debug("members_to_remove: %s", members_to_remove)
+def _roles_to_recompute(sync: RosterSync, alias_changed: bool) -> frozenset[str]:
+ """Whose global role a group write can have changed: the members it added or removed,
+ and every retained member too when a rename can flip the admin-group match."""
+ return (_roster_ids(sync.team) | sync.removed) if alias_changed else (sync.added | sync.removed)
- writes: Final = tuple(
- chain(
- (
- (
- f"add {member_id} to {group_id}",
- partial(
- patch_team_membership,
- user_id=member_id,
- teams_ids_to_add_user_to=[group_id],
- teams_ids_to_remove_user_from=[],
- raise_on_error=True,
- ),
- )
- for member_id in members_to_add
- ),
- (
- (
- f"remove {member_id} from {group_id}",
- partial(
- patch_team_membership,
- user_id=member_id,
- teams_ids_to_add_user_to=[],
- teams_ids_to_remove_user_from=[group_id],
- raise_on_error=True,
- ),
- )
- for member_id in members_to_remove
- ),
- )
+
+async def _write_group_roster(group_id: str, plan: RosterPlan, prisma_client: PrismaClient) -> RosterSyncOutcome:
+ from litellm.proxy.proxy_server import litellm_proxy_admin_name, proxy_logging_obj, user_api_key_cache
+
+ return await sync_team_roster(
+ prisma_client=prisma_client,
+ team_id=group_id,
+ plan=plan,
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ litellm_proxy_admin_name=litellm_proxy_admin_name,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
)
- failures: Final = await _collect_roster_write_failures(writes)
- if failures:
- raise SCIMRosterSyncError(failures, attempted=len(writes))
+
+
+def _synced_roster_or_raise(group_id: str, outcome: RosterSyncOutcome) -> RosterSync:
+ match outcome:
+ case RosterSync():
+ return outcome
+ case TeamGone():
+ raise HTTPException(status_code=404, detail={"error": f"Group not found with ID: {group_id}"})
+ case MembersMissing(user_ids=user_ids):
+ raise HTTPException(
+ status_code=500,
+ detail={
+ "error": f"Users {', '.join(user_ids)} were not found while writing the roster of group "
+ f"'{group_id}'. Retry the request."
+ },
+ )
+ case _:
+ assert_never(outcome)
+
+
+async def _sync_group_roster(
+ group_id: str,
+ plan: RosterPlan,
+ created_via: str,
+ prisma_client: PrismaClient,
+ created_again: frozenset[str] = frozenset(),
+) -> RosterSync:
+ """Bring the group's team roster to the plan in one locked bulk transaction.
+
+ A member whose user row was deleted after the members were resolved is created
+ again and the write retried, as the per-member write did. Deletes that land
+ between retries name new members each time, so the write retries until it lands
+ or a member it already created again goes missing a second time. With
+ scim_upsert_user False it is refused like any member that is not a user yet.
+
+ Raises:
+ HTTPException: 400 when scim_upsert_user is False and a member's user row is gone,
+ 404 when the team is gone, 500 when a member created again is deleted again before
+ the write lands, so the identity provider retries the whole request.
+ """
+ outcome: Final = await _write_group_roster(group_id, plan, prisma_client)
+ if not isinstance(outcome, MembersMissing) or created_again.intersection(outcome.user_ids):
+ return _synced_roster_or_raise(group_id, outcome)
+ if not await _get_scim_upsert_user_setting():
+ raise _member_not_provisioned_error(outcome.user_ids[0])
+ verbose_proxy_logger.warning(
+ "SCIM: users %s were deleted while the roster of group %s was being written; creating them again",
+ sanitize_for_log(", ".join(outcome.user_ids)),
+ sanitize_for_log(group_id),
+ )
+ _ = await _create_group_member_users(outcome.user_ids, created_via, prisma_client)
+ return await _sync_group_roster(group_id, plan, created_via, prisma_client, created_again.union(outcome.user_ids))
+
+
+async def _fill_new_group(group_id: str, member_ids: frozenset[str], prisma_client: PrismaClient) -> RosterSync:
+ """Write a just-created group's roster, deleting the empty team when the write fails so the
+ identity provider's retry creates the group again instead of getting a 409, or a second team
+ of the same name when the POST carried neither ``id`` nor ``externalId``."""
+ try:
+ return await _sync_group_roster(
+ group_id, RosterDelta(add=member_ids, remove=frozenset()), "scim_group_membership", prisma_client
+ )
+ except Exception:
+ _ = await _table(TeamRepository(prisma_client)).delete(where={"team_id": group_id})
+ raise
@scim_router.patch(
@@ -3092,54 +3177,29 @@ async def patch_group(
patch_ops, existing_team, prisma_client
)
- snapshot_members: Final = set(await _get_team_member_user_ids_from_team(existing_team))
- intended_add: Final = final_members - snapshot_members
- intended_remove: Final = snapshot_members - final_members
-
- # Apply the metadata/displayName updates to the database
- updated_team = await _apply_group_patch_updates(group_id, update_data, prisma_client)
-
- refreshed_team: Final = await _table(TeamRepository(prisma_client)).find_unique(where={"team_id": group_id})
- refreshed_current: Final = (
- set(
- await _get_team_member_user_ids_from_team(LiteLLM_TeamTable.model_validate(refreshed_team.model_dump()))
+ snapshot_members: Final = frozenset(await _get_team_member_user_ids_from_team(existing_team))
+ plan: Final[RosterPlan] = (
+ RosterTarget(member_ids=frozenset(replace_target))
+ if replace_target is not None
+ else RosterDelta(
+ add=frozenset(final_members) - snapshot_members, remove=snapshot_members - frozenset(final_members)
)
- if refreshed_team
- else snapshot_members
)
- effective_final: Final = (
- replace_target if replace_target is not None else (refreshed_current | intended_add) - intended_remove
- )
+ # Apply the metadata/displayName updates to the database
+ await _apply_group_patch_updates(group_id, update_data, prisma_client, existing_team.team_alias)
- await _handle_group_membership_changes(group_id, refreshed_current, effective_final)
+ sync: Final = await _sync_group_roster(group_id, plan, "scim_group_patch", prisma_client)
# A rename can flip whether this group matches scim_admin_group by display
# name, so retained members must be re-resolved too, not just the ones whose
# membership changed.
new_alias: Final = update_data.get("team_alias", existing_team.team_alias)
alias_changed: Final = new_alias != existing_team.team_alias
- await _recompute_scim_member_roles(
- prisma_client,
- (refreshed_current | effective_final if alias_changed else refreshed_current ^ effective_final),
- )
-
- # Refresh team one more time to get final state after membership changes
- final_team: Final = await _table(TeamRepository(prisma_client)).find_unique(where={"team_id": group_id})
- if final_team:
- updated_team = final_team
-
- if updated_team is None:
- raise HTTPException(
- status_code=404,
- detail={"error": f"Group not found with ID: {group_id}"},
- )
+ await _recompute_scim_member_roles(prisma_client, _roles_to_recompute(sync, alias_changed))
# Convert to SCIM format and return
- scim_group: Final = await ScimTransformations.transform_litellm_team_to_scim_group(
- LiteLLM_TeamTable.model_validate(updated_team.model_dump())
- )
- return scim_group
+ return await ScimTransformations.transform_litellm_team_to_scim_group(sync.team)
except Exception as e:
raise handle_exception_on_proxy(e)
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index eef85301748..983b6731aea 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -177,6 +177,7 @@ from litellm.proxy.management_endpoints.team_admin_field_permissions import (
)
from litellm.proxy.management_helpers.access_group_team_sync import (
TEAM_ADVISORY_LOCK_SQL,
+ USER_ROWS_LOCK_SQL,
AccessGroupSyncTx,
invalidate_access_group_caches,
reconcile_team_access_group_membership,
@@ -203,6 +204,7 @@ from litellm.proxy.management_helpers.utils import (
)
from litellm.proxy.utils import PrismaClient, ProxyLogging, handle_exception_on_proxy
from litellm.repositories.budget_repository import BudgetRepository
+from litellm.repositories.chunked_in import find_many_in
from litellm.repositories.organization_repository import OrganizationRepository
from litellm.repositories.prisma_protocols import TableActions
from litellm.repositories.table_repositories import (
@@ -413,8 +415,16 @@ class _TeamDeleteTx(AccessGroupSyncTx, Protocol):
def litellm_teammembership(self) -> "TableActions[prisma_models.LiteLLM_TeamMembership]": ...
-_STRIP_DELETED_TEAM_FROM_USERS_SQL: Final = """
-UPDATE "LiteLLM_UserTable" SET teams = array_remove(teams, $1) WHERE $1 = ANY(teams)
+_STRIP_DELETED_TEAMS_FROM_USERS_SQL: Final = """
+UPDATE "LiteLLM_UserTable"
+SET teams = ARRAY(
+ SELECT kept.team_id FROM unnest(teams) WITH ORDINALITY AS kept(team_id, position)
+ WHERE kept.team_id <> ALL($1::text[])
+ ORDER BY kept.position
+)
+WHERE user_id IN (
+ SELECT user_id FROM "LiteLLM_UserTable" WHERE teams && $1::text[] ORDER BY user_id COLLATE "C" FOR UPDATE
+)
"""
_INCLUDE_MODEL_TABLE: Final = MappingProxyType({"litellm_model_table": True})
@@ -3131,6 +3141,17 @@ async def _update_team_members_list(
)
+def _user_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_UserTable]":
+ return tx.litellm_usertable # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+async def _lock_requested_member_rows(tx: "Prisma", members: Sequence[Member]) -> None:
+ emails_only: Final = tuple(m.user_email for m in members if m.user_id is None and m.user_email is not None)
+ matched: Final = await find_many_in(_user_tx_db(tx), "user_email", emails_only)
+ named: Final = (m.user_id for m in members if m.user_id is not None)
+ await tx.query_raw(USER_ROWS_LOCK_SQL, sorted({*named, *(row.user_id for row in matched)}))
+
+
async def _add_team_members_to_team(
data: TeamMemberAddRequest,
complete_team_data: LiteLLM_TeamTable,
@@ -3147,6 +3168,9 @@ async def _add_team_members_to_team(
lock around its own sweep-and-delete, so the two can never interleave; whichever
acquires the lock first runs to completion before the other's re-read can proceed.
+ Every existing user row the request names is locked through ``USER_ROWS_LOCK_SQL`` before
+ the first member write, so a list of members never waits on a SCIM group push in a cycle.
+
The user and membership writes run on this transaction too, not on a second
connection from the pool: a lock waiter that needs a connection it hasn't got yet is
a waiter that can deadlock the pool, since enough concurrent adds for one team would
@@ -3160,6 +3184,7 @@ async def _add_team_members_to_team(
if locked_members is None:
raise HTTPException(status_code=404, detail=gone_detail)
complete_team_data.members_with_roles = locked_members
+ await _lock_requested_member_rows(tx, (data.member,) if isinstance(data.member, Member) else data.member)
updated_users, updated_team_memberships = await _process_team_members(
data=data,
@@ -4687,11 +4712,12 @@ async def _sweep_deleted_team_references(team_ids: Sequence[str], prisma_client:
rows that already drifted, which is the state this was reported against, so the sweep still has
to run on delete.
- `array_remove` rather than read-filter-write: rewriting the whole array from a snapshot read
- outside a transaction drops any team a concurrent `/team/member_add` appended in between.
+ One statement filters the array in place rather than read-filter-write: rewriting the whole
+ array from a snapshot read outside a transaction drops any team a concurrent `/team/member_add`
+ appended in between. It locks the user rows in the order `USER_ROWS_LOCK_SQL` takes them, so it
+ never waits on a SCIM group push in a cycle.
"""
- for team_id in team_ids:
- _ = await prisma_client.db.execute_raw(_STRIP_DELETED_TEAM_FROM_USERS_SQL, team_id)
+ _ = await prisma_client.db.execute_raw(_STRIP_DELETED_TEAMS_FROM_USERS_SQL, list(team_ids))
_ = await _team_membership_db(prisma_client).delete_many(where=_TeamIdInFilter(team_id={"in": tuple(team_ids)}))
@@ -4699,8 +4725,7 @@ async def _sweep_deleted_team_references(team_ids: Sequence[str], prisma_client:
async def _sweep_deleted_team_references_tx(team_ids: Sequence[str], tx: _TeamDeleteTx) -> None:
"""Same sweep as `_sweep_deleted_team_references`, run on the transaction that holds
every id's advisory lock and deletes the team rows, so it commits or rolls back with them."""
- for team_id in team_ids:
- _ = await tx.execute_raw(_STRIP_DELETED_TEAM_FROM_USERS_SQL, team_id)
+ _ = await tx.execute_raw(_STRIP_DELETED_TEAMS_FROM_USERS_SQL, list(team_ids))
membership_filter: Final[_TeamIdInFilter] = {"team_id": {"in": tuple(team_ids)}}
_ = await tx.litellm_teammembership.delete_many(where=membership_filter)
diff --git a/litellm/proxy/management_helpers/access_group_team_sync.py b/litellm/proxy/management_helpers/access_group_team_sync.py
index 1205414b4fb..f79d08ed136 100644
--- a/litellm/proxy/management_helpers/access_group_team_sync.py
+++ b/litellm/proxy/management_helpers/access_group_team_sync.py
@@ -34,6 +34,17 @@ from litellm.types.llms.base import LiteLLMBaseModel
# other and against this mirror, rather than defining a second, divergent lock on the same key.
TEAM_ADVISORY_LOCK_SQL: Final = "SELECT pg_advisory_xact_lock(hashtext($1)) IS NULL AS locked"
+# Every transaction that writes several user rows locks them through this first, so all of
+# them take user row locks in one shared order and none can wait on another in a cycle.
+USER_ROWS_LOCK_SQL: Final = (
+ 'SELECT user_id FROM "LiteLLM_UserTable" WHERE user_id = ANY($1::text[]) ORDER BY user_id COLLATE "C" FOR UPDATE'
+)
+
+DETACH_TEAM_FROM_USERS_SQL: Final = (
+ "UPDATE \"LiteLLM_UserTable\" SET teams = array_remove(teams, $1), updated_at = (NOW() AT TIME ZONE 'UTC')"
+ " WHERE user_id = ANY($2::text[])"
+)
+
_READ_TEAM_SQL: Final = 'SELECT access_group_ids FROM "LiteLLM_TeamTable" WHERE team_id = $1'
# The groups the team is on either side of the reconcile, so the cache step is driven by
diff --git a/litellm/proxy/management_helpers/bulk_user_deletion.py b/litellm/proxy/management_helpers/bulk_user_deletion.py
index c92ebce8531..04dd0b3f57f 100644
--- a/litellm/proxy/management_helpers/bulk_user_deletion.py
+++ b/litellm/proxy/management_helpers/bulk_user_deletion.py
@@ -1,5 +1,6 @@
"""Batched deletes behind `POST /management/v1/users/bulk_delete` and
-`POST /management/v1/teams/{team_id}/members/bulk_delete`.
+`POST /management/v1/teams/{team_id}/members/bulk_delete`, and the locked user row delete that
+`/user/delete` and SCIM `DELETE /Users/{id}` finish with.
Each team a batch touches is rewritten exactly once, under the same advisory lock
`/team/member_delete` takes and from a roster re-read under that lock, so a concurrent
@@ -14,7 +15,7 @@ from collections.abc import Awaitable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import timedelta
from types import MappingProxyType
-from typing import TYPE_CHECKING, Final
+from typing import TYPE_CHECKING, Final, Literal
from fastapi import HTTPException
from typing_extensions import ReadOnly, TypedDict
@@ -40,7 +41,11 @@ from litellm.proxy.management_endpoints.key_management_endpoints import ( # noq
_persist_deleted_verification_tokens, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
persist_deleted_verification_tokens, # pyright: ignore[reportPrivateUsage] # same audit path /key/delete uses
)
-from litellm.proxy.management_helpers.access_group_team_sync import TEAM_ADVISORY_LOCK_SQL
+from litellm.proxy.management_helpers.access_group_team_sync import (
+ DETACH_TEAM_FROM_USERS_SQL,
+ TEAM_ADVISORY_LOCK_SQL,
+ USER_ROWS_LOCK_SQL,
+)
from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.repositories.table_repositories import (
OrganizationMembershipRepository,
@@ -66,6 +71,9 @@ if TYPE_CHECKING:
_AUDIT_LOG_CONCURRENCY: Final = 10
_BATCH_TX_TIMEOUT: Final = timedelta(seconds=60)
+_USER_DELETE_ATTEMPTS: Final = 3
+
+_UserKeys = Literal["delete", "keep"]
class _OrgAdminFilter(TypedDict):
@@ -77,14 +85,6 @@ class _RosterData(TypedDict):
members_with_roles: ReadOnly[str]
-class _TeamsSet(TypedDict):
- set: ReadOnly[tuple[str, ...]]
-
-
-class _TeamsData(TypedDict):
- teams: ReadOnly[_TeamsSet]
-
-
@dataclass(frozen=True, slots=True)
class _TeamRemoval:
"""One team's rewrite. `removed` holds the user ids taken off the team (roster, `teams` array, or both);
@@ -106,18 +106,33 @@ class _UserBatchDeletion:
removals: Mapping[str, _TeamRemoval]
deleted_keys: tuple["prisma_models.LiteLLM_VerificationToken", ...]
jwt_mapping_cache_keys: tuple[str, ...]
+ deleted_users: int
@property
def deleted_key_tokens(self) -> tuple[str, ...]:
return tuple(k.token for k in self.deleted_keys)
+@dataclass(frozen=True, slots=True)
+class _TeamsChanged:
+ teams_of: Mapping[str, frozenset[str]]
+
+
@dataclass(frozen=True, slots=True)
class _DeletedKeys:
keys: tuple["prisma_models.LiteLLM_VerificationToken", ...]
jwt_mapping_cache_keys: tuple[str, ...]
+_NO_DELETED_KEYS: Final = _DeletedKeys(keys=(), jwt_mapping_cache_keys=())
+
+
+@dataclass(frozen=True, slots=True)
+class _DeletedUserRows:
+ keys: _DeletedKeys
+ users: int
+
+
def _team_not_found(team_id: str) -> ManagementProblem:
return ManagementProblem(
ProblemDetail(
@@ -221,8 +236,10 @@ async def _remove_members_from_team(
prisma_client: PrismaClient,
tx: "Prisma",
team_id: str,
+ team_alias: str | None,
members: Sequence[MemberDeleteRequest],
user_api_key_dict: UserAPIKeyAuth,
+ locked_user_ids: frozenset[str],
) -> _TeamRemoval:
await tx.query_raw(TEAM_ADVISORY_LOCK_SQL, team_id)
roster: Final = await TeamRepository(prisma_client).get_members_with_roles_locked(tx, team_id)
@@ -263,9 +280,11 @@ async def _remove_members_from_team(
"members_with_roles": json.dumps(tuple(m.model_dump() for m in kept_members))
}
await _team_tx_db(tx).update(where=_eq_filter("team_id", team_id), data=roster_data)
- for row in stale_rows:
- teams_data: _TeamsData = {"teams": {"set": tuple(t for t in row.teams if t != team_id)}}
- await _user_tx_db(tx).update(where=_eq_filter("user_id", row.user_id), data=teams_data)
+ stale_ids: Final = frozenset(u.user_id for u in stale_rows)
+ if stale_ids - locked_user_ids:
+ _ = await tx.query_raw(USER_ROWS_LOCK_SQL, sorted(stale_ids - locked_user_ids))
+ if stale_ids:
+ _ = await tx.execute_raw(DETACH_TEAM_FROM_USERS_SQL, team_id, sorted(stale_ids))
await _membership_tx_db(tx).delete_many(where=_team_users_filter(team_id, cleanup_ids))
if keys:
await persist_deleted_verification_tokens(
@@ -280,6 +299,7 @@ async def _remove_members_from_team(
return _TeamRemoval(
team=LiteLLM_TeamTable(
team_id=team_id,
+ team_alias=team_alias,
members_with_roles=kept_members, # pyright: ignore[reportArgumentType] # pydantic coerces the tuple into the list field
),
removed=cleanup_ids,
@@ -333,7 +353,9 @@ async def bulk_remove_team_members(
kept_indexes: Final = tuple(i for i in range(len(data.members)) if i not in duplicates)
members: Final = tuple(data.members[i] for i in kept_indexes)
async with prisma_client.tx(timeout=_BATCH_TX_TIMEOUT) as tx:
- removal: Final = await _remove_members_from_team(prisma_client, tx, team_id, members, user_api_key_dict)
+ removal: Final = await _remove_members_from_team(
+ prisma_client, tx, team_id, team.team_alias, members, user_api_key_dict, frozenset()
+ )
if removal.deleted_keys:
KeyManagementEventHooks.create_key_deleted_audit_logs(
keys_being_deleted=removal.deleted_keys,
@@ -386,7 +408,7 @@ def _scope_error(user_id: str, target_org_ids: frozenset[str], caller_admin_org_
)
-async def _delete_user_rows(
+async def _delete_user_keys(
prisma_client: PrismaClient,
tx: "Prisma",
user_ids: frozenset[str],
@@ -407,6 +429,22 @@ async def _delete_user_rows(
tx=tx,
)
await _token_tx_db(tx).delete_many(where=_in_filter("user_id", user_ids))
+ return _DeletedKeys(keys=tuple(keys), jwt_mapping_cache_keys=jwt_mapping_cache_keys)
+
+
+async def _delete_user_rows(
+ prisma_client: PrismaClient,
+ tx: "Prisma",
+ user_ids: frozenset[str],
+ user_keys: _UserKeys,
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_changed_by: str | None,
+) -> _DeletedUserRows:
+ deleted_keys: Final = (
+ await _delete_user_keys(prisma_client, tx, user_ids, user_api_key_dict, litellm_changed_by)
+ if user_keys == "delete"
+ else _NO_DELETED_KEYS
+ )
await _invitation_tx_db(tx).delete_many(
where=_any_filter(
_in_filter("user_id", user_ids),
@@ -416,69 +454,124 @@ async def _delete_user_rows(
)
await _org_membership_tx_db(tx).delete_many(where=_in_filter("user_id", user_ids))
await _membership_tx_db(tx).delete_many(where=_in_filter("user_id", user_ids))
- await _user_tx_db(tx).delete_many(where=_in_filter("user_id", user_ids))
- return _DeletedKeys(keys=tuple(keys), jwt_mapping_cache_keys=jwt_mapping_cache_keys)
+ deleted_users: Final = await _user_tx_db(tx).delete_many(where=_in_filter("user_id", user_ids))
+ return _DeletedUserRows(keys=deleted_keys, users=deleted_users)
+
+
+def _teams_of(
+ users: Iterable["prisma_models.LiteLLM_UserTable"],
+ memberships: Sequence["prisma_models.LiteLLM_TeamMembership"],
+) -> Mapping[str, frozenset[str]]:
+ return MappingProxyType(
+ {
+ u.user_id: frozenset(u.teams) | frozenset(m.team_id for m in memberships if m.user_id == u.user_id)
+ for u in users
+ }
+ )
+
+
+def _all_teams(teams_of: Mapping[str, frozenset[str]]) -> frozenset[str]:
+ return frozenset(t for teams in teams_of.values() for t in teams)
async def _delete_users_tx(
prisma_client: PrismaClient,
users: Sequence["prisma_models.LiteLLM_UserTable"],
teams_of: Mapping[str, frozenset[str]],
+ user_keys: _UserKeys,
user_api_key_dict: UserAPIKeyAuth,
litellm_changed_by: str | None,
-) -> _UserBatchDeletion:
+) -> _UserBatchDeletion | _TeamsChanged:
"""Rewrites every team the users belong to and deletes their rows in one transaction, so a
failure anywhere rolls back the whole batch. Teams a user still names but which no longer exist
- are skipped; the user row goes away regardless."""
+ are skipped; the user row goes away regardless. Every team lock is taken before the first user
+ row write: a SCIM group push holds its team's lock while it waits on its members' rows, so
+ taking one team's lock after writing a member it shares would deadlock against that push. The
+ user rows are then locked through ``USER_ROWS_LOCK_SQL``, before the per-team rewrites touch them.
+ A push that committed while this waited on those rows can have added a user to a team ``teams_of``
+ missed, so the teams are read again under the row locks and an unlocked one returns them for a retry."""
+ user_ids: Final = frozenset(u.user_id for u in users)
async with prisma_client.tx(timeout=_BATCH_TX_TIMEOUT) as tx:
- team_rows: Final = await _team_tx_db(tx).find_many(
- where=_in_filter("team_id", frozenset(t for teams in teams_of.values() for t in teams))
+ existing_team_ids: Final = frozenset(
+ t.team_id for t in await _team_tx_db(tx).find_many(where=_in_filter("team_id", _all_teams(teams_of)))
)
+ for team_id in sorted(existing_team_ids):
+ _ = await tx.query_raw(TEAM_ADVISORY_LOCK_SQL, team_id)
+ _ = await tx.query_raw(USER_ROWS_LOCK_SQL, sorted(user_ids))
+ team_rows: Final = await _team_tx_db(tx).find_many(where=_in_filter("team_id", existing_team_ids))
team_ids: Final = tuple(sorted(t.team_id for t in team_rows))
+ alias_of: Final = MappingProxyType({t.team_id: t.team_alias for t in team_rows})
+ current_teams_of: Final = _teams_of(
+ await _user_tx_db(tx).find_many(where=_in_filter("user_id", user_ids)),
+ await _membership_tx_db(tx).find_many(where=_in_filter("user_id", user_ids)),
+ )
+ if not _all_teams(current_teams_of) <= _all_teams(teams_of):
+ return _TeamsChanged(teams_of=current_teams_of)
removals: Final = MappingProxyType(
{
tid: await _remove_members_from_team(
prisma_client,
tx,
tid,
+ alias_of[tid],
tuple(
MemberDeleteRequest(user_id=u.user_id, user_email=u.user_email)
for u in users
- if tid in teams_of[u.user_id]
+ if tid in teams_of[u.user_id] | current_teams_of.get(u.user_id, frozenset())
),
user_api_key_dict,
+ user_ids,
)
for tid in team_ids
}
)
- deleted_keys: Final = await _delete_user_rows(
- prisma_client, tx, frozenset(u.user_id for u in users), user_api_key_dict, litellm_changed_by
+ deleted_rows: Final = await _delete_user_rows(
+ prisma_client, tx, user_ids, user_keys, user_api_key_dict, litellm_changed_by
)
return _UserBatchDeletion(
removals=removals,
- deleted_keys=deleted_keys.keys + tuple(k for r in removals.values() for k in r.deleted_keys),
- jwt_mapping_cache_keys=deleted_keys.jwt_mapping_cache_keys
+ deleted_keys=deleted_rows.keys.keys + tuple(k for r in removals.values() for k in r.deleted_keys),
+ jwt_mapping_cache_keys=deleted_rows.keys.jwt_mapping_cache_keys
+ tuple(k for r in removals.values() for k in r.jwt_mapping_cache_keys),
+ deleted_users=deleted_rows.users,
)
-async def _delete_users(
+async def _delete_users_on_current_teams(
prisma_client: PrismaClient,
users: Sequence["prisma_models.LiteLLM_UserTable"],
teams_of: Mapping[str, frozenset[str]],
+ user_keys: _UserKeys,
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_changed_by: str | None,
+ attempts_left: int = _USER_DELETE_ATTEMPTS,
+) -> _UserBatchDeletion | str:
+ outcome: Final = await _delete_users_tx(
+ prisma_client, users, teams_of, user_keys, user_api_key_dict, litellm_changed_by
+ )
+ if isinstance(outcome, _UserBatchDeletion):
+ return outcome
+ if attempts_left <= 1:
+ return "the users' teams kept changing while they were being deleted, try again"
+ return await _delete_users_on_current_teams(
+ prisma_client,
+ users,
+ MappingProxyType({uid: teams_of[uid] | outcome.teams_of.get(uid, frozenset()) for uid in teams_of}),
+ user_keys,
+ user_api_key_dict,
+ litellm_changed_by,
+ attempts_left - 1,
+ )
+
+
+async def _after_users_deleted(
+ deletion: _UserBatchDeletion,
+ user_ids: frozenset[str],
user_api_key_dict: UserAPIKeyAuth,
user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging | None,
- litellm_proxy_admin_name: str | None,
litellm_changed_by: str | None,
-) -> _UserBatchDeletion | str:
- """Returns the error message when the transaction rolled back, in which case no row was touched."""
- user_ids: Final = frozenset(u.user_id for u in users)
- try:
- deletion: Final = await _delete_users_tx(prisma_client, users, teams_of, user_api_key_dict, litellm_changed_by)
- except Exception as e: # noqa: BLE001 # the rolled-back batch is reported per row, not as a request failure
- verbose_proxy_logger.error("users/bulk_delete: failed to delete users %s: %s", sorted(user_ids), e)
- return _error_message(e)
+) -> None:
if deletion.deleted_keys:
KeyManagementEventHooks.create_key_deleted_audit_logs(
keys_being_deleted=deletion.deleted_keys,
@@ -494,6 +587,62 @@ async def _delete_users(
await evict_and_broadcast(cache_keys=sorted(user_ids), user_api_key_cache=user_api_key_cache)
for removal in deletion.removals.values():
_emit_team_members_metric(removal.team)
+
+
+async def delete_users_from_current_teams(
+ prisma_client: PrismaClient,
+ user_ids: Sequence[str],
+ user_api_key_dict: UserAPIKeyAuth,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+ litellm_changed_by: str | None,
+) -> int | str:
+ """Deletes the users and the rows referencing them after taking them off every team they are on once
+ their rows are locked, so a group push that added them while the caller cleaned up cannot leave them
+ listed. Their keys are left for the caller. Returns how many users were deleted, or why none were."""
+ unique_ids: Final = frozenset(user_ids)
+ users: Final = await UserRepository(prisma_client).table.find_many(where=_in_filter("user_id", unique_ids))
+ if not users:
+ return 0
+ memberships: Final = await TeamMembershipRepository(prisma_client).table.find_many(
+ where=_in_filter("user_id", unique_ids)
+ )
+ deletion: Final = await _delete_users_on_current_teams(
+ prisma_client, users, _teams_of(users, memberships), "keep", user_api_key_dict, litellm_changed_by
+ )
+ if isinstance(deletion, str):
+ return deletion
+ await _after_users_deleted(
+ deletion, unique_ids, user_api_key_dict, user_api_key_cache, proxy_logging_obj, litellm_changed_by
+ )
+ return deletion.deleted_users
+
+
+async def _delete_users(
+ prisma_client: PrismaClient,
+ users: Sequence["prisma_models.LiteLLM_UserTable"],
+ teams_of: Mapping[str, frozenset[str]],
+ user_api_key_dict: UserAPIKeyAuth,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+ litellm_proxy_admin_name: str | None,
+ litellm_changed_by: str | None,
+) -> _UserBatchDeletion | str:
+ """Returns the error message when the transaction rolled back, in which case no row was touched."""
+ user_ids: Final = frozenset(u.user_id for u in users)
+ try:
+ deletion: Final = await _delete_users_on_current_teams(
+ prisma_client, users, teams_of, "delete", user_api_key_dict, litellm_changed_by
+ )
+ except Exception as e: # noqa: BLE001 # the rolled-back batch is reported per row, not as a request failure
+ verbose_proxy_logger.error("users/bulk_delete: failed to delete users %s: %s", sorted(user_ids), e)
+ return _error_message(e)
+ if isinstance(deletion, str):
+ verbose_proxy_logger.error("users/bulk_delete: failed to delete users %s: %s", sorted(user_ids), deletion)
+ return deletion
+ await _after_users_deleted(
+ deletion, user_ids, user_api_key_dict, user_api_key_cache, proxy_logging_obj, litellm_changed_by
+ )
audit_outcomes: Final = await _bounded(
UserManagementEventHooks.create_internal_user_audit_log(
user_id=u.user_id,
@@ -553,12 +702,7 @@ async def bulk_delete_users(
memberships: Final = await TeamMembershipRepository(prisma_client).table.find_many(
where=_in_filter("user_id", candidate_ids)
)
- teams_of: Final = MappingProxyType(
- {
- u.user_id: frozenset(u.teams) | frozenset(m.team_id for m in memberships if m.user_id == u.user_id)
- for u in candidates
- }
- )
+ teams_of: Final = _teams_of(candidates, memberships)
deletion: Final = (
await _delete_users(
prisma_client,
@@ -571,7 +715,9 @@ async def bulk_delete_users(
litellm_changed_by,
)
if candidates
- else _UserBatchDeletion(removals=MappingProxyType({}), deleted_keys=(), jwt_mapping_cache_keys=())
+ else _UserBatchDeletion(
+ removals=MappingProxyType({}), deleted_keys=(), jwt_mapping_cache_keys=(), deleted_users=0
+ )
)
def result(index: int, user_id: str) -> UserDeleteResult:
diff --git a/litellm/proxy/management_helpers/team_roster_sync.py b/litellm/proxy/management_helpers/team_roster_sync.py
new file mode 100644
index 00000000000..4b29d4676f8
--- /dev/null
+++ b/litellm/proxy/management_helpers/team_roster_sync.py
@@ -0,0 +1,369 @@
+import asyncio
+import json
+from collections.abc import Iterator, Mapping, Sequence
+from dataclasses import dataclass
+from datetime import timedelta
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Final
+
+from pydantic import TypeAdapter
+from typing_extensions import ReadOnly, TypedDict, assert_never
+
+from litellm._uuid import uuid
+from litellm.proxy._types import LiteLLM_TeamTable, Member, UserAPIKeyAuth
+from litellm.proxy.auth.auth_checks import (
+ await_inflight_team_membership_load,
+ delete_cache_team_object,
+ get_jwt_key_mapping_cache_keys_for_tokens,
+)
+from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import (
+ broadcast_evictions,
+ evict_local,
+ evict_shared,
+)
+from litellm.proxy.common_utils.user_api_key_cache import (
+ UserApiKeyCache,
+ team_membership_auth_cache_key,
+ team_membership_reservation_cache_key,
+)
+from litellm.proxy.hooks.key_management_event_hooks import KeyManagementEventHooks
+from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _persist_deleted_verification_tokens, # pyright: ignore[reportPrivateUsage] # same audit path /key/delete uses
+)
+from litellm.proxy.management_endpoints.team_endpoints import (
+ _emit_team_members_metric, # pyright: ignore[reportPrivateUsage] # same gauge /team/member_add moves
+ _schedule_team_membership_audit_log, # pyright: ignore[reportPrivateUsage] # same audit row /team/member_add writes
+)
+from litellm.proxy.management_helpers.access_group_team_sync import (
+ DETACH_TEAM_FROM_USERS_SQL,
+ TEAM_ADVISORY_LOCK_SQL,
+ USER_ROWS_LOCK_SQL,
+)
+from litellm.proxy.utils import PrismaClient, ProxyLogging
+from litellm.repositories.chunked_in import delete_many_in, find_many_in, update_many_in
+
+if TYPE_CHECKING:
+ from prisma import Prisma
+ from prisma import models as prisma_models
+
+ from litellm.repositories.prisma_protocols import TableActions
+
+ROSTER_TX_TIMEOUT: Final = timedelta(seconds=60)
+_JSON_OBJECT: Final = TypeAdapter(dict[str, object])
+
+
+@dataclass(frozen=True, slots=True)
+class RosterTarget:
+ member_ids: frozenset[str]
+
+
+@dataclass(frozen=True, slots=True)
+class RosterDelta:
+ add: frozenset[str]
+ remove: frozenset[str]
+
+
+RosterPlan = RosterTarget | RosterDelta
+
+
+@dataclass(frozen=True, slots=True)
+class RosterSync:
+ team: LiteLLM_TeamTable
+ added: frozenset[str]
+ removed: frozenset[str]
+
+
+@dataclass(frozen=True, slots=True)
+class TeamGone:
+ team_id: str
+
+
+@dataclass(frozen=True, slots=True)
+class MembersMissing:
+ team_id: str
+ user_ids: tuple[str, ...]
+
+
+RosterSyncOutcome = RosterSync | TeamGone | MembersMissing
+
+
+class _TeamDeletedBeforeRosterWrite(Exception):
+ pass
+
+
+class _MembershipData(TypedDict):
+ team_id: ReadOnly[str]
+ user_id: ReadOnly[str]
+ budget_id: ReadOnly[str | None]
+
+
+class _BudgetData(TypedDict):
+ budget_id: ReadOnly[str]
+ allowed_models: ReadOnly[tuple[str, ...]]
+ created_by: ReadOnly[str]
+ updated_by: ReadOnly[str]
+
+
+class _RosterData(TypedDict):
+ members_with_roles: ReadOnly[str]
+
+
+@dataclass(frozen=True, slots=True)
+class _Removal:
+ deleted_keys: tuple["prisma_models.LiteLLM_VerificationToken", ...]
+ jwt_mapping_cache_keys: tuple[str, ...]
+
+
+def team_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_TeamTable]":
+ return tx.litellm_teamtable # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+def user_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_UserTable]":
+ return tx.litellm_usertable # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+def _membership_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_TeamMembership]":
+ return tx.litellm_teammembership # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+def _budget_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_BudgetTable]":
+ return tx.litellm_budgettable # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+def _token_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_VerificationToken]":
+ return tx.litellm_verificationtoken # pyright: ignore[reportReturnType] # TableActions widens the generated inputs to Mapping, as the repositories do
+
+
+def _changes_nothing(plan: RosterPlan) -> bool:
+ match plan:
+ case RosterDelta(add=add, remove=remove):
+ return not add and not remove
+ case RosterTarget():
+ return False
+ case _:
+ assert_never(plan)
+
+
+async def _unchanged_roster(prisma_client: PrismaClient, team_id: str) -> RosterSync | TeamGone:
+ team_row: Final = await prisma_client.writer_db.litellm_teamtable.find_unique(where={"team_id": team_id})
+ if team_row is None:
+ return TeamGone(team_id=team_id)
+ team: Final = LiteLLM_TeamTable.model_validate(team_row.model_dump())
+ return RosterSync(team=team, added=frozenset(), removed=frozenset())
+
+
+def _planned_changes(plan: RosterPlan, roster_ids: frozenset[str]) -> tuple[frozenset[str], frozenset[str]]:
+ match plan:
+ case RosterTarget(member_ids=target):
+ return target - roster_ids, roster_ids - target
+ case RosterDelta(add=add, remove=remove):
+ return add - roster_ids, remove & roster_ids
+ case _:
+ assert_never(plan)
+
+
+def _default_member_budget_id(team: LiteLLM_TeamTable) -> str | None:
+ metadata: Final = (
+ _JSON_OBJECT.validate_python(
+ team.metadata # pyright: ignore[reportUnknownMemberType] # LiteLLM_TeamTable.metadata is a bare dict; validated by the adapter
+ )
+ if team.metadata # pyright: ignore[reportUnknownMemberType] # same bare dict
+ else None
+ )
+ budget_id: Final = metadata.get("team_member_budget_id") if metadata is not None else None
+ return budget_id if isinstance(budget_id, str) else None
+
+
+async def _member_budget_ids(
+ tx: "Prisma",
+ team: LiteLLM_TeamTable,
+ user_ids: Sequence[str],
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_proxy_admin_name: str,
+) -> Mapping[str, str | None]:
+ allowed_models: Final = tuple(team.default_team_member_models or ())
+ if allowed_models:
+ author: Final = user_api_key_dict.user_id or litellm_proxy_admin_name
+ budgets: Final = tuple(
+ _BudgetData(
+ budget_id=str(uuid.uuid4()), allowed_models=allowed_models, created_by=author, updated_by=author
+ )
+ for _ in user_ids
+ )
+ await _budget_tx_db(tx).create_many(data=budgets)
+ return MappingProxyType(dict(zip(user_ids, (budget["budget_id"] for budget in budgets), strict=True)))
+ default_budget_id: Final = _default_member_budget_id(team)
+ if default_budget_id is None:
+ return MappingProxyType({})
+ default_budget: Final = await _budget_tx_db(tx).find_unique(where={"budget_id": default_budget_id})
+ return MappingProxyType(dict.fromkeys(user_ids, default_budget_id if default_budget is not None else None))
+
+
+async def _add_members(
+ tx: "Prisma",
+ team: LiteLLM_TeamTable,
+ user_ids: Sequence[str],
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_proxy_admin_name: str,
+) -> tuple[Member, ...] | MembersMissing:
+ if not user_ids:
+ return ()
+ rows: Final = await find_many_in(user_tx_db(tx), "user_id", user_ids)
+ email_of: Final = MappingProxyType({row.user_id: row.user_email for row in rows})
+ missing: Final = tuple(user_id for user_id in user_ids if user_id not in email_of)
+ if missing:
+ return MembersMissing(team_id=team.team_id, user_ids=missing)
+ budget_ids: Final = await _member_budget_ids(tx, team, user_ids, user_api_key_dict, litellm_proxy_admin_name)
+ await _membership_tx_db(tx).create_many(
+ data=tuple(
+ _MembershipData(team_id=team.team_id, user_id=user_id, budget_id=budget_ids.get(user_id))
+ for user_id in user_ids
+ ),
+ skip_duplicates=True,
+ )
+ await update_many_in(
+ user_tx_db(tx),
+ "user_id",
+ user_ids,
+ data={"teams": {"push": [team.team_id]}},
+ atomicity="caller_transaction",
+ where={"NOT": {"teams": {"has": team.team_id}}},
+ )
+ return tuple(Member(user_id=user_id, user_email=email_of[user_id], role="user") for user_id in user_ids)
+
+
+async def _remove_members(
+ tx: "Prisma",
+ prisma_client: PrismaClient,
+ team_id: str,
+ user_ids: Sequence[str],
+ user_api_key_dict: UserAPIKeyAuth,
+) -> _Removal:
+ if not user_ids:
+ return _Removal(deleted_keys=(), jwt_mapping_cache_keys=())
+ keys: Final = await find_many_in(_token_tx_db(tx), "user_id", user_ids, where={"team_id": team_id})
+ jwt_mapping_cache_keys: Final = await get_jwt_key_mapping_cache_keys_for_tokens(
+ hashed_tokens=tuple(key.token for key in keys), prisma_client=prisma_client
+ )
+ await tx.execute_raw(DETACH_TEAM_FROM_USERS_SQL, team_id, list(user_ids))
+ await delete_many_in(
+ _membership_tx_db(tx), "user_id", user_ids, atomicity="caller_transaction", where={"team_id": team_id}
+ )
+ if keys:
+ await _persist_deleted_verification_tokens(
+ keys=keys, # pyright: ignore[reportArgumentType] # generated row model carries the same columns as LiteLLM_VerificationToken
+ prisma_client=prisma_client,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ tx=tx,
+ )
+ await delete_many_in(
+ _token_tx_db(tx), "user_id", user_ids, atomicity="caller_transaction", where={"team_id": team_id}
+ )
+ return _Removal(deleted_keys=keys, jwt_mapping_cache_keys=jwt_mapping_cache_keys)
+
+
+async def _settle_caches(
+ team: LiteLLM_TeamTable,
+ changed_user_ids: Sequence[str],
+ removal: _Removal,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+) -> None:
+ _ = await asyncio.gather(
+ *(await_inflight_team_membership_load(user_id=user_id, team_id=team.team_id) for user_id in changed_user_ids)
+ )
+ deleted_tokens: Final = tuple(key.token for key in removal.deleted_keys)
+ evicted: Final = (
+ *deleted_tokens,
+ *removal.jwt_mapping_cache_keys,
+ *_member_cache_keys(team.team_id, changed_user_ids),
+ )
+ evict_local(cache_keys=evicted, user_api_key_cache=user_api_key_cache)
+ await evict_shared(cache_keys=evicted, cache=user_api_key_cache)
+ if proxy_logging_obj is not None:
+ await evict_shared(cache_keys=deleted_tokens, cache=proxy_logging_obj.internal_usage_cache.dual_cache)
+ await delete_cache_team_object(
+ team_id=team.team_id,
+ team_alias=team.team_alias,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ await broadcast_evictions(cache_keys=evicted)
+
+
+def _member_cache_keys(team_id: str, user_ids: Sequence[str]) -> Iterator[str]:
+ for user_id in user_ids:
+ yield user_id
+ yield team_membership_auth_cache_key(team_id=team_id, user_id=user_id)
+ yield team_membership_reservation_cache_key(user_id=user_id, team_id=team_id)
+
+
+async def sync_team_roster(
+ prisma_client: PrismaClient,
+ team_id: str,
+ plan: RosterPlan,
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_proxy_admin_name: str,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+) -> RosterSyncOutcome:
+ """Reconcile the team's roster under its advisory lock in one transaction.
+
+ The roster, every member's ``teams`` array, the membership rows and the removed
+ members' team keys change together or not at all, so a failure leaves nothing
+ half-applied for the caller's retry to trip over. ``TeamGone`` means the team row
+ went away before the lock was taken or before the roster write, and ``MembersMissing``
+ means a user the plan adds has no row. Neither writes anything. A delta naming nobody
+ changes nothing, so it reads the team from the writer without the lock or a transaction,
+ and a plan already matching the roster writes nothing and leaves every cache entry in
+ place. Every user row the plan touches is locked through ``USER_ROWS_LOCK_SQL`` before
+ the first write.
+ """
+ if _changes_nothing(plan):
+ return await _unchanged_roster(prisma_client, team_id)
+ try:
+ async with prisma_client.tx(timeout=ROSTER_TX_TIMEOUT) as tx:
+ await tx.query_raw(TEAM_ADVISORY_LOCK_SQL, team_id)
+ team_row: Final = await team_tx_db(tx).find_unique(where={"team_id": team_id})
+ if team_row is None:
+ return TeamGone(team_id=team_id)
+ team: Final = LiteLLM_TeamTable.model_validate(team_row.model_dump())
+ roster: Final = tuple(team.members_with_roles)
+ roster_ids: Final = frozenset(member.user_id for member in roster if member.user_id is not None)
+ to_add, to_remove = _planned_changes(plan, roster_ids)
+ if not to_add and not to_remove:
+ return RosterSync(team=team, added=frozenset(), removed=frozenset())
+ await tx.query_raw(USER_ROWS_LOCK_SQL, sorted(to_add | to_remove))
+ added: Final = await _add_members(tx, team, sorted(to_add), user_api_key_dict, litellm_proxy_admin_name)
+ if isinstance(added, MembersMissing):
+ return added
+ removal: Final = await _remove_members(tx, prisma_client, team_id, sorted(to_remove), user_api_key_dict)
+ after: Final = (*(member for member in roster if member.user_id not in to_remove), *added)
+ written: Final = await team_tx_db(tx).update(
+ where={"team_id": team_id},
+ data=_RosterData(members_with_roles=json.dumps(tuple(member.model_dump() for member in after))),
+ )
+ if written is None:
+ raise _TeamDeletedBeforeRosterWrite
+ except _TeamDeletedBeforeRosterWrite:
+ return TeamGone(team_id=team_id)
+
+ synced: Final = LiteLLM_TeamTable.model_validate(written.model_dump())
+ if removal.deleted_keys:
+ KeyManagementEventHooks.create_key_deleted_audit_logs(
+ keys_being_deleted=removal.deleted_keys,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+ await _settle_caches(synced, sorted(to_add | to_remove), removal, user_api_key_cache, proxy_logging_obj)
+ _emit_team_members_metric(synced)
+ _schedule_team_membership_audit_log(
+ team_id=team_id,
+ team_alias=team.team_alias,
+ before_members=roster,
+ after_members=after,
+ user_api_key_dict=user_api_key_dict,
+ litellm_proxy_admin_name=litellm_proxy_admin_name,
+ )
+ return RosterSync(team=synced, added=to_add, removed=to_remove)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 5b5956eba12..1860b1ab97b 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -29,6 +29,7 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from functools import partial
from itertools import takewhile
+from operator import attrgetter
from types import MappingProxyType
from typing import (
TYPE_CHECKING,
@@ -5831,7 +5832,7 @@ class PrismaClient:
Batch write update queries
"""
batcher = self.db.batch_()
- for idx, user in enumerate(data_list):
+ for user in sorted(data_list, key=attrgetter("user_id")):
try:
data_json = self.jsonify_object(data=user.model_dump(exclude_none=True))
except Exception:
diff --git a/tests/code_coverage_tests/unbounded_in_baseline.txt b/tests/code_coverage_tests/unbounded_in_baseline.txt
index 0ab157498c1..c7e73bf921c 100644
--- a/tests/code_coverage_tests/unbounded_in_baseline.txt
+++ b/tests/code_coverage_tests/unbounded_in_baseline.txt
@@ -42,15 +42,8 @@ litellm/proxy/management_endpoints/customer_endpoints.py delete_end_user prisma
litellm/proxy/management_endpoints/customer_endpoints.py delete_end_user prisma user_id.in `data.user_ids` 1
litellm/proxy/management_endpoints/internal_user_endpoints.py _check_user_info_v2_access prisma team_id.in `caller_user.teams` 0
litellm/proxy/management_endpoints/internal_user_endpoints.py _resolve_user_email_metadata prisma user_id.in `list(user_ids)` 0
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma created_by.in `data.user_ids` 0
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma team_id.in `user_row.teams` 0
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma updated_by.in `data.user_ids` 0
litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 0
litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 1
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 2
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 3
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 4
-litellm/proxy/management_endpoints/internal_user_endpoints.py delete_user prisma user_id.in `data.user_ids` 5
litellm/proxy/management_endpoints/internal_user_endpoints.py get_users prisma organization_id.in `org_id_list` 0
litellm/proxy/management_endpoints/internal_user_endpoints.py get_users prisma sso_user_id.in `sso_id_list` 0
litellm/proxy/management_endpoints/internal_user_endpoints.py get_users prisma user_id.in `user_id_list` 0
diff --git a/tests/integration/_support/database_relay.py b/tests/integration/_support/database_relay.py
index 754813256fe..2b04aa369fc 100644
--- a/tests/integration/_support/database_relay.py
+++ b/tests/integration/_support/database_relay.py
@@ -5,7 +5,7 @@ import time
from collections.abc import Generator
from contextlib import contextmanager
from typing import Final
-from urllib.parse import urlsplit, urlunsplit
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from pydantic import TypeAdapter
@@ -190,6 +190,100 @@ class DroppedConnectionRelay:
)
+SSL_REQUEST_CODE: Final = 80877103
+GSSENC_REQUEST_CODE: Final = 80877104
+
+
+class FrontendStatementScanner:
+ """Counts the statements one Postgres client sends: a Sync closes every extended-protocol statement and a
+ Query is a simple-protocol statement, so the count moves with the number of statements, never their size."""
+
+ def __init__(self) -> None:
+ self._buffer = b""
+ self._started = False
+
+ def feed(self, chunk: bytes) -> int:
+ self._buffer += chunk # rebind-ok: a message can span two reads
+ statements = 0 # rebind-ok: summed over the messages this chunk completes
+ while (frame := self._next_frame()) is not None:
+ length, is_statement = frame
+ statements += int(is_statement)
+ self._buffer = self._buffer[length:] # rebind-ok: drops the parsed message
+ return statements
+
+ def _next_frame(self) -> tuple[int, bool] | None:
+ if not self._started:
+ if len(self._buffer) < 8:
+ return None
+ startup_length: Final = int.from_bytes(self._buffer[:4], "big")
+ if len(self._buffer) < startup_length:
+ return None
+ request_code: Final = int.from_bytes(self._buffer[4:8], "big")
+ self._started = request_code not in (SSL_REQUEST_CODE, GSSENC_REQUEST_CODE)
+ return startup_length, False
+ if len(self._buffer) < 5:
+ return None
+ frame_length: Final = 1 + int.from_bytes(self._buffer[1:5], "big")
+ if len(self._buffer) < frame_length:
+ return None
+ return frame_length, self._buffer[:1] in (b"S", b"Q")
+
+
+class StatementCountingRelay:
+ def __init__(self, upstream_host: str, upstream_port: int) -> None:
+ self.port: Final = _free_port()
+ self._upstream_host: Final = upstream_host
+ self._upstream_port: Final = upstream_port
+ self._loop: Final = asyncio.new_event_loop()
+ self.statements = 0
+ self._ready: Final = threading.Event()
+ self._thread: Final = threading.Thread(target=self._run, daemon=True)
+
+ def start(self) -> None:
+ self._thread.start()
+ assert self._ready.wait(10), "Database relay did not start"
+
+ def stop(self) -> None:
+ self._loop.call_soon_threadsafe(self._loop.stop)
+ self._thread.join(10)
+
+ def _run(self) -> None:
+ asyncio.set_event_loop(self._loop)
+ self._loop.run_until_complete(asyncio.start_server(self._serve, "127.0.0.1", self.port))
+ self._ready.set()
+ self._loop.run_forever()
+
+ async def _serve(self, client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None:
+ server_reader, server_writer = await asyncio.open_connection(self._upstream_host, self._upstream_port)
+
+ async def forward(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter, scanner: FrontendStatementScanner | None
+ ) -> None:
+ try:
+ while chunk := await reader.read(65536):
+ if scanner is not None:
+ self.statements += scanner.feed(chunk)
+ writer.write(chunk)
+ await writer.drain()
+ except (ConnectionError, asyncio.IncompleteReadError):
+ return
+ finally:
+ writer.close()
+
+ await asyncio.gather(
+ forward(client_reader, server_writer, FrontendStatementScanner()),
+ forward(server_reader, client_writer, None),
+ )
+
+
+def plaintext_database_url(database_url: str) -> str:
+ parts: Final = urlsplit(database_url)
+ parameters: Final = tuple(
+ (name, value) for name, value in parse_qsl(parts.query, keep_blank_values=True) if name != "sslmode"
+ ) + (("sslmode", "disable"),)
+ return urlunsplit(parts._replace(query=urlencode(parameters)))
+
+
def _relayed_url(database_url: str, port: int) -> str:
parts: Final = urlsplit(database_url)
credentials: Final = f"{parts.username}:{parts.password}@" if parts.username else ""
@@ -230,3 +324,15 @@ def dropped_connection_relay(database_url: str, trigger: bytes) -> Generator[tup
yield relay, _relayed_url(database_url, relay.port)
finally:
relay.stop()
+
+
+@contextmanager
+def statement_counting_relay(database_url: str) -> Generator[tuple[StatementCountingRelay, str]]:
+ parts: Final = urlsplit(database_url)
+ assert parts.hostname is not None and parts.port is not None, database_url
+ relay: Final = StatementCountingRelay(parts.hostname, parts.port)
+ relay.start()
+ try:
+ yield relay, plaintext_database_url(_relayed_url(database_url, relay.port))
+ finally:
+ relay.stop()
diff --git a/tests/integration/_support/process.py b/tests/integration/_support/process.py
index 7f69f69a55f..75277ba8cfc 100644
--- a/tests/integration/_support/process.py
+++ b/tests/integration/_support/process.py
@@ -757,6 +757,7 @@ def owned_proxy_process(
coverage_file: Path | None = None,
healthcheck: WorkerHealthcheck = WorkerHealthcheck.STRICT,
inherited: Mapping[str, str] = os.environ,
+ client_timeout: float = 15,
) -> Iterator[OwnedProxy]:
assert "--timeout_worker_healthcheck" not in extra_arguments, "Choose the worker healthcheck with `healthcheck`"
root: Final = _proxy_root()
@@ -788,7 +789,7 @@ def owned_proxy_process(
process: Final = launch.process
try:
with httpx.Client(
- base_url=f"http://127.0.0.1:{launch.port}", timeout=15, trust_env=False, limits=GATEWAY_LIMITS
+ base_url=f"http://127.0.0.1:{launch.port}", timeout=client_timeout, trust_env=False, limits=GATEWAY_LIMITS
) as client:
yield OwnedProxy(Gateway(client, gateway.key, gateway.upstream_url), process, launch.log, healthcheck)
finally:
diff --git a/tests/integration/management/test_health_routing.py b/tests/integration/management/test_health_routing.py
index 5939d066201..3a60efe4342 100644
--- a/tests/integration/management/test_health_routing.py
+++ b/tests/integration/management/test_health_routing.py
@@ -3,13 +3,12 @@ import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Final
-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
import pytest
import yaml
from integration._support.client import JSON_OBJECT, Gateway, eventually
from integration._support.database import scratch_database
-from integration._support.database_relay import database_relay, held_statement_relay
+from integration._support.database_relay import database_relay, held_statement_relay, plaintext_database_url
from integration._support.process import owned_proxy
_READINESS_PROBE_QUERY: Final = b"SELECT 1"
@@ -23,14 +22,6 @@ def _health_routing_config(directory: Path, general_settings: dict[str, object])
return path
-def _plaintext_database_url(database_url: str) -> str:
- parts: Final = urlsplit(database_url)
- parameters: Final = tuple(
- (name, value) for name, value in parse_qsl(parts.query, keep_blank_values=True) if name != "sslmode"
- ) + (("sslmode", "disable"),)
- return urlunsplit(parts._replace(query=urlencode(parameters)))
-
-
def _assert_liveness_and_readiness(gateway: Gateway, *, status_code: int, body: dict[str, str]) -> None:
for path in ("/health/liveliness", "/health/liveness"):
response: Final = gateway.client.get(path)
@@ -51,7 +42,7 @@ def test_public_readiness_reports_database_outage_and_allow_unavailable_setting(
gateway,
tmp_path,
{
- "DATABASE_URL": _plaintext_database_url(relayed_url),
+ "DATABASE_URL": plaintext_database_url(relayed_url),
"PRISMA_HEALTH_WATCHDOG_ENABLED": "false",
},
workers=1,
@@ -84,7 +75,7 @@ def test_public_readiness_reports_database_outage_and_allow_unavailable_setting(
gateway,
tmp_path,
{
- "DATABASE_URL": _plaintext_database_url(relayed_url),
+ "DATABASE_URL": plaintext_database_url(relayed_url),
"PRISMA_HEALTH_WATCHDOG_ENABLED": "false",
},
config=allow_unavailable_config,
@@ -125,7 +116,7 @@ def test_public_readiness_reports_stalled_database_lookups(gateway: Gateway, tmp
)
with held_statement_relay(database_url, lookup_hash) as (relay, relayed_url):
overrides = {
- "DATABASE_URL": _plaintext_database_url(relayed_url),
+ "DATABASE_URL": plaintext_database_url(relayed_url),
"PRISMA_HEALTH_WATCHDOG_ENABLED": "false",
"PROXY_DB_LOOKUP_DEADLINE_SECONDS": "1",
"PROXY_DB_LOOKUP_STALL_WINDOW_SECONDS": "15",
diff --git a/tests/integration/management/test_scim_group_bulk_roster.py b/tests/integration/management/test_scim_group_bulk_roster.py
new file mode 100644
index 00000000000..8387beca958
--- /dev/null
+++ b/tests/integration/management/test_scim_group_bulk_roster.py
@@ -0,0 +1,535 @@
+"""SCIM group pushes write the roster in bulk, whatever the member count.
+
+POST /scim/v2/Groups, PUT and PATCH /scim/v2/Groups/{id} used to run /team/member_add once per member, so a
+500-member push was thousands of statements and outlasted the edge in front of the proxy. One locked
+transaction now resolves every member, writes the roster and the membership rows and tags the users, so a
+push of 500 members runs as many statements as a push of 5.
+"""
+
+import os
+import time
+import uuid
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from dataclasses import dataclass
+from hashlib import sha256
+from pathlib import Path
+from typing import Final, LiteralString
+
+import httpx
+import psutil
+import psycopg
+import pytest
+from integration._support.budget import case_timeout_seconds
+from integration._support.client import (
+ JSON_OBJECT,
+ Gateway,
+ Scenario,
+ delete_key_if_present,
+ eventually,
+ object_value,
+ string_value,
+)
+from integration._support.database import read_rows, write_rows
+from integration._support.database_relay import StatementCountingRelay, statement_counting_relay
+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy_process
+from psycopg import sql
+from pydantic import JsonValue
+
+GROUP_SCHEMA: Final = "urn:ietf:params:scim:schemas:core:2.0:Group"
+PATCH_OP_SCHEMA: Final = "urn:ietf:params:scim:api:messages:2.0:PatchOp"
+SMALL_PUSH: Final = 5
+LARGE_PUSH: Final = 500
+# Background work on an idle proxy (the cron-job leader poll, spend flushes) lands a few statements inside a
+# measured window; the per-member loop this guards against added about six statements per member.
+NOISE_ALLOWANCE: Final = 100
+UNFIXED_PUSH_SECONDS: Final = 120
+SWAP_GROUP: Final = 200
+SWAP_ROUNDS: Final = 10
+CHAOS_GROUP: Final = 100
+ROLLBACK_SECONDS: Final = 90
+TEAM_ROW_SQL: Final = 'SELECT members_with_roles FROM "LiteLLM_TeamTable" WHERE team_id = %s'
+LOCK_USER_ROW_SQL: Final = 'SELECT user_id FROM "LiteLLM_UserTable" WHERE user_id = %s FOR UPDATE'
+LOCK_KEY_ROW_SQL: Final = 'SELECT token FROM "LiteLLM_VerificationToken" WHERE token = %s FOR UPDATE'
+SESSIONS_BLOCKED_BY_SQL: Final = (
+ "SELECT count(*)::int AS waiting FROM pg_stat_activity WHERE %s::int = ANY(pg_blocking_pids(pid))"
+)
+CLIENT_PORTS_BLOCKED_BY_SQL: Final = (
+ "SELECT client_port FROM pg_stat_activity WHERE %s::int = ANY(pg_blocking_pids(pid)) AND client_port > 0"
+)
+TRANSACTIONS_OPEN_SINCE_SQL: Final = """
+SELECT count(*)::int AS open FROM pg_stat_activity
+WHERE datname = current_database() AND backend_type = 'client backend' AND pid <> pg_backend_pid()
+ AND xact_start < %s::timestamptz
+"""
+SEED_USERS_SQL: Final = """
+INSERT INTO "LiteLLM_UserTable" (user_id, user_role, teams, models)
+SELECT %s || '-' || lpad(n::text, 3, '0'), 'internal_user', '{}'::text[], '{}'::text[]
+FROM generate_series(1, %s::int) AS n
+"""
+
+
+@dataclass(frozen=True, slots=True)
+class Measured:
+ response: httpx.Response
+ statements: int
+ seconds: float
+
+
+def _measured(relay: StatementCountingRelay, send: Callable[[], httpx.Response]) -> Measured:
+ before: Final = relay.statements
+ started: Final = time.perf_counter()
+ response: Final = send()
+ return Measured(response=response, statements=relay.statements - before, seconds=time.perf_counter() - started)
+
+
+def _seed_users(scenario: Scenario, count: int) -> tuple[str, ...]:
+ prefix: Final = f"integration-scim-{uuid.uuid4().hex}"
+ write_rows(SEED_USERS_SQL, (prefix, str(count)))
+ scenario.cleanups.callback(write_rows, 'DELETE FROM "LiteLLM_UserTable" WHERE user_id LIKE %s', (f"{prefix}-%",))
+ return tuple(f"{prefix}-{index:03d}" for index in range(1, count + 1))
+
+
+def _members(users: Sequence[str]) -> list[JsonValue]:
+ return [{"value": user} for user in users]
+
+
+def _create_group(candidate: Gateway, users: Sequence[str]) -> httpx.Response:
+ return candidate.request(
+ "POST",
+ "/scim/v2/Groups",
+ {"schemas": [GROUP_SCHEMA], "displayName": f"integration-{uuid.uuid4().hex}", "members": _members(users)},
+ )
+
+
+def _replace_group(candidate: Gateway, team: str, users: Sequence[str]) -> httpx.Response:
+ return candidate.request(
+ "PUT",
+ f"/scim/v2/Groups/{team}",
+ {
+ "schemas": [GROUP_SCHEMA],
+ "id": team,
+ "displayName": f"integration-{uuid.uuid4().hex}",
+ "members": _members(users),
+ },
+ )
+
+
+def _add_to_group(candidate: Gateway, team: str, users: Sequence[str]) -> httpx.Response:
+ return candidate.request(
+ "PATCH",
+ f"/scim/v2/Groups/{team}",
+ {
+ "schemas": [PATCH_OP_SCHEMA],
+ "Operations": [{"op": "add", "path": "members", "value": _members(users)}],
+ },
+ )
+
+
+def _body(response: httpx.Response) -> dict[str, JsonValue]:
+ return JSON_OBJECT.validate_json(response.content)
+
+
+def _member_ids(body: Mapping[str, JsonValue]) -> frozenset[str]:
+ members: Final = body.get("members") or []
+ assert isinstance(members, list), members
+ return frozenset(string_value(object_value(member)["value"]) for member in members)
+
+
+def _created_team(scenario: Scenario, created: httpx.Response) -> str:
+ assert created.status_code == 201, created.text
+ team: Final = string_value(_body(created)["id"])
+ scenario.cleanups.callback(scenario.delete_team, team)
+ return team
+
+
+def _membership_user_ids(team: str) -> frozenset[str]:
+ rows: Final = read_rows('SELECT user_id FROM "LiteLLM_TeamMembership" WHERE team_id = %s', (team,))
+ return frozenset(string_value(row["user_id"]) for row in rows)
+
+
+_UTC_MICROSECONDS: Final = "YYYY-MM-DD HH24:MI:SS.US"
+
+
+def _updated_at(user_id: str) -> str:
+ rows: Final = read_rows(
+ f"SELECT to_char(updated_at, '{_UTC_MICROSECONDS}') AS updated_at FROM \"LiteLLM_UserTable\" WHERE user_id = %s",
+ (user_id,),
+ )
+ return string_value(rows[0]["updated_at"])
+
+
+def _database_utc_now() -> str:
+ rows: Final = read_rows(f"SELECT to_char(NOW() AT TIME ZONE 'UTC', '{_UTC_MICROSECONDS}') AS utc_now", ())
+ return string_value(rows[0]["utc_now"])
+
+
+def _users_referencing(team: str) -> frozenset[str]:
+ rows: Final = read_rows('SELECT user_id FROM "LiteLLM_UserTable" WHERE %s = ANY(teams)', (team,))
+ return frozenset(string_value(row["user_id"]) for row in rows)
+
+
+def _assert_landed(candidate: Gateway, team: str, users: Sequence[str]) -> None:
+ assert _member_ids(candidate.get(f"/scim/v2/Groups/{team}")) == frozenset(users)
+ assert _membership_user_ids(team) == frozenset(users)
+ assert _users_referencing(team) == frozenset(users)
+
+
[email protected](300) # owned proxy boot plus three 500-member pushes
+def test_group_pushes_of_500_members_run_as_many_statements_as_pushes_of_5(
+ gateway: Gateway, tmp_path: Path, record_property: Callable[[str, object], None]
+) -> None:
+ with (
+ gateway.scenario() as scenario,
+ statement_counting_relay(os.environ["DATABASE_URL"]) as (relay, relayed_url),
+ owned_proxy_process(
+ gateway,
+ tmp_path,
+ {"DATABASE_URL": relayed_url},
+ remove_environment=("DATABASE_URL_READ_REPLICA",),
+ workers=2,
+ client_timeout=UNFIXED_PUSH_SECONDS,
+ ) as owned,
+ ):
+ candidate: Final = owned.gateway
+ small_a: Final = _seed_users(scenario, SMALL_PUSH)
+ small_b: Final = _seed_users(scenario, SMALL_PUSH)
+ large: Final = _seed_users(scenario, LARGE_PUSH)
+
+ created_small: Final = _measured(relay, lambda: _create_group(candidate, small_a))
+ small_team: Final = _created_team(scenario, created_small.response)
+ created_large: Final = _measured(relay, lambda: _create_group(candidate, large))
+ large_team: Final = _created_team(scenario, created_large.response)
+ assert _member_ids(_body(created_large.response)) == frozenset(large)
+ _assert_landed(candidate, small_team, small_a)
+ _assert_landed(candidate, large_team, large)
+ detach_window_open: Final = _database_utc_now()
+
+ replaced_small: Final = _measured(relay, lambda: _replace_group(candidate, small_team, small_b))
+ replaced_large: Final = _measured(relay, lambda: _replace_group(candidate, large_team, small_a))
+ assert replaced_small.response.status_code == 200, replaced_small.response.text
+ assert replaced_large.response.status_code == 200, replaced_large.response.text
+ assert _member_ids(_body(replaced_small.response)) == frozenset(small_b)
+ _assert_landed(candidate, small_team, small_b)
+ _assert_landed(candidate, large_team, small_a)
+ assert detach_window_open <= _updated_at(large[0]) <= _database_utc_now()
+
+ patched_small: Final = _measured(relay, lambda: _add_to_group(candidate, small_team, small_a))
+ patched_large: Final = _measured(relay, lambda: _add_to_group(candidate, large_team, large))
+ assert patched_small.response.status_code == 200, patched_small.response.text
+ assert patched_large.response.status_code == 200, patched_large.response.text
+ _assert_landed(candidate, small_team, [*small_a, *small_b])
+ _assert_landed(candidate, large_team, [*small_a, *large])
+
+ pushes: Final = (
+ ("POST", created_small, created_large),
+ ("PUT", replaced_small, replaced_large),
+ ("PATCH", patched_small, patched_large),
+ )
+ for verb, small, big in pushes:
+ record_property(
+ f"{verb.lower()}_statements",
+ f"{SMALL_PUSH} members: {small.statements} statements in {small.seconds:.2f}s; "
+ f"{LARGE_PUSH} members: {big.statements} statements in {big.seconds:.2f}s",
+ )
+ for verb, small, big in pushes:
+ assert min(small.statements, big.statements) > 0, (verb, small.statements, big.statements)
+ assert big.statements <= small.statements + NOISE_ALLOWANCE, (verb, small.statements, big.statements)
+
+
+def _trade_rosters(candidate: Gateway, teams: tuple[str, str], rosters: tuple[Sequence[str], Sequence[str]]) -> None:
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ left: Final = pool.submit(_replace_group, candidate, teams[0], rosters[1])
+ right: Final = pool.submit(_replace_group, candidate, teams[1], rosters[0])
+ for response in (left.result(), right.result()):
+ assert response.status_code == 200, response.text
+
+
+def test_two_groups_trading_rosters_in_parallel_both_land(gateway: Gateway, tmp_path: Path) -> None:
+ with (
+ gateway.scenario() as scenario,
+ owned_proxy_process(
+ gateway,
+ tmp_path,
+ {},
+ remove_environment=("DATABASE_URL_READ_REPLICA",),
+ workers=2,
+ client_timeout=UNFIXED_PUSH_SECONDS,
+ ) as owned,
+ ):
+ candidate: Final = owned.gateway
+ left_users: Final = _seed_users(scenario, SWAP_GROUP)
+ right_users: Final = _seed_users(scenario, SWAP_GROUP)
+ left: Final = _created_team(scenario, _create_group(candidate, left_users))
+ right: Final = _created_team(scenario, _create_group(candidate, right_users))
+ for round_index in range(SWAP_ROUNDS):
+ held: Final = (left_users, right_users) if round_index % 2 == 0 else (right_users, left_users)
+ _trade_rosters(candidate, (left, right), held)
+ _assert_landed(candidate, left, left_users)
+ _assert_landed(candidate, right, right_users)
+
+
+def _int_value(rows: Sequence[Mapping[str, JsonValue]], column: str) -> int:
+ value: Final = rows[0][column]
+ assert isinstance(value, int), rows
+ return value
+
+
+@contextmanager
+def _holding_row_lock(lock_sql: LiteralString, row_id: str) -> Iterator[int]:
+ with psycopg.connect(os.environ["DATABASE_URL"]) as holder:
+ _ = holder.execute(lock_sql, (row_id,))
+ yield holder.info.backend_pid
+
+
+def _sessions_blocked_by(backend_pid: int) -> int:
+ return _int_value(read_rows(SESSIONS_BLOCKED_BY_SQL, (str(backend_pid),)), "waiting")
+
+
+def _database_now() -> str:
+ return string_value(read_rows("SELECT now()::text AS now", ())[0]["now"])
+
+
+def _transactions_open_since(moment: str) -> int:
+ return _int_value(read_rows(TRANSACTIONS_OPEN_SINCE_SQL, (moment,)), "open")
+
+
+def _client_ports_blocked_by(backend_pid: int) -> frozenset[int]:
+ rows: Final = read_rows(CLIENT_PORTS_BLOCKED_BY_SQL, (str(backend_pid),))
+ return frozenset(_int_value((row,), "client_port") for row in rows)
+
+
+def _local_tcp_ports(pid: int) -> Iterator[int]:
+ worker: Final = psutil.Process(pid)
+ for process in (worker, *worker.children(recursive=True)):
+ yield from (connection.laddr.port for connection in process.net_connections(kind="tcp"))
+
+
+def _worker_holding(owned: OwnedProxy, client_ports: frozenset[int]) -> int:
+ (worker,) = tuple(pid for pid in owned.worker_pids() if client_ports & frozenset(_local_tcp_ports(pid)))
+ return worker
+
+
+def _roster_ids(team: str) -> tuple[str, ...]:
+ rows: Final = read_rows(TEAM_ROW_SQL, (team,))
+ assert len(rows) == 1, rows
+ roster: Final = rows[0]["members_with_roles"]
+ assert isinstance(roster, list), roster
+ return tuple(string_value(object_value(member)["user_id"]) for member in roster)
+
+
+def _delete_team_if_present(candidate: Gateway, team: str) -> None:
+ if read_rows(TEAM_ROW_SQL, (team,)):
+ _ = candidate.post("/team/delete", {"team_ids": [team]})
+
+
+def _group_the_test_deletes(candidate: Gateway, scenario: Scenario) -> str:
+ created: Final = _create_group(candidate, ())
+ assert created.status_code == 201, created.text
+ team: Final = string_value(_body(created)["id"])
+ scenario.cleanups.callback(_delete_team_if_present, candidate, team)
+ return team
+
+
+def test_a_group_deleted_while_its_push_waits_on_a_member_row_answers_404_and_writes_nothing(
+ gateway: Gateway,
+) -> None:
+ with gateway.scenario() as scenario, ThreadPoolExecutor(max_workers=1) as pool:
+ users: Final = _seed_users(scenario, SMALL_PUSH)
+ team: Final = _group_the_test_deletes(gateway, scenario)
+ with _holding_row_lock(LOCK_USER_ROW_SQL, min(users)) as holder_pid:
+ push: Final = pool.submit(_replace_group, gateway, team, users)
+ _ = eventually(lambda: _sessions_blocked_by(holder_pid), lambda waiting: waiting >= 1, seconds=30)
+ deleted: Final = gateway.request("DELETE", f"/scim/v2/Groups/{team}")
+ assert deleted.status_code == 204, deleted.text
+ assert not push.done(), push.result().text
+ pushed: Final = push.result()
+ assert pushed.status_code == 404, pushed.text
+ assert read_rows(TEAM_ROW_SQL, (team,)) == []
+ assert _membership_user_ids(team) == frozenset()
+ assert _users_referencing(team) == frozenset()
+
+
+@contextmanager
+def _refusing_memberships_for(user_id: str) -> Iterator[None]:
+ name: Final = sql.Identifier(f"integration_refuse_membership_{uuid.uuid4().hex}")
+ with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as connection:
+ _ = connection.execute(
+ sql.SQL(
+ "CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS "
+ "$$ BEGIN RAISE EXCEPTION 'integration refused this membership write'; END $$"
+ ).format(name)
+ )
+ _ = connection.execute(
+ sql.SQL(
+ 'CREATE TRIGGER {} BEFORE INSERT ON "LiteLLM_TeamMembership" FOR EACH ROW '
+ "WHEN (NEW.user_id = {}) EXECUTE FUNCTION {}()"
+ ).format(name, sql.Literal(user_id), name)
+ )
+ try:
+ yield
+ finally:
+ _ = connection.execute(sql.SQL('DROP TRIGGER {} ON "LiteLLM_TeamMembership"').format(name))
+ _ = connection.execute(sql.SQL("DROP FUNCTION {}()").format(name))
+
+
+def test_a_push_whose_membership_write_fails_answers_5xx_keeps_the_old_roster_and_a_retry_lands(
+ gateway: Gateway,
+) -> None:
+ with gateway.scenario() as scenario:
+ kept: Final = _seed_users(scenario, SMALL_PUSH)
+ arriving: Final = _seed_users(scenario, SMALL_PUSH)
+ team: Final = _created_team(scenario, _create_group(gateway, kept))
+ replacement: Final = (*kept[:2], *arriving)
+ with _refusing_memberships_for(max(arriving)):
+ refused: Final = _replace_group(gateway, team, replacement)
+ assert 500 <= refused.status_code < 600, refused.text
+ _assert_landed(gateway, team, kept)
+ retried: Final = _replace_group(gateway, team, replacement)
+ assert retried.status_code == 200, retried.text
+ _assert_landed(gateway, team, replacement)
+
+
+def _five_kilobyte_member(scenario: Scenario) -> str:
+ user_id: Final = f"integration-scim-{uuid.uuid4().hex}-".ljust(5 * 1024, "x")
+ scenario.cleanups.callback(write_rows, 'DELETE FROM "LiteLLM_UserTable" WHERE user_id = %s', (user_id,))
+ return user_id
+
+
+ODD_MEMBER_VALUES: Final[Mapping[str, Callable[[Scenario, Sequence[str]], JsonValue]]] = {
+ "int": lambda _scenario, _kept: 7,
+ "list": lambda _scenario, kept: [kept[0]],
+ "empty": lambda _scenario, _kept: "",
+ "five-kilobytes": lambda scenario, _kept: _five_kilobyte_member(scenario),
+ "duplicate": lambda _scenario, kept: kept[0],
+}
+
+
[email protected]("shape", tuple(ODD_MEMBER_VALUES))
+def test_a_push_with_an_odd_member_value_never_answers_500_and_keeps_the_roster_consistent(
+ gateway: Gateway, shape: str
+) -> None:
+ with gateway.scenario() as scenario:
+ kept: Final = _seed_users(scenario, SMALL_PUSH)
+ team: Final = _created_team(scenario, _create_group(gateway, kept))
+ odd: Final = ODD_MEMBER_VALUES[shape](scenario, kept)
+ pushed: Final = gateway.request(
+ "PUT",
+ f"/scim/v2/Groups/{team}",
+ {
+ "schemas": [GROUP_SCHEMA],
+ "id": team,
+ "displayName": f"integration-{uuid.uuid4().hex}",
+ "members": [*_members(kept), {"value": odd}],
+ },
+ )
+ assert pushed.status_code < 500, pushed.text
+ roster: Final = _roster_ids(team)
+ assert len(roster) == len(frozenset(roster)), roster
+ assert frozenset(kept) <= frozenset(roster), roster
+ _assert_landed(gateway, team, roster)
+ if pushed.status_code >= 400:
+ assert frozenset(roster) == frozenset(kept), (pushed.text, roster)
+
+
+@dataclass(frozen=True, slots=True)
+class PatchShape:
+ operations: Callable[[Sequence[str]], list[JsonValue]]
+ expected: Callable[[Sequence[str]], tuple[str, ...]]
+
+
+PATCH_SHAPES: Final[Mapping[str, PatchShape]] = {
+ "okta-remove-by-filter": PatchShape(
+ operations=lambda users: [{"op": "remove", "path": f'members[value eq "{users[1]}"]'}],
+ expected=lambda users: (users[0], users[2]),
+ ),
+ "entra-remove-by-value-list": PatchShape(
+ operations=lambda users: [{"op": "Remove", "path": "members", "value": [{"value": users[1]}]}],
+ expected=lambda users: (users[0], users[2]),
+ ),
+ "replace-members": PatchShape(
+ operations=lambda users: [
+ {"op": "replace", "path": "members", "value": [{"value": users[0]}, {"value": users[3]}]}
+ ],
+ expected=lambda users: (users[0], users[3]),
+ ),
+}
+
+
[email protected]("shape", tuple(PATCH_SHAPES))
+def test_patch_member_operation_shapes_land_the_expected_roster(gateway: Gateway, shape: str) -> None:
+ with gateway.scenario() as scenario:
+ users: Final = _seed_users(scenario, 4)
+ team: Final = _created_team(scenario, _create_group(gateway, users[:3]))
+ patched: Final = gateway.request(
+ "PATCH",
+ f"/scim/v2/Groups/{team}",
+ {"schemas": [PATCH_OP_SCHEMA], "Operations": PATCH_SHAPES[shape].operations(users)},
+ )
+ assert patched.status_code == 200, patched.text
+ _assert_landed(gateway, team, PATCH_SHAPES[shape].expected(users))
+
+
+def _team_key_for(scenario: Scenario, team: str, user_id: str) -> str:
+ key: Final = string_value(scenario.gateway.post("/key/generate", {"team_id": team, "user_id": user_id})["key"])
+ scenario.cleanups.callback(delete_key_if_present, scenario.gateway, key)
+ return key
+
+
+def _push_outcome(candidate: Gateway, team: str, users: Sequence[str]) -> str:
+ try:
+ return str(_replace_group(candidate, team, users).status_code)
+ except httpx.TransportError as error:
+ return type(error).__name__
+
+
[email protected](case_timeout_seconds() + 2 * graceful_stop_seconds() + UNFIXED_PUSH_SECONDS + ROLLBACK_SECONDS)
+def test_a_worker_killed_mid_push_leaves_the_old_roster_and_a_retry_lands_the_new_one(
+ gateway: Gateway, tmp_path: Path, record_property: Callable[[str, object], None]
+) -> None:
+ with (
+ gateway.scenario() as scenario,
+ owned_proxy_process(
+ gateway,
+ tmp_path,
+ {},
+ remove_environment=("DATABASE_URL_READ_REPLICA",),
+ workers=2,
+ client_timeout=UNFIXED_PUSH_SECONDS,
+ ) as owned,
+ ThreadPoolExecutor(max_workers=1) as pool,
+ ):
+ candidate: Final = owned.gateway
+ leaving: Final = _seed_users(scenario, CHAOS_GROUP)
+ arriving: Final = _seed_users(scenario, CHAOS_GROUP)
+ team: Final = _created_team(scenario, _create_group(candidate, leaving))
+ pinned_key: Final = _team_key_for(scenario, team, max(leaving))
+ with _holding_row_lock(LOCK_KEY_ROW_SQL, sha256(pinned_key.encode()).hexdigest()) as holder_pid:
+ push: Final = pool.submit(_push_outcome, candidate, team, arriving)
+ blocked_ports: Final = eventually(
+ lambda: _client_ports_blocked_by(holder_pid), bool, seconds=UNFIXED_PUSH_SECONDS
+ )
+ killed_at: Final = _database_now()
+ _ = owned.kill_worker(_worker_holding(owned, blocked_ports))
+ record_property("interrupted_push", push.result())
+ _ = eventually(lambda: _transactions_open_since(killed_at), lambda open: open == 0, seconds=ROLLBACK_SECONDS)
+ settled: Final = frozenset(_roster_ids(team))
+ record_property(
+ "roster_after_kill",
+ {"leaving": len(settled & frozenset(leaving)), "arriving": len(settled & frozenset(arriving))},
+ )
+ assert settled in (frozenset(leaving), frozenset(arriving)), sorted(settled)
+ _assert_landed(candidate, team, sorted(settled))
+
+ retried: Final = _replace_group(candidate, team, arriving)
+ assert retried.status_code == 200, retried.text
+ _assert_landed(candidate, team, arriving)
+ assert (
+ read_rows(
+ 'SELECT token FROM "LiteLLM_VerificationToken" WHERE token = %s',
+ (sha256(pinned_key.encode()).hexdigest(),),
+ )
+ == []
+ )
diff --git a/tests/integration/management/test_team_delete_large_membership.py b/tests/integration/management/test_team_delete_large_membership.py
index 5912256e5cd..90d204722ac 100644
--- a/tests/integration/management/test_team_delete_large_membership.py
+++ b/tests/integration/management/test_team_delete_large_membership.py
@@ -46,6 +46,12 @@ FROM generate_series(1, %s::int) AS n
# The master key's user id. `/team/new` appends the creator to the roster as an admin, so every team
# created here carries this member alongside the ones the test adds.
PROXY_ADMIN: Final = "default_user_id"
+KEYS_WELL_PAST_THE_PUBLISH_CAP: Final = 2500
+SEED_TEAM_KEYS_SQL: Final = """
+INSERT INTO "LiteLLM_VerificationToken" (token, team_id, models)
+SELECT encode(sha256(convert_to(%s || '-' || n::text, 'UTF8')), 'hex'), %s, '{}'::text[]
+FROM generate_series(1, %s::int) AS n
+"""
TAKE_TEAM_LOCK_SQL: Final = "SELECT pg_advisory_xact_lock(hashtext(%s))"
# Sessions blocked on the advisory lock the given backend holds, and nothing else on the shared rig.
WAITERS_ON_HELD_LOCK_SQL: Final = """
@@ -632,3 +638,36 @@ def test_member_add_and_delete_released_together_leave_no_team_reference(gateway
assert _user_teams(newcomer) == []
assert _users_referencing(team) == []
assert [row["team_id"] for row in _tombstones(team)] == [team]
+
+
+def _seeded_team_keys(team_id: str, count: int) -> tuple[str, ...]:
+ prefix: Final = f"sk-integration-{uuid.uuid4().hex}"
+ write_rows(SEED_TEAM_KEYS_SQL, (prefix, team_id, str(count)))
+ return tuple(f"{prefix}-{index}" for index in range(1, count + 1))
+
+
+def _models_status(proxy: Gateway, key: str) -> int:
+ return proxy.request("GET", "/v1/models", key=key).status_code
+
+
+def _statuses(proxy: Gateway, keys: Sequence[str]) -> dict[int, int]:
+ with ThreadPoolExecutor(max_workers=16) as pool:
+ statuses: Final = tuple(pool.map(lambda key: _models_status(proxy, key), keys))
+ return {status: statuses.count(status) for status in frozenset(statuses)}
+
+
+def test_deleting_a_team_with_more_keys_than_the_publish_cap_revokes_every_key_on_a_warmed_peer(
+ gateway: Gateway, peer: Gateway
+) -> None:
+ with gateway.scenario() as scenario:
+ team: Final = _create_team(scenario)
+ scenario.cleanups.callback(write_rows, 'DELETE FROM "LiteLLM_VerificationToken" WHERE team_id = %s', (team,))
+ keys: Final = _seeded_team_keys(team, KEYS_WELL_PAST_THE_PUBLISH_CAP)
+ assert _statuses(peer, keys) == {200: len(keys)}
+
+ response: Final = _delete_teams(gateway, [team])
+ assert response.status_code == 200, response.text
+ assert read_rows('SELECT token FROM "LiteLLM_VerificationToken" WHERE team_id = %s', (team,)) == []
+
+ _ = eventually(lambda: _models_status(peer, keys[-1]), lambda status: status == 401, seconds=10)
+ assert _statuses(peer, keys) == {401: len(keys)}
diff --git a/tests/integration/management/test_team_delete_member_cache_eviction.py b/tests/integration/management/test_team_delete_member_cache_eviction.py
index 0b1daa1f527..9b1e51a578e 100644
--- a/tests/integration/management/test_team_delete_member_cache_eviction.py
+++ b/tests/integration/management/test_team_delete_member_cache_eviction.py
@@ -1,6 +1,7 @@
"""
`/team/delete` cache eviction across both proxies: member user objects, the team object and the
-team's keys must stop being served by every worker once the team rows are gone.
+team's keys must stop being served by every worker once the team rows are gone. A SCIM group push
+that removes a member deletes that member's team keys, which must stop the same way.
Auth caches the user object under the Redis key `<user_id>`, the team under `team_id:<team_id>`
and the key under its sha256; `enable_redis_auth_cache` is on, so Redis is the observable and
@@ -36,6 +37,8 @@ from tests.integration._support.wire import Reply, Request, wire_server
_USAGE: Final = {"prompt_tokens": 11, "completion_tokens": 4, "total_tokens": 15}
_CACHE_KEY_HEADER: Final = "x-litellm-cache-key"
+_GROUP_SCHEMA: Final = "urn:ietf:params:scim:schemas:core:2.0:Group"
+_PATCH_OP_SCHEMA: Final = "urn:ietf:params:scim:api:messages:2.0:PatchOp"
def _redis() -> Redis:
@@ -444,3 +447,111 @@ def test_team_delete_evicts_team_object_and_key_on_both_proxies(gateway: Gateway
assert refused.status_code == 401 and "token_not_found_in_db" in refused.text, refused.text
assert cache.exists(f"team_id:{team}") == 0, cache.keys(f"*{team}*")
assert cache.exists(hashed) == 0, cache.keys(f"*{hashed}*")
+
+
+def _scim_group(gateway: Gateway, scenario: Scenario, members: Sequence[str]) -> str:
+ created: Final = gateway.request(
+ "POST",
+ "/scim/v2/Groups",
+ {
+ "schemas": [_GROUP_SCHEMA],
+ "displayName": f"integration-{uuid.uuid4().hex}",
+ "members": [{"value": member} for member in members],
+ },
+ )
+ assert created.status_code == 201, created.text
+ team_id: Final = string_value(JSON_OBJECT.validate_json(created.content)["id"])
+ scenario.cleanups.callback(_delete_team_if_present, gateway, team_id)
+ return team_id
+
+
+def _scim_replace_members(gateway: Gateway, team_id: str, members: Sequence[str]) -> None:
+ replaced: Final = gateway.request(
+ "PUT",
+ f"/scim/v2/Groups/{team_id}",
+ {
+ "schemas": [_GROUP_SCHEMA],
+ "id": team_id,
+ "displayName": f"integration-{uuid.uuid4().hex}",
+ "members": [{"value": member} for member in members],
+ },
+ )
+ assert replaced.status_code == 200, replaced.text
+
+
+def _scim_remove_member(gateway: Gateway, team_id: str, member: str) -> None:
+ patched: Final = gateway.request(
+ "PATCH",
+ f"/scim/v2/Groups/{team_id}",
+ {"schemas": [_PATCH_OP_SCHEMA], "Operations": [{"op": "remove", "path": f'members[value eq "{member}"]'}]},
+ )
+ assert patched.status_code == 200, patched.text
+
+
+def _member_team_key(gateway: Gateway, scenario: Scenario, team_id: str, user_id: str, model: str) -> str:
+ created: Final = gateway.post("/key/generate", {"team_id": team_id, "user_id": user_id, "models": [model]})
+ token: Final = string_value(created["key"])
+ scenario.cleanups.callback(delete_key_if_present, gateway, token)
+ return token
+
+
+def _refused_on_peer(peer: Gateway, model: str, key: str) -> None:
+ _ = eventually(
+ lambda: _httpx_chat(peer, model, key, False, "removed member key on peer " + uuid.uuid4().hex),
+ lambda status: status == 401,
+ seconds=10,
+ )
+
+
+def test_scim_removal_refuses_the_removed_members_team_key_for_every_client_on_both_proxies(
+ gateway: Gateway, peer: Gateway
+) -> None:
+ proxies: Final = {"primary": gateway, "peer": peer}
+ with wire_server(_upstream) as upstream, gateway.scenario() as scenario:
+ model: Final = scenario.model(api_base=upstream.url + "/v1")
+ alice: Final = scenario.user(user_role="internal_user")
+ bob: Final = scenario.user(user_role="internal_user")
+ team: Final = _scim_group(gateway, scenario, (alice, bob))
+ alice_key: Final = _member_team_key(gateway, scenario, team, alice, model)
+ bob_key: Final = _member_team_key(gateway, scenario, team, bob, model)
+ warmed: Final = {**_observe(proxies, model, alice_key), **_observe(proxies, model, bob_key)}
+ assert _off(warmed, 200) == {}, _off(warmed, 200)
+
+ _scim_replace_members(gateway, team, (alice,))
+
+ _refused_on_peer(peer, model, bob_key)
+ removed: Final = _observe(proxies, model, bob_key)
+ assert _off(removed, 401) == {}, _off(removed, 401)
+ kept: Final = _observe(proxies, model, alice_key)
+ assert _off(kept, 200) == {}, _off(kept, 200)
+
+ _scim_remove_member(gateway, team, alice)
+
+ _refused_on_peer(peer, model, alice_key)
+ patched_out: Final = _observe(proxies, model, alice_key)
+ assert _off(patched_out, 401) == {}, _off(patched_out, 401)
+
+
+def test_scim_removal_refuses_a_cached_response_for_the_removed_members_key(gateway: Gateway) -> None:
+ with wire_server(_upstream) as upstream, gateway.scenario() as scenario:
+ model: Final = scenario.model(api_base=upstream.url + "/v1")
+ member: Final = scenario.user(user_role="internal_user")
+ team: Final = _scim_group(gateway, scenario, (member,))
+ key: Final = _member_team_key(gateway, scenario, team, member, model)
+ marker: Final = "scim cache twin " + uuid.uuid4().hex
+ body: Final = _chat_body(model, marker)
+ first: Final = gateway.request("POST", "/v1/chat/completions", body, key=key)
+ assert first.status_code == 200, first.text
+ second: Final = gateway.request("POST", "/v1/chat/completions", body, key=key)
+ assert second.status_code == 200, second.text
+ assert second.headers.get(_CACHE_KEY_HEADER), dict(second.headers)
+ assert second.json()["id"] == first.json()["id"], (first.text, second.text)
+ received: Final = upstream.drain()
+ assert len(received) == 1 and marker.encode() in received[0].body, received
+
+ _scim_replace_members(gateway, team, ())
+
+ third: Final = gateway.request("POST", "/v1/chat/completions", body, key=key)
+ assert third.status_code == 401, third.text
+ assert "token_not_found_in_db" in third.text, third.text
+ assert upstream.drain() == (), "upstream saw a request for the removed member's key"
diff --git a/tests/integration/management/test_team_delete_prometheus.py b/tests/integration/management/test_team_delete_prometheus.py
index c5e383131f2..b93e14a0e8d 100644
--- a/tests/integration/management/test_team_delete_prometheus.py
+++ b/tests/integration/management/test_team_delete_prometheus.py
@@ -22,7 +22,7 @@ import yaml
from tests.integration._support.client import Gateway, Scenario, eventually, object_value, string_value
from tests.integration._support.database import read_rows
-from tests.integration._support.process import owned_proxy_process
+from tests.integration._support.process import graceful_stop_seconds, owned_proxy_process
METRIC: Final = "litellm_team_members_metric"
METRICS_ROUTE: Final = "/metrics/"
@@ -120,3 +120,52 @@ def test_team_members_gauge_reads_roster_size_then_zero_after_delete(gateway: Ga
seconds=30,
)
assert after == ({"team": team_id, "team_alias": alias}, 0.0), after
+
+
[email protected](2 * graceful_stop_seconds() + 120)
+def test_user_delete_moves_the_aliased_team_members_gauge(gateway: Gateway, tmp_path: Path) -> None:
+ with (
+ gateway.scenario() as scenario,
+ owned_proxy_process(
+ gateway,
+ tmp_path,
+ {"DATABASE_URL": os.environ["DATABASE_URL"]},
+ config=_prometheus_config(tmp_path),
+ remove_environment=("DATABASE_URL_READ_REPLICA",),
+ ) as owned,
+ ):
+ candidate: Final = owned.gateway
+ alias: Final = f"integration-h7-{uuid.uuid4().hex}"
+ team_id: Final = string_value(candidate.post("/team/new", {"team_alias": alias})["team_id"])
+ scenario.cleanups.callback(_delete_team_if_present, gateway, team_id)
+ leaving: Final = string_value(
+ candidate.post(
+ "/user/new",
+ {
+ "user_id": f"integration-h7-{uuid.uuid4().hex}",
+ "auto_create_key": False,
+ "user_role": "internal_user",
+ },
+ )["user_id"]
+ )
+ staying: Final = tuple(_user(candidate, scenario) for _ in range(MEMBERS - 1))
+ candidate.post(
+ "/team/member_add",
+ {"team_id": team_id, "member": [{"role": "user", "user_id": user_id} for user_id in (leaving, *staying)]},
+ )
+ before: Final = eventually(
+ lambda: _team_members_series(_scrape(candidate), team_id),
+ lambda sample: sample is not None and sample[1] == float(MEMBERS),
+ seconds=30,
+ )
+ assert before == ({"team": team_id, "team_alias": alias}, float(MEMBERS)), before
+
+ deleted: Final = candidate.request("POST", "/user/delete", {"user_ids": [leaving]})
+ assert deleted.status_code == 200, deleted.text
+
+ after: Final = eventually(
+ lambda: _team_members_series(_scrape(candidate), team_id),
+ lambda sample: sample is not None and sample[1] == float(MEMBERS - 1),
+ seconds=30,
+ )
+ assert after == ({"team": team_id, "team_alias": alias}, float(MEMBERS - 1)), after
diff --git a/tests/integration/management/test_user_delete_revokes_keys.py b/tests/integration/management/test_user_delete_revokes_keys.py
index ba1d3ca42e3..37886cd94bb 100644
--- a/tests/integration/management/test_user_delete_revokes_keys.py
+++ b/tests/integration/management/test_user_delete_revokes_keys.py
@@ -1,9 +1,11 @@
import os
import uuid
+from concurrent.futures import ThreadPoolExecutor
from hashlib import sha256
from typing import Final
import httpx
+import psycopg
import pytest
from integration._support.client import Gateway, eventually, object_value, string_value
from integration._support.database import read_rows
@@ -13,6 +15,12 @@ from litellm.models.user import LiteLLM_UserTable
from litellm.proxy.auth.auth_checks import ExperimentalUIJWTToken
+TAKE_TEAM_LOCK_SQL: Final = "SELECT pg_advisory_xact_lock(hashtext(%s))"
+SESSIONS_BLOCKED_BY_SQL: Final = (
+ "SELECT count(*)::int AS waiting FROM pg_stat_activity WHERE %s::int = ANY(pg_blocking_pids(pid))"
+)
+
+
def _observed(upstream: httpx.Client) -> list[dict[str, JsonValue]]:
response: Final = upstream.get("/__observations")
response.raise_for_status()
@@ -387,3 +395,35 @@ def test_scim_user_delete_revokes_keys(gateway: Gateway, peer: Gateway, monkeypa
assert denied_peer.json() == _blocked_key_error(), denied_peer.text
assert _observed(upstream) == []
assert _observed(upstream) == []
+
+
+def _sessions_blocked_by(backend_pid: int) -> int:
+ waiting: Final = read_rows(SESSIONS_BLOCKED_BY_SQL, (str(backend_pid),))[0]["waiting"]
+ assert isinstance(waiting, int)
+ return waiting
+
+
+def test_user_delete_deletes_a_user_whose_team_is_deleted_while_it_waits_on_the_team_lock(gateway: Gateway) -> None:
+ team_id: Final = string_value(
+ gateway.post("/team/new", {"team_alias": f"integration-{uuid.uuid4().hex}"})["team_id"]
+ )
+ user_id: Final = _new_user(gateway)
+ gateway.post("/team/member_add", {"team_id": team_id, "member": {"role": "user", "user_id": user_id}})
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ with psycopg.connect(os.environ["DATABASE_URL"]) as holder:
+ _ = holder.execute(TAKE_TEAM_LOCK_SQL, (team_id,))
+ deletion: Final = pool.submit(gateway.request, "POST", "/user/delete", {"user_ids": [user_id]})
+ _ = eventually(
+ lambda: _sessions_blocked_by(holder.info.backend_pid), lambda waiting: waiting >= 1, seconds=30
+ )
+ _ = holder.execute('DELETE FROM "LiteLLM_TeamMembership" WHERE team_id = %s', (team_id,))
+ _ = holder.execute(
+ 'UPDATE "LiteLLM_UserTable" SET teams = array_remove(teams, %s) WHERE %s = ANY(teams)',
+ (team_id, team_id),
+ )
+ _ = holder.execute('DELETE FROM "LiteLLM_TeamTable" WHERE team_id = %s', (team_id,))
+ assert not deletion.done(), deletion.result().text
+ deleted: Final = deletion.result()
+ assert deleted.status_code == 200, deleted.text
+ assert deleted.json() == 1
+ assert _user_rows(user_id)["user"] == []
diff --git a/tests/unit/proxy/auth/test_auth_checks.py b/tests/unit/proxy/auth/test_auth_checks.py
index a8c11acbb30..e1afa81d372 100644
--- a/tests/unit/proxy/auth/test_auth_checks.py
+++ b/tests/unit/proxy/auth/test_auth_checks.py
@@ -2,12 +2,14 @@
## Tests if 'get_end_user_object' works as expected
import sys, os, asyncio, time, random, uuid
+import hashlib
+import json
import traceback
from dotenv import load_dotenv
load_dotenv()
-from collections.abc import Iterator, Mapping
+from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
from copy import deepcopy
from types import SimpleNamespace
from typing import Final
@@ -34,8 +36,11 @@ from litellm.proxy._types import (
ProxyException,
)
from litellm.proxy.utils import PrismaClient
+import litellm.proxy.common_utils.auth_cache_invalidation_pubsub as pubsub_module
+from litellm.caching.in_memory_cache import InMemoryCache
from litellm.proxy.auth.auth_checks import (
can_team_access_model,
+ delete_cache_key_objects,
is_model_cost_zero,
virtual_key_soft_budget_check,
_team_soft_budget_check,
@@ -2197,3 +2202,181 @@ async def test_get_skill_names_from_access_groups_reads_cached_group_rows():
user_api_key_cache=cache,
proxy_logging_obj=MagicMock(),
) == frozenset({"skill-a", "skill-b", "shared"})
+
+
+class _Pipeline:
+ def __init__(self, send: Callable[[Sequence[str]], Awaitable[None]]) -> None:
+ self._send = send
+ self._messages: list[str] = []
+
+ def publish(self, channel: str, message: str) -> "_Pipeline":
+ self._messages.append(message)
+ return self
+
+ async def execute(self) -> None:
+ await self._send(tuple(self._messages))
+
+
+class _SlowPublishRedisClient:
+ def __init__(self) -> None:
+ self.published: list[str] = []
+
+ async def _send(self, messages: Sequence[str]) -> None:
+ await asyncio.sleep(0.001)
+ self.published.extend(messages)
+
+ async def publish(self, channel: str, message: str) -> int:
+ await self._send((message,))
+ return 1
+
+ def pipeline(self, transaction: bool = True) -> _Pipeline:
+ return _Pipeline(self._send)
+
+
+class _WedgedPublishRedisClient:
+ def __init__(self) -> None:
+ self.release = asyncio.Event()
+
+ async def _send(self, messages: Sequence[str]) -> None:
+ await self.release.wait()
+
+ async def publish(self, channel: str, message: str) -> int:
+ await self._send((message,))
+ return 1
+
+ def pipeline(self, transaction: bool = True) -> _Pipeline:
+ return _Pipeline(self._send)
+
+
+class _PubSubRedisCache:
+ namespace = None
+
+ def __init__(self, client: _SlowPublishRedisClient | _WedgedPublishRedisClient) -> None:
+ self._client = client
+
+ def init_pubsub_client(self) -> _SlowPublishRedisClient | _WedgedPublishRedisClient:
+ return self._client
+
+
+async def _drain_publishes() -> None:
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
+
+async def test_evicting_more_keys_than_the_publisher_holds_pending_broadcasts_every_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ client = _SlowPublishRedisClient()
+ hashed_tokens: Final = tuple(f"token-{index}" for index in range(pubsub_module._MAX_PENDING_PUBLISHES + 476)) # pyright: ignore[reportPrivateUsage] # the cap under test
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ await delete_cache_key_objects(
+ hashed_tokens=hashed_tokens, user_api_key_cache=UserApiKeyCache(), proxy_logging_obj=None
+ )
+ await _drain_publishes()
+
+ assert {json.loads(message)["cache_key"] for message in client.published} == set(hashed_tokens)
+
+
+async def test_bulk_eviction_clears_this_worker_before_waiting_on_a_wedged_redis(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.5)
+ client = _WedgedPublishRedisClient()
+ cache: Final = UserApiKeyCache(key_object_in_memory_cache=InMemoryCache(max_size_in_memory=2_000))
+ hashed_tokens: Final = tuple(
+ hashlib.sha256(f"token-{index}".encode()).hexdigest()
+ for index in range(600)
+ )
+ for hashed_token in hashed_tokens:
+ cache.in_memory_cache_for(hashed_token).set_cache(key=hashed_token, value={"token": hashed_token})
+ seeded: Final = tuple(
+ token for token in hashed_tokens if cache.in_memory_cache_for(token).get_cache(token) is not None
+ )
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ eviction: Final = asyncio.create_task(
+ delete_cache_key_objects(hashed_tokens=hashed_tokens, user_api_key_cache=cache, proxy_logging_obj=None)
+ )
+ await asyncio.sleep(0.05)
+ still_cached: Final = tuple(
+ token for token in seeded if cache.in_memory_cache_for(token).get_cache(token) is not None
+ )
+ client.release.set()
+ await eviction
+ await _drain_publishes()
+
+ assert seeded == hashed_tokens
+ assert still_cached == ()
+
+
+class _AuthRedisCache:
+ namespace = None
+
+ def __init__(self, entries: dict[str, object]) -> None:
+ self.entries = dict(entries)
+
+ async def async_get_cache(self, key: str, **kwargs: object) -> object | None:
+ return self.entries.get(key)
+
+ def set_cache(self, key: str, value: object, **kwargs: object) -> None:
+ self.entries[key] = value
+
+ async def async_set_cache(self, key: str, value: object, **kwargs: object) -> None:
+ self.entries[key] = value
+
+ def delete_cache(self, key: str) -> None:
+ self.entries.pop(key, None)
+
+ async def async_delete_cache(self, key: str) -> None:
+ self.entries.pop(key, None)
+
+ async def delete_cache_keys(self, keys: Sequence[str]) -> None:
+ for key in keys:
+ self.entries.pop(key, None)
+
+
+async def test_bulk_eviction_clears_the_redis_copies_before_waiting_on_a_wedged_broadcast(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.5)
+ client = _WedgedPublishRedisClient()
+ hashed_tokens: Final = tuple(
+ hashlib.sha256(f"token-{index}".encode()).hexdigest()
+ for index in range(600)
+ )
+ redis = _AuthRedisCache({token: {"token": token} for token in hashed_tokens})
+ cache: Final = UserApiKeyCache(key_object_in_memory_cache=InMemoryCache(max_size_in_memory=2_000))
+ cache.attach_redis_cache(redis) # pyright: ignore[reportArgumentType] # a dict-backed fake of the Redis layer
+ for hashed_token in hashed_tokens:
+ cache.in_memory_cache_for(hashed_token).set_cache(key=hashed_token, value={"token": hashed_token})
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ eviction: Final = asyncio.create_task(
+ delete_cache_key_objects(hashed_tokens=hashed_tokens, user_api_key_cache=cache, proxy_logging_obj=None)
+ )
+ await asyncio.sleep(0.05)
+ refilled: Final = [token for token in hashed_tokens if await cache.async_get_cache(key=token) is not None]
+ client.release.set()
+ await eviction
+ await _drain_publishes()
+
+ assert refilled == []
+ assert redis.entries == {}
diff --git a/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py b/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
index ce0e2f77e87..694b817ab86 100644
--- a/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
+++ b/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
@@ -9,15 +9,17 @@ import pytest
from redis.asyncio import Redis
import litellm.proxy.common_utils.auth_cache_invalidation_pubsub as pubsub_module
+from litellm._internal_context import current_service_target
from litellm.caching.in_memory_cache import InMemoryCache
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import (
AUTH_CACHE_INVALIDATION_CHANNEL,
AuthCacheInvalidationSubscriber,
+ broadcast_evictions,
evict_and_broadcast,
publish_auth_cache_invalidation,
)
-from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+from litellm.proxy.common_utils.user_api_key_cache import AUTH_OBJECTS_TARGET, UserApiKeyCache
class _RecordingRedisClient(Redis):
@@ -45,6 +47,46 @@ class _WedgedPublishRedisClient(Redis):
return 1
+class _SlowPublishRedisClient(Redis):
+ def __init__(self) -> None:
+ self.published: list[str] = []
+
+ async def publish(self, channel: str, message: str) -> int:
+ await asyncio.sleep(0.001)
+ self.published.append(message)
+ return 1
+
+
+class _Pipeline:
+ def __init__(self, client: "_PipelinedRedisClient") -> None:
+ self._client = client
+ self._messages: list[str] = []
+
+ def publish(self, channel: str, message: str) -> "_Pipeline":
+ self._messages.append(message)
+ return self
+
+ async def execute(self) -> None:
+ await self._client.send(tuple(self._messages))
+
+
+class _PipelinedRedisClient:
+ def __init__(self, wedged: bool = False) -> None:
+ self.published: list[str] = []
+ self.round_trips = 0
+ self.release = asyncio.Event()
+ if not wedged:
+ self.release.set()
+
+ async def send(self, messages: tuple[str, ...]) -> None:
+ self.round_trips += 1
+ await self.release.wait()
+ self.published.extend(messages)
+
+ def pipeline(self, transaction: bool = True) -> _Pipeline:
+ return _Pipeline(self)
+
+
class _FailingPublishRedisClient(Redis):
def __init__(self) -> None:
pass
@@ -53,6 +95,15 @@ class _FailingPublishRedisClient(Redis):
raise ConnectionError("redis down")
+class _TargetRecordingRedisClient(Redis):
+ def __init__(self) -> None:
+ self.targets: list[str | None] = []
+
+ async def publish(self, channel: str, message: str) -> int:
+ self.targets.append(current_service_target())
+ return 1
+
+
class _QueuePubSub:
def __init__(self, initial_messages: Iterable[object] = ()) -> None:
self.queue: asyncio.Queue[object] = asyncio.Queue()
@@ -281,3 +332,60 @@ async def test_publish_holds_at_most_sixteen_redis_connections_while_redis_is_we
await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
assert len(client.attempted) == 64
+
+
+async def test_broadcast_evictions_tells_redis_every_key_past_the_pending_publish_cap_in_one_round_trip(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ client = _PipelinedRedisClient()
+ cache_keys = tuple(f"user-{i}" for i in range(3000))
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_FakeRedisCache(client=client),
+ ):
+ await broadcast_evictions(cache_keys=cache_keys)
+
+ assert [json.loads(message)["cache_key"] for message in client.published] == list(cache_keys)
+ assert client.round_trips == 1
+
+
+async def test_broadcast_evictions_returns_within_its_bound_while_redis_never_answers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.05)
+ client = _PipelinedRedisClient(wedged=True)
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_FakeRedisCache(client=client),
+ ):
+ started = time.monotonic()
+ await broadcast_evictions(cache_keys=("user-1",))
+ waited = time.monotonic() - started
+ assert client.published == []
+ client.release.set()
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
+ assert 0.05 <= waited < 1.0
+ assert client.published == [json.dumps({"cache_key": "user-1"})]
+
+
+async def test_evict_and_broadcast_publishes_under_the_auth_objects_service_target() -> None:
+ client = _TargetRecordingRedisClient()
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_FakeRedisCache(client=client),
+ ):
+ await evict_and_broadcast(cache_keys=("user-a", "user-b"), user_api_key_cache=UserApiKeyCache())
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
+ assert client.targets == [AUTH_OBJECTS_TARGET, AUTH_OBJECTS_TARGET]
diff --git a/tests/unit/proxy/management_endpoints/scim/test_scim_key_deactivation.py b/tests/unit/proxy/management_endpoints/scim/test_scim_key_deactivation.py
index 0c3600cbcc7..1a43980bc2d 100644
--- a/tests/unit/proxy/management_endpoints/scim/test_scim_key_deactivation.py
+++ b/tests/unit/proxy/management_endpoints/scim/test_scim_key_deactivation.py
@@ -5,6 +5,8 @@ When a SCIM provider deprovisions a user (DELETE) or marks them inactive
working immediately. Reactivating (active=True) must un-block them.
"""
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -38,12 +40,22 @@ def _build_prisma_with_keys(user_keys, mock_user=None, updated_user=None):
mock_client = MagicMock()
mock_db = MagicMock()
mock_client.db = mock_db
+
+ @asynccontextmanager
+ async def tx(*, timeout: object = None) -> AsyncIterator[MagicMock]:
+ yield mock_db
+
+ mock_client.tx = tx
+ mock_db.query_raw = AsyncMock(return_value=[])
if mock_user is not None:
mock_db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user)
+ mock_db.litellm_usertable.find_many = AsyncMock(return_value=[mock_user] if mock_user is not None else [])
if updated_user is not None:
mock_db.litellm_usertable.update = AsyncMock(return_value=updated_user)
- mock_db.litellm_usertable.delete = AsyncMock(return_value=None)
+ mock_db.litellm_usertable.delete_many = AsyncMock(return_value=1)
mock_db.litellm_teamtable.find_unique = AsyncMock(return_value=None)
+ mock_db.litellm_teamtable.find_many = AsyncMock(return_value=[])
+ mock_db.litellm_teammembership.find_many = AsyncMock(return_value=[])
mock_db.litellm_verificationtoken.find_many = AsyncMock(return_value=user_keys)
mock_db.litellm_verificationtoken.update_many = AsyncMock(return_value=None)
@@ -184,8 +196,8 @@ async def test_scim_delete_user_blocks_keys_before_deleting_user():
assert update_kwargs["where"] == {"token": "hash-a"}
assert update_kwargs["data"]["blocked"] is True
assert '"scim_blocked": true' in update_kwargs["data"]["metadata"]
- mock_db.litellm_usertable.delete.assert_awaited_once_with(
- where={"user_id": user_id}
+ mock_db.litellm_usertable.delete_many.assert_awaited_once_with(
+ where={"user_id": {"in": [user_id]}}
)
@@ -211,8 +223,8 @@ async def test_scim_delete_user_clears_fk_referenced_rows_before_user_delete():
mock_db.litellm_teammembership.delete_many = AsyncMock(
side_effect=lambda **kw: call_order.append(("teammembership", kw)) or None
)
- mock_db.litellm_usertable.delete = AsyncMock(
- side_effect=lambda **kw: call_order.append(("user", kw)) or None
+ mock_db.litellm_usertable.delete_many = AsyncMock(
+ side_effect=lambda **kw: call_order.append(("user", kw)) or 1
)
with (
@@ -232,18 +244,18 @@ async def test_scim_delete_user_clears_fk_referenced_rows_before_user_delete():
inv_kwargs = mock_db.litellm_invitationlink.delete_many.await_args.kwargs
assert inv_kwargs == {
"where": {
- "OR": [
- {"user_id": user_id},
- {"created_by": user_id},
- {"updated_by": user_id},
- ]
+ "OR": (
+ {"user_id": {"in": [user_id]}},
+ {"created_by": {"in": [user_id]}},
+ {"updated_by": {"in": [user_id]}},
+ )
}
}
mock_db.litellm_organizationmembership.delete_many.assert_awaited_once_with(
- where={"user_id": user_id}
+ where={"user_id": {"in": [user_id]}}
)
mock_db.litellm_teammembership.delete_many.assert_awaited_once_with(
- where={"user_id": user_id}
+ where={"user_id": {"in": [user_id]}}
)
stages = [stage for stage, _ in call_order]
@@ -615,7 +627,7 @@ async def test_scim_delete_user_evicts_cached_user_row(failure: str | None) -> N
saved: Final = LiteLLM_UserTable(user_id=user_id, user_email="[email protected]", teams=[], metadata={})
client, db = _build_prisma_with_keys([], mock_user=saved.model_copy(deep=True))
if failure == "delete":
- db.litellm_usertable.delete.side_effect = RuntimeError("user delete failed")
+ db.litellm_usertable.delete_many.side_effect = RuntimeError("user delete failed")
cache: Final = UserApiKeyCache()
await cache.async_set_cache(key=user_id, value=saved, model_type=LiteLLM_UserTable)
with (
diff --git a/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py b/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
index 85b3baed01d..8fccba4d76d 100644
--- a/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
@@ -1,12 +1,13 @@
+from contextlib import asynccontextmanager
+import asyncio
import json
import logging
import time
from collections.abc import Callable, Mapping, Sequence
from itertools import chain
from types import MappingProxyType
-from typing import Final
-from unittest.mock import AsyncMock, MagicMock
-from unittest.mock import call as mock_call
+from typing import Final, assert_never
+from unittest.mock import ANY, AsyncMock, MagicMock, call
import pytest
from fastapi import FastAPI, HTTPException
@@ -19,6 +20,7 @@ from litellm.proxy._types import (
LiteLLM_UserTable,
LitellmUserRoles,
Member,
+ NewTeamRequest,
NewUserRequest,
NewUserResponse,
ProxyErrorTypes,
@@ -33,7 +35,6 @@ from litellm.proxy.management_endpoints.scim.scim_v2 import (
_create_user_if_not_exists,
_extract_group_member_ids,
_extract_ids_from_path_filter,
- _handle_group_membership_changes,
_handle_team_membership_changes,
_member_ids_to_drop,
_parse_member_entries,
@@ -57,6 +58,15 @@ from litellm.proxy.management_endpoints.scim.scim_v2 import (
update_user,
user_api_key_auth,
)
+from litellm.proxy.management_helpers.bulk_user_creation import BULK_NEW_USER_CONCURRENCY
+from litellm.proxy.management_helpers.team_roster_sync import (
+ MembersMissing,
+ RosterDelta,
+ RosterPlan,
+ RosterSync,
+ RosterTarget,
+ TeamGone,
+)
from litellm.types.proxy.management_endpoints.scim_v2 import (
SCIM_ENTERPRISE_USER_SCHEMA,
SCIM_MANAGED_TEAM_METADATA_KEY,
@@ -73,6 +83,49 @@ from litellm.types.proxy.management_endpoints.scim_v2 import (
SCIMUserName,
)
+_SYNC_GROUP_ROSTER: Final = "litellm.proxy.management_endpoints.scim.scim_v2._sync_group_roster"
+
+
+def _created_team(team_id: str | None) -> dict[str, object]:
+ """What ``new_team`` answers for a group created with no members."""
+ assert team_id is not None
+ return LiteLLM_TeamTable(team_id=team_id, members_with_roles=[]).model_dump()
+
+
+def _stub_roster_sync(mocker: MockerFixture, team: LiteLLM_TeamTable | None = None) -> AsyncMock:
+ """Stand in for the bulk roster write: apply the plan to ``team`` (else to the row the
+ prisma mock answers for the group, else to an empty roster) and report the diff, so an
+ endpoint test asserts the plan the endpoint decided on while the write itself is
+ covered by ``test_team_roster_sync.py``."""
+
+ async def current(group_id: str, prisma_client: MagicMock) -> LiteLLM_TeamTable:
+ if team is not None:
+ return team
+ row = await prisma_client.db.litellm_teamtable.find_unique(where={"team_id": group_id})
+ if isinstance(row, LiteLLM_TeamTable):
+ return row
+ return LiteLLM_TeamTable(team_id=group_id, members_with_roles=[])
+
+ def diff(plan: RosterPlan, roster: frozenset[str]) -> tuple[frozenset[str], frozenset[str]]:
+ match plan:
+ case RosterTarget(member_ids=target):
+ return target - roster, roster - target
+ case RosterDelta(add=add, remove=remove):
+ return add - roster, remove & roster
+ case _:
+ assert_never(plan)
+
+ async def sync(group_id: str, plan: RosterPlan, created_via: str, prisma_client: MagicMock) -> RosterSync:
+ base = await current(group_id, prisma_client)
+ roster = frozenset(member.user_id for member in base.members_with_roles if member.user_id is not None)
+ added, removed = diff(plan, roster)
+ kept = [member for member in base.members_with_roles if member.user_id not in removed]
+ joined = [Member(user_id=user_id, role="user") for user_id in sorted(added)]
+ after = base.model_copy(update={"members_with_roles": [*kept, *joined]})
+ return RosterSync(team=after, added=added, removed=removed)
+
+ return mocker.patch(_SYNC_GROUP_ROSTER, AsyncMock(side_effect=sync))
+
@pytest.mark.asyncio
async def test_create_user_existing_user_conflict(mocker):
@@ -1629,7 +1682,7 @@ async def test_update_group_metadata_serialization_issue(mocker):
mock_user.user_email = "[email protected]" # Add proper string value for user_email
mock_user.teams = [group_id]
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user)
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=(mock_user,))
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=mock_user)
# Mock the _get_prisma_client_or_raise_exception to return our mock
@@ -1638,8 +1691,9 @@ async def test_update_group_metadata_serialization_issue(mocker):
AsyncMock(return_value=mock_prisma_client),
)
+ _stub_roster_sync(mocker)
mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
+ "litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
@@ -1654,10 +1708,6 @@ async def test_update_group_metadata_serialization_issue(mocker):
"litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
AsyncMock(return_value=mock_scim_group_response),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
# Call the function that had the bug
await update_group(group_id=group_id, group=scim_group)
@@ -1687,16 +1737,10 @@ async def test_update_group_metadata_serialization_issue(mocker):
@pytest.mark.asyncio
async def test_team_membership_management(mocker):
- """
- Test that team membership changes work correctly:
- - Adding members to team
- - Removing members from team
- - members_with_roles is used as source of truth
- """
+ """members_with_roles is the source of truth for a team's member ids."""
from litellm.proxy._types import Member
from litellm.proxy.management_endpoints.scim.scim_v2 import (
_get_team_member_user_ids_from_team,
- _handle_group_membership_changes,
)
# Mock team with members_with_roles as source of truth
@@ -1712,54 +1756,6 @@ async def test_team_membership_management(mocker):
assert set(member_ids) == {"user1", "user2"}
assert "user3" not in member_ids # Should not be included even though in members
- # Mock patch_team_membership function
- mock_patch_team_membership = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
-
- # Test adding and removing members
- group_id = "test-group-id"
- current_members = {"user1", "user2"}
- final_members = {"user2", "user3", "user4"} # Remove user1, add user3 and user4
-
- await _handle_group_membership_changes(
- group_id=group_id, current_members=current_members, final_members=final_members
- )
-
- # Verify patch_team_membership was called correctly
- assert mock_patch_team_membership.call_count == 3
-
- # Check calls for adding members
- add_calls = [
- call for call in mock_patch_team_membership.call_args_list if call[1]["teams_ids_to_add_user_to"] == [group_id]
- ]
- assert len(add_calls) == 2 # user3 and user4
-
- add_user_ids = {call[1]["user_id"] for call in add_calls}
- assert add_user_ids == {"user3", "user4"}
-
- # Check calls for removing members
- remove_calls = [
- call
- for call in mock_patch_team_membership.call_args_list
- if call[1]["teams_ids_to_remove_user_from"] == [group_id]
- ]
- assert len(remove_calls) == 1 # user1
-
- remove_user_ids = {call[1]["user_id"] for call in remove_calls}
- assert remove_user_ids == {"user1"}
-
- # Verify all calls have correct structure
- for call in mock_patch_team_membership.call_args_list:
- assert "user_id" in call[1]
- assert "teams_ids_to_add_user_to" in call[1]
- assert "teams_ids_to_remove_user_from" in call[1]
- # Each call should either add OR remove, not both
- add_teams = call[1]["teams_ids_to_add_user_to"]
- remove_teams = call[1]["teams_ids_to_remove_user_from"]
- assert (len(add_teams) > 0) != (len(remove_teams) > 0) # XOR - one should be empty
-
@pytest.mark.asyncio
async def test_update_group_e2e(mocker):
@@ -1828,12 +1824,13 @@ async def test_update_group_e2e(mocker):
},
)
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated_team)
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(side_effect=[existing_team, updated_team])
# Mock user validation (all users exist)
mock_user = mocker.MagicMock()
mock_users: Final = tuple(LiteLLM_UserTable(user_id=user_id) for user_id in ("user2", "user3", "user4"))
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user)
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=mock_users)
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
# Mock dependencies
mocker.patch(
@@ -1841,9 +1838,9 @@ async def test_update_group_e2e(mocker):
AsyncMock(return_value=mock_prisma_client),
)
- # Mock patch_team_membership to track membership changes
- mock_patch_team_membership = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
+ sync_mock = _stub_roster_sync(mocker)
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
@@ -1885,27 +1882,14 @@ async def test_update_group_e2e(mocker):
assert "scim_data" in metadata
assert metadata["scim_data"]["displayName"] == "Updated Team Name"
- # Verify team membership changes were handled correctly
- assert mock_patch_team_membership.call_count == 3 # Remove user1, add user3, add user4
-
- # Check membership changes
- call_args_list = mock_patch_team_membership.call_args_list
-
- # Find remove operation (user1)
- remove_calls = [call for call in call_args_list if call[1]["teams_ids_to_remove_user_from"] == [group_id]]
- assert len(remove_calls) == 1
- assert remove_calls[0][1]["user_id"] == "user1"
- assert remove_calls[0][1]["teams_ids_to_add_user_to"] == []
-
- # Find add operations (user3, user4)
- add_calls = [call for call in call_args_list if call[1]["teams_ids_to_add_user_to"] == [group_id]]
- assert len(add_calls) == 2
- add_user_ids = {call[1]["user_id"] for call in add_calls}
- assert add_user_ids == {"user3", "user4"}
-
- # Verify all add calls have empty remove lists
- for call in add_calls:
- assert call[1]["teams_ids_to_remove_user_from"] == []
+ assert sync_mock.await_args_list == [
+ call(
+ group_id,
+ RosterTarget(member_ids=frozenset({"user2", "user3", "user4"})),
+ "scim_group_membership",
+ mock_prisma_client,
+ )
+ ]
# Verify the response
assert result.id == group_id
@@ -1921,7 +1905,7 @@ def _rows_by_exact_id(
) -> Callable[..., tuple[LiteLLM_UserTable | MagicMock, ...]]:
"""``find_many`` stand-in for a table where members match only exact user ids."""
- def rows(where: Mapping[str, object], take: int | None = None) -> tuple[LiteLLM_UserTable | MagicMock, ...]:
+ def rows(where: Mapping[str, object], take: int | None = None) -> tuple[LiteLLM_UserTable, ...]:
clauses: Final = where["OR"]
assert isinstance(clauses, list)
fields: Final = tuple(next(iter(clause)) for clause in clauses)
@@ -2170,6 +2154,12 @@ async def test_create_group_with_nonexistent_users_creates_when_flag_true(mocker
AsyncMock(return_value=mock_team),
)
+ _stub_roster_sync(mocker)
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
+ AsyncMock(),
+ )
+
# Mock transformation
mock_scim_group = SCIMGroup(
schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
@@ -2842,8 +2832,9 @@ async def test_patch_user_grants_admin_by_team_display_name(mocker, monkeypatch)
def _scim_admin_prisma(mocker, *, user_teams):
- """Prisma double whose user resolves to user_teams and whose teams expose an
- alias equal to their id, used by the role-recompute helper tests."""
+ """Prisma double and its one transaction, in which the user resolves to user_teams
+ and teams expose an alias equal to their id. Only the transaction answers reads,
+ so a role written outside it fails the role-recompute helper tests."""
user = mocker.MagicMock()
user.user_id = "member-1"
user.teams = user_teams
@@ -2853,15 +2844,26 @@ def _scim_admin_prisma(mocker, *, user_teams):
team.team_alias = where["team_id"]
return team
+ def _teams_find_many(where):
+ return tuple(_team_find_unique({"team_id": team_id}) for team_id in where["team_id"]["in"])
+
+ def _users_find_many(where):
+ return (user,) if user.user_id in where["user_id"]["in"] else ()
+
+ tx = mocker.MagicMock()
+ tx.query_raw = AsyncMock(return_value=[])
+ tx.execute_raw = AsyncMock(return_value=1)
+ tx.litellm_usertable.find_many = AsyncMock(side_effect=_users_find_many)
+ tx.litellm_usertable.update = AsyncMock(return_value=user)
+ tx.litellm_teamtable.find_many = AsyncMock(side_effect=_teams_find_many)
+
+ @asynccontextmanager
+ async def _tx(timeout=None):
+ yield tx
+
prisma = mocker.MagicMock()
- prisma.db = mocker.MagicMock()
- prisma.db.litellm_usertable = mocker.MagicMock()
- prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=user)
- prisma.db.litellm_usertable.find_many = AsyncMock(return_value=())
- prisma.db.litellm_usertable.update = AsyncMock(return_value=user)
- prisma.db.litellm_teamtable = mocker.MagicMock()
- prisma.db.litellm_teamtable.find_unique = AsyncMock(side_effect=_team_find_unique)
- return prisma
+ prisma.tx = _tx
+ return prisma, tx
@pytest.mark.asyncio
@@ -2876,12 +2878,11 @@ async def test_recompute_scim_member_roles_demotes_when_not_in_admin_group(mocke
monkeypatch.setattr(proxy_config, "get_config", mock_get_config)
monkeypatch.setattr("litellm.default_internal_user_params", None, raising=False)
- prisma = _scim_admin_prisma(mocker, user_teams=["engineering"])
+ prisma, tx = _scim_admin_prisma(mocker, user_teams=["engineering"])
await _recompute_scim_member_roles(prisma, ["member-1"])
- call_args = prisma.db.litellm_usertable.update.call_args
- assert call_args[1]["data"]["user_role"] == LitellmUserRoles.INTERNAL_USER_VIEW_ONLY
+ tx.execute_raw.assert_awaited_once_with(ANY, LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, ["member-1"])
@pytest.mark.asyncio
@@ -2896,12 +2897,11 @@ async def test_recompute_scim_member_roles_grants_when_in_admin_group(mocker, mo
monkeypatch.setattr(proxy_config, "get_config", mock_get_config)
monkeypatch.setattr("litellm.default_internal_user_params", None, raising=False)
- prisma = _scim_admin_prisma(mocker, user_teams=["litellm-admins"])
+ prisma, tx = _scim_admin_prisma(mocker, user_teams=["litellm-admins"])
await _recompute_scim_member_roles(prisma, ["member-1"])
- call_args = prisma.db.litellm_usertable.update.call_args
- assert call_args[1]["data"]["user_role"] == LitellmUserRoles.PROXY_ADMIN
+ tx.execute_raw.assert_awaited_once_with(ANY, LitellmUserRoles.PROXY_ADMIN, ["member-1"])
@pytest.mark.asyncio
@@ -2915,11 +2915,12 @@ async def test_recompute_scim_member_roles_noop_when_admin_group_unset(mocker, m
monkeypatch.setattr(proxy_config, "get_config", mock_get_config)
- prisma = _scim_admin_prisma(mocker, user_teams=["litellm-admins"])
+ prisma, tx = _scim_admin_prisma(mocker, user_teams=["litellm-admins"])
await _recompute_scim_member_roles(prisma, ["member-1"])
- prisma.db.litellm_usertable.update.assert_not_called()
+ tx.execute_raw.assert_not_called()
+ tx.litellm_usertable.update.assert_not_called()
@pytest.mark.asyncio
@@ -2957,18 +2958,13 @@ async def test_update_group_recomputes_roles_for_changed_members(mocker):
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
- return_value=tuple(LiteLLM_UserTable(user_id=user_id) for user_id in ("user2", "user3"))
- )
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, existing_team)
recompute_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -3018,18 +3014,13 @@ async def test_patch_group_recomputes_roles_for_changed_members(mocker):
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
- return_value=(LiteLLM_UserTable(user_id="user1"), LiteLLM_UserTable(user_id="user2"))
- )
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, existing_team)
recompute_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -3249,9 +3240,7 @@ async def test_create_group_recomputes_roles_for_members(mocker):
mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=())
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
- return_value=(LiteLLM_UserTable(user_id="user1"), LiteLLM_UserTable(user_id="user2"))
- )
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
@@ -3259,8 +3248,9 @@ async def test_create_group_recomputes_roles_for_members(mocker):
)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.new_team",
- AsyncMock(return_value=mocker.MagicMock()),
+ AsyncMock(return_value=_created_team(scim_group.id)),
)
+ _stub_roster_sync(mocker)
recompute_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -3310,16 +3300,13 @@ async def test_update_group_rename_recomputes_retained_members(mocker):
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=(LiteLLM_UserTable(user_id="user1"),))
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, existing_team)
recompute_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -3366,18 +3353,13 @@ async def test_patch_group_rename_recomputes_retained_members(mocker):
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
- return_value=(LiteLLM_UserTable(user_id="user1"), LiteLLM_UserTable(user_id="user2"))
- )
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, existing_team)
recompute_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -3503,10 +3485,9 @@ async def test_get_groups_reports_members_from_members_with_roles(mocker):
mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[team])
mock_prisma_client.db.litellm_teamtable.count = AsyncMock(return_value=1)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
- mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
- return_value=mocker.MagicMock(user_id="member-1", user_email="[email protected]")
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
+ return_value=(mocker.MagicMock(user_id="member-1", user_email="[email protected]"),)
)
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=())
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
@@ -3519,31 +3500,59 @@ async def test_get_groups_reports_members_from_members_with_roles(mocker):
@pytest.mark.asyncio
-async def test_apply_group_patch_updates_does_not_write_legacy_members(mocker):
+async def test_apply_group_patch_updates_writes_only_the_patched_columns_and_evicts_the_cached_team(mocker):
"""The group PATCH apply must not write the legacy ``members`` column.
Membership is reconciled onto the source of truth (members_with_roles and
each member's user.teams) separately; writing the legacy column here too
would create a second, unread copy of membership that can drift from the
- source of truth, which is the inconsistency this PR removes.
+ source of truth, which is the inconsistency this PR removes. The write also
+ evicts the team cached under its id and its old alias, so a rename-only PATCH
+ is not served from the stale copy until its TTL expires.
"""
+ from litellm.proxy import proxy_server
+
mock_prisma_client = mocker.MagicMock()
mock_prisma_client.db = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
updated = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated)
+ proxy_server.user_api_key_cache.set_cache(key="team_id:team-1", value={"team_id": "team-1"})
+ proxy_server.user_api_key_cache.set_cache(key="team_alias:Old", value={"team_id": "team-1"})
result = await _apply_group_patch_updates(
group_id="team-1",
update_data={"team_alias": "Renamed"},
prisma_client=mock_prisma_client,
+ team_alias="Old",
)
assert result is updated
mock_prisma_client.db.litellm_teamtable.update.assert_awaited_once()
- written = mock_prisma_client.db.litellm_teamtable.update.call_args.kwargs["data"]
- assert "members" not in written
- assert written["team_alias"] == "Renamed"
+ assert mock_prisma_client.db.litellm_teamtable.update.await_args.kwargs["data"] == {"team_alias": "Renamed"}
+ assert proxy_server.user_api_key_cache.get_cache("team_id:team-1") is None
+ assert proxy_server.user_api_key_cache.get_cache("team_alias:Old") is None
+
+
+async def test_apply_group_patch_updates_with_nothing_to_write_reads_the_team_and_keeps_its_cache(mocker):
+ from litellm.proxy import proxy_server
+
+ mock_prisma_client = mocker.MagicMock()
+ mock_prisma_client.db = mocker.MagicMock()
+ mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
+ existing = mocker.MagicMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock()
+ proxy_server.user_api_key_cache.set_cache(key="team_id:team-2", value={"team_id": "team-2"})
+
+ result = await _apply_group_patch_updates(
+ group_id="team-2", update_data={}, prisma_client=mock_prisma_client, team_alias="Kept"
+ )
+
+ assert result is existing
+ mock_prisma_client.db.litellm_teamtable.update.assert_not_awaited()
+ assert proxy_server.user_api_key_cache.get_cache("team_id:team-2") is not None
def _mock_prisma_for_delete_user(mocker, team):
@@ -3552,12 +3561,10 @@ def _mock_prisma_for_delete_user(mocker, team):
mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team)
mock_prisma_client.db.litellm_teamtable.update = AsyncMock()
- mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
- mock_prisma_client.db.litellm_usertable.delete = AsyncMock()
return mock_prisma_client
-def _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user):
+def _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user) -> AsyncMock:
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
@@ -3570,9 +3577,11 @@ def _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user):
"litellm.proxy.management_endpoints.scim.scim_v2._set_user_keys_blocked",
AsyncMock(),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2._delete_rows_referencing_user",
- AsyncMock(),
+ return (
+ mocker.patch( # test-quality-ok: the locked user row delete is module-level, not injectable into the endpoint
+ "litellm.proxy.management_endpoints.scim.scim_v2.delete_users_from_current_teams",
+ AsyncMock(return_value=1),
+ )
)
@@ -3594,7 +3603,7 @@ async def test_delete_user_prunes_members_with_roles(mocker):
)
mock_prisma_client = _mock_prisma_for_delete_user(mocker, team)
- _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
+ delete_rows_mock = _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
team_member_delete_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.team_member_delete",
AsyncMock(),
@@ -3607,7 +3616,7 @@ async def test_delete_user_prunes_members_with_roles(mocker):
assert call.kwargs["data"].team_id == "team-1"
assert call.kwargs["data"].user_id == user_id
assert call.kwargs["user_api_key_dict"].user_role == LitellmUserRoles.PROXY_ADMIN
- mock_prisma_client.db.litellm_usertable.delete.assert_awaited_once()
+ assert delete_rows_mock.await_args.kwargs["user_ids"] == (user_id,)
@pytest.mark.asyncio
@@ -3628,7 +3637,7 @@ async def test_delete_user_surfaces_prune_failure_and_keeps_user(mocker):
)
mock_prisma_client = _mock_prisma_for_delete_user(mocker, team)
- _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
+ delete_rows_mock = _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.team_member_delete",
AsyncMock(side_effect=Exception("database connection lost")),
@@ -3637,7 +3646,7 @@ async def test_delete_user_surfaces_prune_failure_and_keeps_user(mocker):
with pytest.raises(ProxyException):
await delete_user(user_id=user_id)
- mock_prisma_client.db.litellm_usertable.delete.assert_not_awaited()
+ delete_rows_mock.assert_not_awaited()
@pytest.mark.asyncio
@@ -3657,7 +3666,7 @@ async def test_delete_user_skips_teams_where_not_a_member(mocker):
)
mock_prisma_client = _mock_prisma_for_delete_user(mocker, team)
- _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
+ delete_rows_mock = _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
team_member_delete_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.team_member_delete",
AsyncMock(),
@@ -3666,53 +3675,43 @@ async def test_delete_user_skips_teams_where_not_a_member(mocker):
await delete_user(user_id=user_id)
team_member_delete_mock.assert_not_awaited()
- mock_prisma_client.db.litellm_usertable.delete.assert_awaited_once()
+ delete_rows_mock.assert_awaited_once()
@pytest.mark.asyncio
-async def test_patch_group_add_applies_delta_and_keeps_concurrent_add(mocker):
- """A group PATCH op:add must be applied as a delta against the live roster,
- not as a snapshot-based absolute target.
-
- When a concurrent PATCH has already added a member between this request's
- initial read and its post-write refresh, that member shows up in the
- refreshed roster but not in this request's snapshot-derived target. Diffing
- the refreshed roster against the snapshot target would issue a spurious
- team_member_delete for the concurrently-added member. Applying only this
- request's intended delta on top of the refreshed roster must retain them.
- """
- from litellm.proxy.management_endpoints.scim.scim_transformations import (
- ScimTransformations,
- )
+async def test_delete_user_answers_500_so_the_idp_retries_when_pushes_keep_moving_the_user(mocker):
+ """When group pushes keep adding the user to new teams while the delete waits on their row,
+ the locked delete gives up without deleting anything, and the endpoint must say so with a 5xx
+ rather than a 204 the IdP would never retry."""
+ existing_user = mocker.MagicMock()
+ existing_user.teams = []
+ mock_prisma_client = _mock_prisma_for_delete_user(mocker, None)
+ delete_rows_mock = _patch_delete_user_dependencies(mocker, mock_prisma_client, existing_user)
+ delete_rows_mock.return_value = "the users' teams kept changing while they were being deleted, try again"
- group_id = "team-concurrent"
+ with pytest.raises(ProxyException) as exc_info:
+ await delete_user(user_id="scim-del-user")
+
+ assert int(exc_info.value.code) == 500
+ assert "kept changing" in str(exc_info.value.message)
+
+async def test_patch_group_add_applies_delta_and_keeps_concurrent_add(mocker):
+ """A group PATCH ``op: add`` is a delta against the live roster, never a snapshot-based
+ absolute target. The roster write enrolls exactly the members this request named on
+ top of whatever the roster holds when it takes the lock, so a member a concurrent
+ request added between this request's read and its write is kept, not deleted."""
+ group_id = "team-concurrent"
snapshot_team = LiteLLM_TeamTable(
team_id=group_id,
team_alias="Group",
members_with_roles=[Member(user_id="zed", role="user")],
metadata={"externalId": "grp-ext"},
)
- refreshed_team = LiteLLM_TeamTable(
- team_id=group_id,
- team_alias="Group",
- members_with_roles=[
- Member(user_id="zed", role="user"),
- Member(user_id="alice", role="user"),
- ],
- metadata={"externalId": "grp-ext"},
+ live_team = snapshot_team.model_copy(
+ update={"members_with_roles": [Member(user_id="zed", role="user"), Member(user_id="carol", role="user")]}
)
- final_team = LiteLLM_TeamTable(
- team_id=group_id,
- team_alias="Group",
- members_with_roles=[
- Member(user_id="zed", role="user"),
- Member(user_id="alice", role="user"),
- Member(user_id="bob", role="user"),
- ],
- metadata={"externalId": "grp-ext"},
- )
-
patch_ops = SCIMPatchOp(
schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
Operations=[SCIMPatchOperation(op="add", path="members", value=[{"value": "bob"}])],
@@ -3721,10 +3720,8 @@ async def test_patch_group_add_applies_delta_and_keeps_concurrent_add(mocker):
mock_prisma_client = mocker.MagicMock()
mock_prisma_client.db = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
- mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
- side_effect=[snapshot_team, refreshed_team, final_team]
- )
- mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=final_team)
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=snapshot_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=snapshot_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
@@ -3732,80 +3729,34 @@ async def test_patch_group_add_applies_delta_and_keeps_concurrent_add(mocker):
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- patch_membership_mock = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, live_team)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
- mocker.patch.object(
- ScimTransformations,
- "transform_litellm_team_to_scim_group",
- AsyncMock(
- return_value=SCIMGroup(
- schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
- id=group_id,
- displayName="Group",
- )
- ),
- )
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
- await patch_group(group_id=group_id, patch_ops=patch_ops)
+ group = await patch_group(group_id=group_id, patch_ops=patch_ops)
- calls = patch_membership_mock.call_args_list
-
- removed_user_ids = {
- call.kwargs["user_id"] for call in calls if call.kwargs.get("teams_ids_to_remove_user_from") == [group_id]
- }
- assert removed_user_ids == set()
-
- added_user_ids = {
- call.kwargs["user_id"] for call in calls if call.kwargs.get("teams_ids_to_add_user_to") == [group_id]
- }
- assert added_user_ids == {"bob"}
+ assert sorted(member.value for member in group.members or []) == ["bob", "carol", "zed"]
@pytest.mark.asyncio
async def test_patch_group_replace_stays_absolute_against_concurrent_roster(mocker):
- """A group PATCH ``replace`` op declares the roster is exactly the given set,
- so it must reconcile as a set-to-target, not as a delta.
-
- Unlike ``add``/``remove``, ``replace`` is absolute. A member that another
- request added concurrently is present in the refreshed roster but not in the
- replace target, and ``replace`` must drop it. Rebasing the replace onto the
- refreshed roster (the delta behavior correct only for add/remove) would
- wrongly retain that concurrently-added member.
- """
- from litellm.proxy.management_endpoints.scim.scim_transformations import (
- ScimTransformations,
- )
-
+ """A group PATCH ``replace`` declares the roster is exactly the given set, so it is
+ planned as a target, never as a delta. A member another request added concurrently
+ is dropped by the roster write, where a delta rebased onto the live roster would
+ wrongly keep it."""
group_id = "team-replace-concurrent"
-
snapshot_team = LiteLLM_TeamTable(
team_id=group_id,
team_alias="Group",
members_with_roles=[Member(user_id="zed", role="user")],
metadata={"externalId": "grp-ext"},
)
- refreshed_team = LiteLLM_TeamTable(
- team_id=group_id,
- team_alias="Group",
- members_with_roles=[
- Member(user_id="alice", role="user"),
- Member(user_id="bob", role="user"),
- ],
- metadata={"externalId": "grp-ext"},
- )
- final_team = LiteLLM_TeamTable(
- team_id=group_id,
- team_alias="Group",
- members_with_roles=[Member(user_id="alice", role="user")],
- metadata={"externalId": "grp-ext"},
+ live_team = snapshot_team.model_copy(
+ update={"members_with_roles": [Member(user_id="zed", role="user"), Member(user_id="carol", role="user")]}
)
-
patch_ops = SCIMPatchOp(
schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
Operations=[SCIMPatchOperation(op="replace", path="members", value=[{"value": "alice"}])],
@@ -3814,10 +3765,8 @@ async def test_patch_group_replace_stays_absolute_against_concurrent_roster(mock
mock_prisma_client = mocker.MagicMock()
mock_prisma_client.db = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
- mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
- side_effect=[snapshot_team, refreshed_team, final_team]
- )
- mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=final_team)
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=snapshot_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=snapshot_team)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
@@ -3825,39 +3774,16 @@ async def test_patch_group_replace_stays_absolute_against_concurrent_roster(mock
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
- patch_membership_mock = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, live_team)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
- mocker.patch.object(
- ScimTransformations,
- "transform_litellm_team_to_scim_group",
- AsyncMock(
- return_value=SCIMGroup(
- schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
- id=group_id,
- displayName="Group",
- )
- ),
- )
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
- await patch_group(group_id=group_id, patch_ops=patch_ops)
+ group = await patch_group(group_id=group_id, patch_ops=patch_ops)
- calls = patch_membership_mock.call_args_list
-
- removed_user_ids = {
- call.kwargs["user_id"] for call in calls if call.kwargs.get("teams_ids_to_remove_user_from") == [group_id]
- }
- assert removed_user_ids == {"bob"}
-
- added_user_ids = {
- call.kwargs["user_id"] for call in calls if call.kwargs.get("teams_ids_to_add_user_to") == [group_id]
- }
- assert added_user_ids == set()
+ assert [member.value for member in group.members or []] == ["alice"]
@pytest.mark.parametrize(
@@ -4156,8 +4082,9 @@ async def test_create_group_ignores_nested_group_members(mocker, scim_upsert_use
)
new_team_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.new_team",
- AsyncMock(return_value=mocker.MagicMock()),
+ AsyncMock(return_value=_created_team(scim_group.id)),
)
+ sync_mock = _stub_roster_sync(mocker)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
AsyncMock(return_value=scim_group),
@@ -4170,7 +4097,8 @@ async def test_create_group_ignores_nested_group_members(mocker, scim_upsert_use
await create_group(group=scim_group)
create_user_mock.assert_not_called()
- assert new_team_mock.call_args.kwargs["data"].members_with_roles == [Member(user_id="real-user", role="user")]
+ assert new_team_mock.call_args.kwargs["data"].members_with_roles == []
+ assert sync_mock.await_args.args[1] == RosterDelta(add=frozenset({"real-user"}), remove=frozenset())
@pytest.mark.asyncio
@@ -4210,24 +4138,17 @@ async def test_update_group_ignores_nested_group_members(mocker, scim_upsert_use
"litellm.proxy.management_endpoints.scim.scim_v2._create_user_if_not_exists",
AsyncMock(return_value=NewUserResponse(user_id="phantom-user", key="phantom-key")),
)
- patch_membership_mock = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership",
- AsyncMock(),
- )
+ _stub_roster_sync(mocker, existing_team)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
- AsyncMock(return_value=scim_group),
- )
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", prisma_client)
- await update_group(group_id=group_id, group=scim_group)
+ response = await update_group(group_id=group_id, group=scim_group)
create_user_mock.assert_not_called()
- enrolled = {call.kwargs["user_id"] for call in patch_membership_mock.call_args_list}
- assert enrolled == {"real-user"}
+ assert [member.value for member in response.members or []] == ["real-user"]
@pytest.mark.asyncio
@@ -4269,6 +4190,85 @@ async def test_process_group_patch_operations_ignores_nested_group_members(mocke
assert final_members == {"incumbent", "real-user"}
+async def test_unprovisioned_group_members_are_created_concurrently_up_to_the_bulk_limit(
+ mocker, scim_upsert_user_enabled
+):
+ in_flight = 0
+ peak = 0
+
+ async def create_user(user_id: str, created_via: str = "scim_group") -> NewUserResponse:
+ nonlocal in_flight, peak
+ in_flight += 1
+ peak = max(peak, in_flight)
+ await asyncio.sleep(0.01)
+ in_flight -= 1
+ return NewUserResponse(user_id=user_id, key="")
+
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._create_user_if_not_exists",
+ AsyncMock(side_effect=create_user),
+ )
+ newcomers = [f"newcomer-{index:02d}" for index in range(3 * BULK_NEW_USER_CONCURRENCY)]
+ patch_ops = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[SCIMPatchOperation(op="add", path="members", value=[{"value": user_id} for user_id in newcomers])],
+ )
+
+ _, final_members, _ = await _process_group_patch_operations(
+ patch_ops=patch_ops,
+ existing_team=LiteLLM_TeamTable(team_id="group", team_alias="Group", members=[], members_with_roles=[]),
+ prisma_client=_member_resolution_prisma(mocker, users=set(), teams=set()),
+ )
+
+ assert final_members == set(newcomers)
+ assert peak == BULK_NEW_USER_CONCURRENCY
+
+
[email protected]("newcomer_count, admitted", [(1, True), (2, False)])
+async def test_group_push_creates_its_new_members_only_when_they_all_fit_the_license_seats(
+ mocker: MockerFixture, scim_upsert_user_enabled: None, newcomer_count: int, admitted: bool
+):
+ """Members a group push creates are seats too: the batch is checked against the seat limit
+ up front, so a push cannot create users past it the way per-user checks racing each other could."""
+ from litellm.proxy.auth.litellm_license import LicenseCheck
+
+ license_check: Final = LicenseCheck()
+ license_check.airgapped_license_data = {"max_users": 3}
+ mocker.patch("litellm.proxy.proxy_server._license_check", license_check)
+
+ async def count(where: Mapping[str, object] | None = None) -> int:
+ return 0 if where is not None else 2
+
+ prisma_client: Final = _member_resolution_prisma(mocker, users=set(), teams=set())
+ prisma_client.db.litellm_usertable.count = AsyncMock(side_effect=count)
+ create_user_mock: Final = mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._create_user_if_not_exists",
+ AsyncMock(side_effect=lambda user_id, created_via: NewUserResponse(user_id=user_id, key="")),
+ )
+ newcomers: Final = [f"newcomer-{index}" for index in range(newcomer_count)]
+ patch_ops: Final = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[SCIMPatchOperation(op="add", path="members", value=[{"value": user_id} for user_id in newcomers])],
+ )
+ push: Final = _process_group_patch_operations(
+ patch_ops=patch_ops,
+ existing_team=LiteLLM_TeamTable(team_id="group", team_alias="Group", members=[], members_with_roles=[]),
+ prisma_client=prisma_client,
+ )
+
+ if admitted:
+ _, final_members, _ = await push
+ assert final_members == set(newcomers)
+ return
+ with pytest.raises(HTTPException) as exc_info:
+ await push
+ assert exc_info.value.status_code == 403
+ assert "License is over limit" in str(exc_info.value.detail)
+ create_user_mock.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_process_group_patch_operations_ignores_lowercase_group_type(mocker, scim_upsert_user_enabled):
"""The ``type`` comparison is case-insensitive; IdPs are not consistent about it."""
@@ -4351,6 +4351,79 @@ async def test_process_group_patch_operations_prefers_user_over_team_for_collidi
assert final_members == {"dual-id"}
+async def test_create_group_whose_roster_write_fails_leaves_no_team_so_the_retry_creates_it(
+ mocker: MockerFixture, scim_upsert_user_enabled: None
+):
+ """A POST whose roster write failed left the empty team behind, so the identity provider's
+ retry got a 409 and the group never filled."""
+ group_id: Final = "new-group"
+ scim_group: Final = SCIMGroup(
+ schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
+ id=group_id,
+ displayName="Engineering",
+ members=[SCIMMember(value="user1"), SCIMMember(value="user2")],
+ )
+ teams: Final[dict[str, LiteLLM_TeamTable]] = {}
+
+ async def find_team(where: Mapping[str, str]) -> LiteLLM_TeamTable | None:
+ return teams.get(where["team_id"])
+
+ async def delete_team(where: Mapping[str, str]) -> LiteLLM_TeamTable | None:
+ return teams.pop(where["team_id"], None)
+
+ async def create_team(data: NewTeamRequest, **kwargs: object) -> dict[str, object]:
+ assert data.team_id is not None
+ teams[data.team_id] = LiteLLM_TeamTable(team_id=data.team_id, members_with_roles=[])
+ return teams[data.team_id].model_dump()
+
+ prisma_client: Final = mocker.MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(side_effect=find_team)
+ prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=())
+ prisma_client.db.litellm_teamtable.delete = AsyncMock(side_effect=delete_team)
+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
+ prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
+ AsyncMock(return_value=prisma_client),
+ )
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.new_team", AsyncMock(side_effect=create_team))
+ filled: Final = RosterSync(
+ team=LiteLLM_TeamTable(
+ team_id=group_id,
+ members_with_roles=[Member(user_id="user1", role="user"), Member(user_id="user2", role="user")],
+ ),
+ added=frozenset({"user1", "user2"}),
+ removed=frozenset(),
+ )
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2.sync_team_roster",
+ AsyncMock(
+ side_effect=[
+ MembersMissing(team_id=group_id, user_ids=("user2",)),
+ MembersMissing(team_id=group_id, user_ids=("user2",)),
+ filled,
+ ]
+ ),
+ )
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._create_user_if_not_exists",
+ AsyncMock(return_value=NewUserResponse(user_id="user2", key="k")),
+ )
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles", AsyncMock())
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
+ AsyncMock(return_value=scim_group),
+ )
+
+ with pytest.raises(ProxyException) as first_push:
+ await create_group(group=scim_group)
+ await create_group(group=scim_group)
+
+ assert first_push.value.code == "500"
+ assert tuple(teams) == (group_id,)
+
+
@pytest.mark.asyncio
async def test_create_group_strict_mode_accepts_group_and_team_members(mocker, scim_upsert_user_disabled):
"""Strict mode (scim_upsert_user=False) rejects unknown *users*; a nested group
@@ -4376,8 +4449,9 @@ async def test_create_group_strict_mode_accepts_group_and_team_members(mocker, s
)
new_team_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.new_team",
- AsyncMock(return_value=mocker.MagicMock()),
+ AsyncMock(return_value=_created_team(scim_group.id)),
)
+ sync_mock = _stub_roster_sync(mocker)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
AsyncMock(return_value=scim_group),
@@ -4390,7 +4464,8 @@ async def test_create_group_strict_mode_accepts_group_and_team_members(mocker, s
await create_group(group=scim_group)
create_user_mock.assert_not_called()
- assert new_team_mock.call_args.kwargs["data"].members_with_roles == [Member(user_id="real-user", role="user")]
+ assert new_team_mock.call_args.kwargs["data"].members_with_roles == []
+ assert sync_mock.await_args.args[1] == RosterDelta(add=frozenset({"real-user"}), remove=frozenset())
@pytest.mark.asyncio
@@ -4726,7 +4801,7 @@ async def test_create_group_stamps_scim_provenance(mocker, scim_upsert_user_enab
)
new_team_mock = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.new_team",
- AsyncMock(return_value=mocker.MagicMock()),
+ AsyncMock(return_value=_created_team(scim_group.id)),
)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
@@ -4782,7 +4857,7 @@ async def test_create_group_applies_default_team_params(
new_team_mock = (
mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable into create_group
"litellm.proxy.management_endpoints.scim.scim_v2.new_team",
- AsyncMock(return_value=mocker.MagicMock()),
+ AsyncMock(return_value=_created_team(scim_group.id)),
)
)
mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable into create_group
@@ -4838,6 +4913,7 @@ async def test_update_group_stamps_scim_provenance(mocker, scim_upsert_user_enab
"litellm.proxy.management_endpoints.scim.scim_v2._check_team_exists",
AsyncMock(return_value=existing_team),
)
+ _stub_roster_sync(mocker)
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -4942,7 +5018,7 @@ async def test_resolve_group_member_ids_dedupes_repeated_member(mocker, scim_ups
def _identity_lookup(*values: str) -> object:
unique_values: Final = tuple(dict.fromkeys(values))
subjects: Final = list(dict.fromkeys(value.strip() for value in unique_values))
- return mock_call(
+ return call(
where={
"OR": [
{"user_id": {"in": list(unique_values)}},
@@ -5545,7 +5621,7 @@ async def test_resolve_group_member_ids_reads_the_user_table_once_per_push(mocke
_identity_lookup("by-id", "[email protected]", "by-team", "nobody")
]
assert prisma_client.db.litellm_teamtable.find_many.await_args_list == [
- mock_call(where={"team_id": {"in": ["[email protected]", "by-team", "nobody"]}})
+ call(where={"team_id": {"in": ["[email protected]", "by-team", "nobody"]}})
]
@@ -5754,10 +5830,9 @@ async def test_get_groups_members_are_typed_as_users(mocker):
mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[team])
mock_prisma_client.db.litellm_teamtable.count = AsyncMock(return_value=1)
mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
- mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
- return_value=mocker.MagicMock(user_id="member-1", user_email="[email protected]")
+ mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
+ return_value=(mocker.MagicMock(user_id="member-1", user_email="[email protected]"),)
)
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=())
mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
@@ -5852,53 +5927,6 @@ async def test_patch_user_roster_remove_failure_propagates_and_skips_teams_write
mock_prisma_client.db.litellm_usertable.update.assert_not_called()
[email protected]("failing_member", ["user0", "user1", "user2", "user3"])
-async def test_handle_group_membership_changes_attempts_every_member_and_names_failures(mocker, failing_member):
- """One failing member must not strand the rest of the roster unattempted.
-
- Regression: reconciliation stopped at the first failure, so a group push carrying
- several membership changes left the later ones neither written nor reported, and the
- IdP got one opaque error. Every member is attempted now and only the writes that
- actually failed are named, so the next push closes exactly that gap.
- """
-
- async def add_member(**kwargs):
- if kwargs["data"].member.user_id == failing_member:
- raise HTTPException(status_code=500, detail={"error": "db unavailable"})
-
- async def remove_member(**kwargs):
- if kwargs["data"].user_id == failing_member:
- raise HTTPException(status_code=500, detail={"error": "db unavailable"})
-
- add_mock = AsyncMock(side_effect=add_member)
- delete_mock = AsyncMock(side_effect=remove_member)
- mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.team_member_add", add_mock)
- mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.team_member_delete", delete_mock)
-
- with pytest.raises(SCIMRosterSyncError) as exc_info:
- await _handle_group_membership_changes(
- group_id="group-1",
- current_members={"user0"},
- final_members={"user1", "user2", "user3"},
- )
-
- assert [call.kwargs["data"].member.user_id for call in add_mock.call_args_list] == ["user1", "user2", "user3"]
- assert [call.kwargs["data"].user_id for call in delete_mock.call_args_list] == ["user0"]
-
- message = str(exc_info.value)
- assert "1 of 4 team membership writes" in message
- failed_write = "remove user0 from group-1" if failing_member == "user0" else f"add {failing_member} to group-1"
- assert failed_write in message
- all_writes = {
- "remove user0 from group-1",
- "add user1 to group-1",
- "add user2 to group-1",
- "add user3 to group-1",
- }
- assert not [write for write in all_writes - {failed_write} if write in message]
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize(
"first_status, second_status, expected_status",
@@ -5967,53 +5995,154 @@ async def test_patch_team_membership_attempts_every_team_before_reporting(mocker
assert not [team for team in {"team-a", "team-b", "team-c"} - {failing_team} if f"add user1 to {team}" in message]
-async def test_update_group_roster_failure_propagates(mocker):
- """PUT /Groups must fail loudly when a member roster write fails, instead of
- reporting a successful membership sync to the IdP."""
- group_id = "test-team-123"
- existing_team = LiteLLM_TeamTable(
+def _put_group_whose_member_is_deleted_mid_push(mocker: MockerFixture, group_id: str) -> set[str]:
+ """Wire a PUT whose member ``user2`` resolves as an existing user and then has its row
+ deleted before the locked roster write, and return the ids the endpoint creates."""
+ existing_team: Final = LiteLLM_TeamTable(
team_id=group_id,
team_alias="Engineering",
members_with_roles=[Member(user_id="user1", role="user")],
metadata={},
)
- scim_group = SCIMGroup(
+ created: Final[set[str]] = set()
+
+ async def create_user(user_id: str, created_via: str) -> NewUserResponse:
+ created.add(user_id)
+ return NewUserResponse(user_id=user_id, key="k")
+
+ async def sync(team_id: str, **kwargs: object) -> RosterSync | MembersMissing:
+ if "user2" not in created:
+ return MembersMissing(team_id=team_id, user_ids=("user2",))
+ return RosterSync(
+ team=existing_team.model_copy(
+ update={
+ "members_with_roles": [Member(user_id="user1", role="user"), Member(user_id="user2", role="user")]
+ }
+ ),
+ added=frozenset({"user2"}),
+ removed=frozenset(),
+ )
+
+ prisma_client: Final = mocker.MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
+ prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=())
+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=None)
+ prisma_client.db.litellm_usertable.find_many = AsyncMock(side_effect=_rows_by_exact_id(_user_row_for))
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
+ AsyncMock(return_value=prisma_client),
+ )
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.sync_team_roster", AsyncMock(side_effect=sync))
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._create_user_if_not_exists",
+ AsyncMock(side_effect=create_user),
+ )
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles", AsyncMock())
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
+ AsyncMock(side_effect=_group_of_roster),
+ )
+ return created
+
+
+async def _group_of_roster(team: LiteLLM_TeamTable) -> SCIMGroup:
+ return SCIMGroup(
+ schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
+ id=team.team_id,
+ displayName=team.team_alias or team.team_id,
+ members=[SCIMMember(value=member.user_id) for member in team.members_with_roles if member.user_id is not None],
+ )
+
+
+def _engineering_group(group_id: str) -> SCIMGroup:
+ return SCIMGroup(
schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
id=group_id,
displayName="Engineering",
members=[SCIMMember(value="user1"), SCIMMember(value="user2")],
)
- mock_prisma_client = mocker.MagicMock()
- mock_prisma_client.db = mocker.MagicMock()
- mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
- mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
- mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=())
- mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
- mock_prisma_client.db.litellm_usertable = mocker.MagicMock()
- mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mocker.MagicMock())
- mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(
- return_value=(LiteLLM_UserTable(user_id="user1"), LiteLLM_UserTable(user_id="user2"))
- )
- mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
- AsyncMock(return_value=mock_prisma_client),
+async def test_update_group_creates_a_member_deleted_mid_push_again(mocker: MockerFixture, scim_upsert_user_enabled):
+ """A user deleted between member resolution and the locked roster write failed the whole
+ push with a 500, where the per-member write created the member again and answered 200."""
+ created: Final = _put_group_whose_member_is_deleted_mid_push(mocker, "test-team-123")
+
+ response: Final = await update_group(group_id="test-team-123", group=_engineering_group("test-team-123"))
+
+ assert created == {"user2"}
+ assert [member.value for member in response.members or []] == ["user1", "user2"]
+
+
+async def test_update_group_creates_members_deleted_between_its_retries_again(
+ mocker: MockerFixture, scim_upsert_user_enabled
+):
+ group_id: Final = "test-team-123"
+ created: Final = _put_group_whose_member_is_deleted_mid_push(mocker, group_id)
+ members: Final = [Member(user_id=user_id, role="user") for user_id in ("user1", "user2", "user3")]
+
+ async def sync(team_id: str, **kwargs: object) -> RosterSync | MembersMissing:
+ missing = next((user_id for user_id in ("user2", "user3") if user_id not in created), None)
+ if missing is not None:
+ return MembersMissing(team_id=team_id, user_ids=(missing,))
+ return RosterSync(
+ team=LiteLLM_TeamTable(team_id=team_id, members_with_roles=members),
+ added=frozenset({"user2", "user3"}),
+ removed=frozenset(),
+ )
+
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.sync_team_roster", AsyncMock(side_effect=sync))
+ group: Final = _engineering_group(group_id).model_copy(
+ update={"members": [SCIMMember(value=member.user_id) for member in members]}
)
+
+ response: Final = await update_group(group_id=group_id, group=group)
+
+ assert created == {"user2", "user3"}
+ assert [member.value for member in response.members or []] == ["user1", "user2", "user3"]
+
+
+async def test_update_group_in_strict_mode_fails_when_a_member_is_deleted_mid_push(
+ mocker: MockerFixture, scim_upsert_user_disabled
+):
+ """With scim_upsert_user False a group write never creates users, so a member deleted
+ mid-push is refused like any member that is not a user yet, instead of being created
+ behind the setting that forbids it."""
+ created: Final = _put_group_whose_member_is_deleted_mid_push(mocker, "test-team-123")
+
+ with pytest.raises(ProxyException) as exc_info:
+ await update_group(group_id="test-team-123", group=_engineering_group("test-team-123"))
+
+ assert exc_info.value.code == "400"
+ assert "does not exist" in exc_info.value.message
+ assert "user2" in exc_info.value.message
+ assert created == set()
+
+
+async def test_update_group_roster_failure_propagates(mocker: MockerFixture, scim_upsert_user_enabled):
+ """PUT /Groups must fail loudly when the roster write cannot land every member,
+ instead of reporting a successful membership sync to the IdP."""
+ group_id: Final = "test-team-123"
+ _ = _put_group_whose_member_is_deleted_mid_push(mocker, group_id)
mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.team_member_add",
- AsyncMock(side_effect=HTTPException(status_code=500, detail={"error": "db unavailable"})),
+ "litellm.proxy.management_endpoints.scim.scim_v2.sync_team_roster",
+ AsyncMock(return_value=MembersMissing(team_id=group_id, user_ids=("user2",))),
)
- recompute_mock = mocker.patch(
+ recompute_mock: Final = mocker.patch(
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
)
with pytest.raises(ProxyException) as exc_info:
- await update_group(group_id=group_id, group=scim_group)
+ await update_group(group_id=group_id, group=_engineering_group(group_id))
- assert "add user2 to test-team-123" in exc_info.value.message
+ assert exc_info.value.code == "500"
+ assert "user2" in exc_info.value.message
recompute_mock.assert_not_called()
@@ -6061,35 +6190,12 @@ async def test_resolve_group_member_ids_admits_member_created_concurrently(mocke
assert len(result.created_users) == 0
-async def test_handle_group_membership_changes_already_in_team_is_noop(mocker):
- """The strict path must keep treating an already-enrolled member as a no-op
- and continue with the remaining members instead of failing the sync."""
- mock_team_member_add = mocker.patch(
- "litellm.proxy.management_endpoints.scim.scim_v2.team_member_add",
- AsyncMock(
- side_effect=ProxyException(
- message="already in team",
- type=ProxyErrorTypes.team_member_already_in_team.value,
- param=None,
- code=400,
- )
- ),
- )
-
- await _handle_group_membership_changes(
- group_id="group-1", current_members=set(), final_members={"user-1", "user-2"}
- )
-
- assert mock_team_member_add.await_count == 2
-
-
@pytest.mark.asyncio
async def test_patch_group_404s_when_team_deleted_mid_request(mocker):
- """A group deleted between the existence check and the write must 404.
+ """A group deleted between the existence check and the roster write must 404.
- Prisma returns None from both the update and the refresh reads once the row is
- gone, and patch_group used to dereference that None while building the response.
+ The roster write reports the team gone instead of a roster, and patch_group used to
+ dereference a None row while building the response.
"""
group_id = "team-gone"
@@ -6108,13 +6214,17 @@ async def test_patch_group_404s_when_team_deleted_mid_request(mocker):
mock_prisma_client = mocker.MagicMock()
mock_prisma_client.db = mocker.MagicMock()
mock_prisma_client.db.litellm_teamtable = mocker.MagicMock()
- mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(side_effect=[snapshot_team, None, None])
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=snapshot_team)
mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=None)
mocker.patch( # test-quality-ok: stubs the collaborator so the test pins the endpoint's own error contract
"litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
AsyncMock(return_value=mock_prisma_client),
)
+ mocker.patch( # test-quality-ok: stubs the collaborator so the test pins the endpoint's own error contract
+ "litellm.proxy.management_endpoints.scim.scim_v2.sync_team_roster",
+ AsyncMock(return_value=TeamGone(team_id=group_id)),
+ )
mocker.patch( # test-quality-ok: stubs the collaborator so the test pins the endpoint's own error contract
"litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles",
AsyncMock(),
@@ -6232,6 +6342,15 @@ def _shadow_tenant_prisma(
prisma_client.db.litellm_invitationlink = mocker.MagicMock(delete_many=AsyncMock(return_value=0))
prisma_client.db.litellm_organizationmembership = mocker.MagicMock(delete_many=AsyncMock(return_value=0))
prisma_client.db.litellm_teammembership = mocker.MagicMock(delete_many=AsyncMock(return_value=0))
+
+ async def locked_user_delete(*, user_ids: Sequence[str], **_: object) -> int:
+ deleted: Final = [await prisma_client.db.litellm_usertable.delete(where={"user_id": uid}) for uid in user_ids]
+ return sum(row is not None for row in deleted)
+
+ mocker.patch( # test-quality-ok: the locked user row delete runs in a transaction this fake does not model
+ "litellm.proxy.management_endpoints.scim.scim_v2.delete_users_from_current_teams",
+ AsyncMock(side_effect=locked_user_delete),
+ )
return prisma_client
@@ -6282,9 +6401,6 @@ async def test_merge_placeholder_hands_the_group_to_the_shadowed_account(mocker,
assert (added.team_id, added.member.user_id) == (_SHADOWED_GROUP, _SHADOWED_ACCOUNT)
dropped: Final = team_member_delete_mock.call_args.kwargs["data"]
assert (dropped.team_id, dropped.user_id) == (_SHADOWED_GROUP, _SHADOW_MEMBER_VALUE)
- shadowed_tenant.db.litellm_teammembership.delete_many.assert_awaited_once_with(
- where={"user_id": _SHADOW_MEMBER_VALUE}
- )
shadowed_tenant.db.litellm_usertable.delete.assert_awaited_once_with(where={"user_id": _SHADOW_MEMBER_VALUE})
after: Final = await _push_shadow_member(shadowed_tenant)
@@ -6412,7 +6528,7 @@ async def test_patch_group_pathless_replace_applies_attributes_and_drops_empty_k
mock_prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=())
monkeypatch.setattr(proxy_server, "prisma_client", mock_prisma_client)
- mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", AsyncMock())
+ _stub_roster_sync(mocker)
mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles", AsyncMock())
response = await patch_group(group_id=group_id, patch_ops=patch_ops)
@@ -6556,3 +6672,91 @@ async def test_process_group_patch_operations_rejects_pathless_op_it_cannot_appl
)
assert exc.value.status_code == 400
+
+
+_LARGE_PUSH: Final = tuple(f"user-{index:03d}" for index in range(500))
+
+
+async def _group_listing_the_roster(team: LiteLLM_TeamTable) -> SCIMGroup:
+ return SCIMGroup(
+ schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
+ id=team.team_id,
+ displayName=team.team_alias or team.team_id,
+ members=[SCIMMember(value=member.user_id) for member in team.members_with_roles if member.user_id is not None],
+ )
+
+
+async def _push_group(verb: str, group_id: str, scim_group: SCIMGroup) -> SCIMGroup:
+ match verb:
+ case "POST":
+ return await create_group(group=scim_group)
+ case "PUT":
+ return await update_group(group_id=group_id, group=scim_group)
+ case "PATCH":
+ patch_ops: Final = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[
+ SCIMPatchOperation(op="add", path="members", value=[{"value": user_id} for user_id in _LARGE_PUSH])
+ ],
+ )
+ return await patch_group(group_id=group_id, patch_ops=patch_ops)
+ case _:
+ raise AssertionError(verb)
+
+
+ "verb, expected_plan, created_via",
+ [
+ ("POST", RosterDelta(add=frozenset(_LARGE_PUSH), remove=frozenset()), "scim_group_membership"),
+ ("PUT", RosterTarget(member_ids=frozenset(_LARGE_PUSH)), "scim_group_membership"),
+ ("PATCH", RosterDelta(add=frozenset(_LARGE_PUSH), remove=frozenset()), "scim_group_patch"),
+ ],
+)
+async def test_group_push_of_500_members_reads_the_user_table_once_and_writes_the_roster_once(
+ mocker: MockerFixture,
+ scim_upsert_user_enabled: None,
+ verb: str,
+ expected_plan: RosterPlan,
+ created_via: str,
+):
+ """A group push costs one read of the user table and one roster write however many
+ members it carries. Resolving and enrolling members one at a time made a 500-member
+ push outlast the edge in front of the proxy, so the IdP saw a 504 and retried."""
+ group_id = "large-group"
+ existing_team = LiteLLM_TeamTable(
+ team_id=group_id,
+ team_alias="Everyone",
+ members_with_roles=[],
+ metadata={SCIM_MANAGED_TEAM_METADATA_KEY: True},
+ )
+ scim_group = SCIMGroup(
+ schemas=["urn:ietf:params:scim:schemas:core:2.0:Group"],
+ id=group_id,
+ displayName="Everyone",
+ members=[SCIMMember(value=user_id) for user_id in _LARGE_PUSH],
+ )
+ prisma_client = _member_resolution_prisma(mocker, users=set(_LARGE_PUSH), teams=set())
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=None if verb == "POST" else existing_team)
+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=existing_team)
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",
+ AsyncMock(return_value=prisma_client),
+ )
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2.new_team", AsyncMock(return_value=_created_team(group_id))
+ )
+ mocker.patch("litellm.proxy.management_endpoints.scim.scim_v2._recompute_scim_member_roles", AsyncMock())
+ mocker.patch(
+ "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_team_to_scim_group",
+ AsyncMock(side_effect=_group_listing_the_roster),
+ )
+ sync_mock = _stub_roster_sync(mocker, existing_team)
+
+ response = await _push_group(verb, group_id, scim_group)
+
+ assert (response.id, sorted(member.value for member in response.members)) == (group_id, sorted(_LARGE_PUSH))
+ assert sync_mock.await_args_list == [call(group_id, expected_plan, created_via, prisma_client)]
+ assert prisma_client.db.litellm_usertable.find_many.await_count == 1
+ prisma_client.db.litellm_usertable.find_unique.assert_not_awaited()
+ prisma_client.db.litellm_teamtable.find_many.assert_not_awaited()
diff --git a/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py
index fb463186d8c..037ccd26236 100644
--- a/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py
@@ -2,7 +2,8 @@ import asyncio
import hashlib
import json
import logging
-from collections.abc import Mapping, Sequence
+from collections.abc import AsyncIterator, Mapping, Sequence
+from contextlib import asynccontextmanager
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import TYPE_CHECKING, Final, cast
@@ -2829,6 +2830,17 @@ async def test_get_user_daily_activity_rejects_service_account_caller(monkeypatc
mock_get_daily.assert_not_called()
+def _serve_locked_user_delete(prisma_client: MagicMock, *users: object) -> None:
+ @asynccontextmanager
+ async def tx(*, timeout: object = None) -> AsyncIterator[MagicMock]:
+ yield prisma_client.db
+
+ prisma_client.tx = tx
+ prisma_client.db.query_raw = AsyncMock(return_value=[])
+ prisma_client.db.litellm_usertable.find_many = AsyncMock(return_value=list(users))
+ prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[])
+
+
@pytest.mark.asyncio
async def test_delete_user_cleans_up_created_by_invitation_links(mocker):
"""
@@ -2881,6 +2893,7 @@ async def test_delete_user_cleans_up_created_by_invitation_links(mocker):
mock_prisma_client.db.litellm_usertable.delete_many = mocker.AsyncMock(
return_value=1
)
+ _serve_locked_user_delete(mock_prisma_client, mock_user_row)
mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
@@ -2970,6 +2983,7 @@ async def test_delete_user_evicts_jwt_key_mapping_cache_of_its_keys(mocker):
mock_prisma_client.db.litellm_organizationmembership.delete_many = mocker.AsyncMock(return_value=0)
mock_prisma_client.db.litellm_teammembership.delete_many = mocker.AsyncMock(return_value=0)
mock_prisma_client.db.litellm_usertable.delete_many = mocker.AsyncMock(return_value=1)
+ _serve_locked_user_delete(mock_prisma_client, user_row)
mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) # test-quality-ok: substitute the database dependency
mocker.patch("litellm.proxy.proxy_server.user_api_key_cache", cache) # test-quality-ok: exercise a real isolated cache
@@ -4930,6 +4944,7 @@ async def test_delete_user_evicts_cached_user_rows(mocker: MockerFixture) -> Non
prisma_client.db.litellm_organizationmembership.delete_many = mocker.AsyncMock(return_value=0)
prisma_client.db.litellm_teammembership.delete_many = mocker.AsyncMock(return_value=0)
prisma_client.db.litellm_usertable.delete_many = mocker.AsyncMock(return_value=1)
+ _serve_locked_user_delete(prisma_client, deleted)
mocker.patch("litellm.proxy.proxy_server.prisma_client", prisma_client) # test-quality-ok: substitute the database dependency
cache: Final = UserApiKeyCache()
for row in (deleted, survivor):
@@ -5102,6 +5117,7 @@ async def test_delete_user_writes_deleted_audit_log_for_user_keys(mocker):
mock_prisma_client.db.litellm_teammembership.delete_many = mocker.AsyncMock(return_value=0)
mock_prisma_client.db.litellm_jwtkeymapping.find_many = mocker.AsyncMock(return_value=[])
mock_prisma_client.db.litellm_usertable.delete_many = mocker.AsyncMock(return_value=1)
+ _serve_locked_user_delete(mock_prisma_client, mock_user_row)
mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
mocker.patch("litellm.store_audit_logs", True)
diff --git a/tests/unit/proxy/management_endpoints/test_team_endpoints.py b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
index 71666fe69fa..0b28c58a3c7 100644
--- a/tests/unit/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
@@ -49,7 +49,7 @@ from litellm.proxy.management_endpoints.team_admin_field_permissions import (
SUPPORTED_TEAM_ADMIN_PERMISSIONS,
)
from litellm.proxy.management_endpoints.team_endpoints import (
- _STRIP_DELETED_TEAM_FROM_USERS_SQL,
+ _STRIP_DELETED_TEAMS_FROM_USERS_SQL,
GetTeamMemberPermissionsResponse,
UpdateTeamMemberPermissionsRequest,
_build_team_list_where_conditions,
@@ -2047,9 +2047,10 @@ async def test_add_team_members_reconciles_against_freshly_locked_row():
assert tx.query_raw.call_args_list[0].args == (TEAM_ADVISORY_LOCK_SQL, "test-team-lock"), (
"expected the team's advisory lock to be acquired before the members_with_roles read"
)
- assert not any("FOR UPDATE" in str(call.args[0]) for call in tx.query_raw.call_args_list), (
- "a row lock here can deadlock with the access-group endpoints; only the advisory lock is safe"
- )
+ assert not any(
+ "FOR UPDATE" in str(call.args[0]) and "LiteLLM_TeamTable" in str(call.args[0])
+ for call in tx.query_raw.call_args_list
+ ), "a team row lock here can deadlock with the access-group endpoints; only the advisory lock is safe"
assert [m.user_id for m in updated_team.members_with_roles] == ["zed", "alice", "bob"]
@@ -2118,6 +2119,61 @@ async def test_add_team_members_runs_member_writes_on_the_lock_holding_transacti
assert [tm.budget_id for tm in updated_team_memberships] == ["budget-pool"]
+async def test_add_team_members_locks_every_named_user_row_in_id_order_before_the_first_member_write():
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ _add_team_members_to_team,
+ )
+
+ events: list[object] = []
+ email_match = MagicMock()
+ email_match.user_id = "alice-id"
+
+ async def query_raw(sql: str, *args: object) -> list[dict[str, object]]:
+ if "FOR UPDATE" in sql:
+ events.append(("locked", list(cast(list[str], args[0]))))
+ return []
+ return [{"members_with_roles": []}]
+
+ async def write_members(**_: object) -> tuple[list[object], list[object]]:
+ events.append("member writes")
+ return [], []
+
+ tx = MagicMock()
+ tx.query_raw = AsyncMock(side_effect=query_raw)
+ tx.litellm_usertable.find_many = AsyncMock(return_value=[email_match])
+ tx.litellm_teamtable.update = AsyncMock(
+ return_value=LiteLLM_TeamTable(team_id="team-order", members_with_roles=[])
+ )
+ tx_cm = MagicMock()
+ tx_cm.__aenter__ = AsyncMock(return_value=tx)
+ tx_cm.__aexit__ = AsyncMock(return_value=None)
+ prisma_client = MagicMock()
+ prisma_client.tx = MagicMock(return_value=tx_cm)
+
+ with patch(
+ "litellm.proxy.management_endpoints.team_endpoints._process_team_members",
+ new=AsyncMock(side_effect=write_members),
+ ):
+ await _add_team_members_to_team(
+ data=TeamMemberAddRequest(
+ team_id="team-order",
+ member=[
+ Member(user_id="u2", role="user"),
+ Member(user_email="[email protected]", role="user"),
+ Member(user_id="u10", role="user"),
+ Member(user_id="u1", role="user"),
+ ],
+ ),
+ complete_team_data=LiteLLM_TeamTable(team_id="team-order", members_with_roles=[]),
+ prisma_client=cast(object, prisma_client),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ litellm_proxy_admin_name="admin",
+ )
+
+ assert events == [("locked", ["alice-id", "u1", "u10", "u2"]), "member writes"]
+
+
@pytest.mark.asyncio
async def test_add_team_members_skips_budget_and_membership_writes_for_members_already_on_the_roster():
"""
@@ -9120,12 +9176,9 @@ async def test_delete_team_sweeps_references_outside_members_with_roles(
litellm_changed_by="admin-user",
)
- # array_remove strips just the deleted id in one statement; a read-filter-write of the whole
- # array would drop any team a concurrent /team/member_add appended between read and write
- assert "array_remove" in _STRIP_DELETED_TEAM_FROM_USERS_SQL
assert mock_execute_raw.await_args_list == [
- call(_STRIP_DELETED_TEAM_FROM_USERS_SQL, "team-doomed"),
- call(_STRIP_DELETED_TEAM_FROM_USERS_SQL, "team-doomed"),
+ call(_STRIP_DELETED_TEAMS_FROM_USERS_SQL, ["team-doomed"]),
+ call(_STRIP_DELETED_TEAMS_FROM_USERS_SQL, ["team-doomed"]),
], (
"the unlocked sweep must run once to catch pre-existing drift, and the locked sweep "
"(alongside the delete, under the same advisory lock member_add takes) must run again "
@@ -9395,6 +9448,37 @@ async def test_delete_team_failing_locked_sweep_rolls_back_the_delete_and_leaves
assert fresh_cache.get_cache(key="team_alias:doomed-team") is not None
+class _BroadcastPipeline:
+ def __init__(self, redis: "_BroadcastRecordingRedis") -> None:
+ self._redis = redis
+ self._messages: list[str] = []
+
+ def publish(self, channel: str, message: str) -> "_BroadcastPipeline":
+ self._messages.append(message)
+ return self
+
+ async def execute(self) -> None:
+ for message in self._messages:
+ await self._redis.publish("", message)
+
+
+class _BroadcastRecordingRedis:
+ namespace = None
+
+ def __init__(self) -> None:
+ self.broadcast_keys: list[str] = []
+
+ def init_pubsub_client(self) -> "_BroadcastRecordingRedis":
+ return self
+
+ async def publish(self, channel: str, message: str) -> int:
+ self.broadcast_keys.append(json.loads(message)["cache_key"])
+ return 1
+
+ def pipeline(self, transaction: bool = True) -> _BroadcastPipeline:
+ return _BroadcastPipeline(self)
+
+
@pytest.mark.asyncio
async def test_delete_team_broadcasts_cache_invalidation_to_other_workers(
monkeypatch,
@@ -9436,12 +9520,11 @@ async def test_delete_team_broadcasts_cache_invalidation_to_other_workers(
mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
_wire_team_delete_tx(mock_prisma_client)
- published = []
+ import litellm.proxy.common_utils.auth_cache_invalidation_pubsub as pubsub_module
- async def record_publish(cache_key):
- published.append(cache_key)
-
- monkeypatch.setattr("litellm.proxy.auth.auth_checks.publish_auth_cache_invalidation", record_publish)
+ redis = _BroadcastRecordingRedis()
+ monkeypatch.setattr(pubsub_module, "coordination_redis_cache", lambda: redis)
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", UserApiKeyCache())
monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", AsyncMock())
@@ -9458,9 +9541,11 @@ async def test_delete_team_broadcasts_cache_invalidation_to_other_workers(
litellm_changed_by="admin-user",
)
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
# the deleted key first, then both keys `_cache_team_object` writes: miss the alias one and the
# JWT-by-alias path keeps resolving the team, miss the token and the key still authenticates
- assert published == ["hashed-doomed-key", "team_id:team-doomed", "team_alias:doomed-team"]
+ assert redis.broadcast_keys == ["hashed-doomed-key", "team_id:team-doomed", "team_alias:doomed-team"]
@pytest.mark.asyncio
diff --git a/tests/unit/proxy/management_helpers/test_bulk_user_deletion.py b/tests/unit/proxy/management_helpers/test_bulk_user_deletion.py
index 32e5bea613c..74b4a3caf0a 100644
--- a/tests/unit/proxy/management_helpers/test_bulk_user_deletion.py
+++ b/tests/unit/proxy/management_helpers/test_bulk_user_deletion.py
@@ -1,18 +1,25 @@
import asyncio
import copy
+import itertools
import json
from collections.abc import Callable, Mapping, Sequence
from contextlib import asynccontextmanager
-from typing import Final
+from typing import Final, cast
import pytest
from pydantic import BaseModel, ConfigDict, ValidationError
+import litellm
+from litellm.integrations.prometheus import PrometheusLogger
from litellm.proxy._types import LiteLLM_TeamTable, LitellmTableNames, LitellmUserRoles, Member, UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import jwt_key_mapping_cache_key
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.list_api.common import ManagementProblem
-from litellm.proxy.management_helpers.bulk_user_deletion import bulk_delete_users, bulk_remove_team_members
+from litellm.proxy.management_helpers.bulk_user_deletion import (
+ bulk_delete_users,
+ bulk_remove_team_members,
+ delete_users_from_current_teams,
+)
from litellm.types.proxy.management_endpoints.internal_user_endpoints import BulkDeleteUserRequest
from litellm.types.proxy.management_endpoints.team_endpoints import BulkTeamMemberDeleteRequest, TeamMemberRef
@@ -70,17 +77,14 @@ class _Rows:
class _UserTable:
- def __init__(self, users: Sequence[_UserRow]) -> None:
+ def __init__(self, users: Sequence[_UserRow], after_read: Callable[[dict[str, _UserRow]], None]) -> None:
self.rows: dict[str, _UserRow] = {u.user_id: u for u in users}
+ self._after_read = after_read
async def find_many(self, where: Mapping[str, object]) -> list[_UserRow]:
- return [u for u in self.rows.values() if _matches(u.model_dump(), where)]
-
- async def update(self, where: Mapping[str, str], data: Mapping[str, Mapping[str, Sequence[str]]]) -> _UserRow:
- row = self.rows[where["user_id"]]
- updated = row.model_copy(update={"teams": list(data["teams"]["set"])})
- self.rows[row.user_id] = updated
- return updated
+ found = [u for u in self.rows.values() if _matches(u.model_dump(), where)]
+ self._after_read(self.rows)
+ return found
async def delete_many(self, where: Mapping[str, object]) -> int:
doomed = [uid for uid, u in self.rows.items() if _matches(u.model_dump(), where)]
@@ -117,8 +121,9 @@ class _Db:
invitations: Sequence[Mapping[str, object]] = (),
org_memberships: Sequence[Mapping[str, object]] = (),
jwt_mappings: Sequence[Mapping[str, object]] = (),
+ after_user_read: Callable[[dict[str, _UserRow]], None] = lambda _: None,
) -> None:
- self.litellm_usertable = _UserTable(users)
+ self.litellm_usertable = _UserTable(users, after_user_read)
self.litellm_teamtable = _TeamTable(teams)
self.litellm_teammembership = _Rows([{"team_id": t, "user_id": u} for t, u in memberships])
self.litellm_verificationtoken = _Rows(tokens)
@@ -129,7 +134,15 @@ class _Db:
class _Tx:
- def __init__(self, db: _Db, on_lock: Callable[[str], None], fail_locks: frozenset[str]) -> None:
+ def __init__(
+ self,
+ db: _Db,
+ on_lock: Callable[[str], None],
+ fail_locks: frozenset[str],
+ on_user_lock: Callable[[_Db], None],
+ ) -> None:
+ self._db = db
+ self._on_user_lock = on_user_lock
self.litellm_teamtable = db.litellm_teamtable
self.litellm_usertable = db.litellm_usertable
self.litellm_teammembership = db.litellm_teammembership
@@ -141,14 +154,22 @@ class _Tx:
self._fail_locks = fail_locks
self.locks: list[str] = []
self.roster_reads: list[str] = []
+ self.user_locks: list[dict[str, list[str]]] = []
async def query_raw(self, sql: str, *args: object) -> list[dict[str, object]]:
+ if 'ORDER BY user_id COLLATE "C" FOR UPDATE' in sql:
+ self._on_user_lock(self._db)
+ user_ids = [str(user_id) for user_id in cast(Sequence[object], args[0])]
+ rows = self.litellm_usertable.rows
+ self.user_locks.append({user_id: list(rows[user_id].teams) for user_id in user_ids if user_id in rows})
+ return [{"user_id": user_id} for user_id in user_ids if user_id in rows]
team_id = str(args[0])
if "pg_advisory_xact_lock" in sql:
if team_id in self._fail_locks:
raise RuntimeError("lock timeout")
- self.locks.append(team_id)
- self._on_lock(team_id)
+ if team_id not in self.locks:
+ self.locks.append(team_id)
+ self._on_lock(team_id)
return []
assert team_id in self.locks, "roster must be read under this team's advisory lock"
self.roster_reads.append(team_id)
@@ -157,6 +178,14 @@ class _Tx:
return []
return [{"members_with_roles": json.dumps([m.model_dump() for m in team.members_with_roles])}]
+ async def execute_raw(self, sql: str, team_id: str, user_ids: Sequence[str]) -> int:
+ assert "array_remove(teams, $1)" in sql
+ rows = self.litellm_usertable.rows
+ detached = [user_id for user_id in user_ids if user_id in rows]
+ for user_id in detached:
+ rows[user_id] = rows[user_id].model_copy(update={"teams": [t for t in rows[user_id].teams if t != team_id]})
+ return len(detached)
+
class _FakePrisma:
def __init__(
@@ -171,18 +200,22 @@ class _FakePrisma:
on_lock: Callable[[str], None] = lambda _: None,
fail_locks: frozenset[str] = frozenset(),
fail_commit: bool = False,
+ on_user_lock: Callable[[_Db], None] = lambda _: None,
+ after_user_read: Callable[[dict[str, _UserRow]], None] = lambda _: None,
) -> None:
- self.db = _Db(users, teams, memberships, tokens, invitations, org_memberships, jwt_mappings)
+ self.db = _Db(users, teams, memberships, tokens, invitations, org_memberships, jwt_mappings, after_user_read)
self._on_lock = on_lock
+ self._on_user_lock = on_user_lock
self._fail_locks = fail_locks
self._fail_commit = fail_commit
self.locks: list[str] = []
self.roster_reads: list[str] = []
+ self.user_locks: list[dict[str, list[str]]] = []
@asynccontextmanager
async def tx(self, *, timeout: object = None):
snapshot = copy.deepcopy(self.db)
- tx = _Tx(self.db, self._on_lock, self._fail_locks)
+ tx = _Tx(self.db, self._on_lock, self._fail_locks, self._on_user_lock)
try:
yield tx
if self._fail_commit:
@@ -192,11 +225,13 @@ class _FakePrisma:
raise
self.locks.extend(tx.locks)
self.roster_reads.extend(tx.roster_reads)
+ self.user_locks.extend(tx.user_locks)
-def _team(team_id: str, *members: str, org: str | None = None) -> LiteLLM_TeamTable:
+def _team(team_id: str, *members: str, org: str | None = None, alias: str | None = None) -> LiteLLM_TeamTable:
return LiteLLM_TeamTable(
team_id=team_id,
+ team_alias=alias,
organization_id=org,
members_with_roles=[Member(user_id=m, user_email=f"{m}@example.com", role="user") for m in members],
)
@@ -373,6 +408,141 @@ async def test_bulk_delete_reads_roster_under_lock_so_a_concurrent_add_survives(
assert _roster(prisma, "t1") == ["late"]
+async def test_bulk_delete_still_deletes_a_user_whose_team_was_deleted_while_it_waited_on_the_team_lock():
+ def team_delete_commits_first(team_id: str) -> None:
+ del prisma.db.litellm_teamtable.rows[team_id]
+ prisma.db.litellm_usertable.rows["u1"] = prisma.db.litellm_usertable.rows["u1"].model_copy(update={"teams": []})
+
+ prisma = _FakePrisma(users=[_user("u1", "t1")], teams=[_team("t1", "u1")], on_lock=team_delete_commits_first)
+
+ results = await _delete(prisma, ["u1"])
+
+ assert results[0].success is True
+ assert "u1" not in prisma.db.litellm_usertable.rows
+
+
+async def test_bulk_delete_takes_every_team_lock_before_writing_a_user_row():
+ teams_when_locked: dict[str, list[str]] = {}
+
+ def snapshot_user_row(team_id: str) -> None:
+ teams_when_locked[team_id] = list(prisma.db.litellm_usertable.rows["u1"].teams)
+
+ prisma = _FakePrisma(
+ users=[_user("u1", "t1", "t2")],
+ teams=[_team("t1", "u1"), _team("t2", "u1")],
+ on_lock=snapshot_user_row,
+ )
+
+ results = await _delete(prisma, ["u1"])
+
+ assert results[0].success is True
+ assert teams_when_locked == {"t1": ["t1", "t2"], "t2": ["t1", "t2"]}
+
+
+async def test_bulk_delete_removes_users_from_a_team_a_push_added_them_to_while_it_waited_on_their_rows():
+ pushed = itertools.count()
+
+ def push_commits_before_the_row_lock(db: _Db) -> None:
+ if next(pushed):
+ return
+ db.litellm_usertable.rows["u1"] = db.litellm_usertable.rows["u1"].model_copy(update={"teams": ["side", "g1"]})
+ db.litellm_teamtable.rows["g1"].members_with_roles.append(Member(user_id="u1", role="user"))
+ db.litellm_teammembership.rows.append({"team_id": "g1", "user_id": "u1"})
+
+ prisma = _FakePrisma(
+ users=[_user("u1", "side")],
+ teams=[_team("side", "u1", "keep"), _team("g1", "keep")],
+ memberships=[("side", "u1")],
+ on_user_lock=push_commits_before_the_row_lock,
+ )
+
+ results = await _delete(prisma, ["u1"])
+
+ assert results[0].success is True
+ assert sorted(results[0].teams_removed) == ["g1", "side"]
+ assert _roster(prisma, "g1") == ["keep"]
+ assert _roster(prisma, "side") == ["keep"]
+ assert prisma.db.litellm_teammembership.rows == []
+ assert "u1" not in prisma.db.litellm_usertable.rows
+
+
+async def test_user_delete_takes_the_user_off_a_team_a_push_added_them_to_and_leaves_their_keys():
+ pushed = itertools.count()
+
+ def push_commits_before_the_row_lock(db: _Db) -> None:
+ if next(pushed):
+ return
+ db.litellm_usertable.rows["u1"] = db.litellm_usertable.rows["u1"].model_copy(update={"teams": ["g1"]})
+ db.litellm_teamtable.rows["g1"].members_with_roles.append(Member(user_id="u1", role="user"))
+ db.litellm_teammembership.rows.append({"team_id": "g1", "user_id": "u1"})
+
+ prisma = _FakePrisma(
+ users=[_user("u1"), _user("keep", "g1")],
+ teams=[_team("g1", "keep")],
+ memberships=[("g1", "keep")],
+ tokens=[{"token": "k1", "user_id": "u1"}],
+ invitations=[{"id": "i1", "user_id": "keep", "created_by": "u1", "updated_by": "admin"}],
+ org_memberships=[{"user_id": "u1", "organization_id": "o1", "user_role": "internal_user"}],
+ on_user_lock=push_commits_before_the_row_lock,
+ )
+ cache = UserApiKeyCache()
+ cache.set_cache(key="u1", value={"user_id": "u1"})
+
+ deleted = await delete_users_from_current_teams(
+ prisma_client=prisma, # pyright: ignore[reportArgumentType] # fake stands in for PrismaClient
+ user_ids=("u1",),
+ user_api_key_dict=ADMIN,
+ user_api_key_cache=cache,
+ proxy_logging_obj=None,
+ litellm_changed_by=None,
+ )
+
+ assert deleted == 1
+ assert _roster(prisma, "g1") == ["keep"]
+ assert prisma.db.litellm_teammembership.rows == [{"team_id": "g1", "user_id": "keep"}]
+ assert sorted(prisma.db.litellm_usertable.rows) == ["keep"]
+ assert prisma.db.litellm_invitationlink.rows == []
+ assert prisma.db.litellm_organizationmembership.rows == []
+ assert prisma.db.litellm_verificationtoken.rows == [{"token": "k1", "user_id": "u1"}]
+ assert cache.get_cache(key="u1") is None
+
+
+async def test_bulk_delete_deletes_nothing_when_pushes_keep_adding_the_user_to_new_teams():
+ team_numbers = itertools.count()
+
+ def push_adds_another_team(db: _Db) -> None:
+ team_id = f"g{next(team_numbers)}"
+ db.litellm_teamtable.rows[team_id] = _team(team_id, "u1")
+ db.litellm_teammembership.rows.append({"team_id": team_id, "user_id": "u1"})
+
+ prisma = _FakePrisma(users=[_user("u1")], on_user_lock=push_adds_another_team)
+
+ results = await _delete(prisma, ["u1"])
+
+ assert results[0].success is False
+ assert "u1" in prisma.db.litellm_usertable.rows
+ assert all(_roster(prisma, team_id) == ["u1"] for team_id in prisma.db.litellm_teamtable.rows)
+
+
+async def test_bulk_delete_locks_every_user_row_in_id_order_before_rewriting_any_team():
+ prisma = _FakePrisma(
+ users=[_user("u2", "t1"), _user("u10", "t2"), _user("u1", "t1", "t2")],
+ teams=[_team("t1", "u1", "u2"), _team("t2", "u1", "u10")],
+ )
+
+ results = await _delete(prisma, ["u2", "u10", "u1"])
+
+ assert all(result.success for result in results)
+ assert prisma.user_locks == [{"u1": ["t1", "t2"], "u10": ["t2"], "u2": ["t1"]}]
+ assert list(prisma.user_locks[0]) == ["u1", "u10", "u2"]
+
+
@pytest.mark.asyncio
async def test_bulk_delete_reports_missing_and_duplicate_ids_per_item_and_still_deletes_the_rest():
prisma = _FakePrisma(users=[_user("u1")])
@@ -465,6 +635,40 @@ async def test_bulk_delete_evicts_deleted_keys_and_users_from_the_auth_cache():
assert cache.get_cache(key="keep-key") is not None
+class _TeamMembersGauge(PrometheusLogger):
+ def __init__(self) -> None:
+ self.emitted: list[tuple[str, str | None, tuple[str | None, ...]]] = []
+
+ def set_team_members_metric(self, team: LiteLLM_TeamTable) -> None:
+ self.emitted.append((team.team_id, team.team_alias, tuple(m.user_id for m in team.members_with_roles)))
+
+
+def team_members_gauge() -> _TeamMembersGauge:
+ gauge: Final = _TeamMembersGauge()
+ litellm.logging_callback_manager.add_litellm_callback(gauge)
+ return gauge
+
+
+ "remove",
+ [
+ lambda prisma: _delete(prisma, ["u1"]),
+ lambda prisma: _remove(prisma, "t1", [{"user_id": "u1"}]),
+ ],
+ ids=["user_delete", "member_bulk_delete"],
+)
+async def test_team_members_gauge_keeps_the_team_alias_label_after_a_removal(team_members_gauge, remove):
+ prisma = _FakePrisma(
+ users=[_user("u1", "t1"), _user("keep", "t1")], teams=[_team("t1", "u1", "keep", alias="Alpha")]
+ )
+
+ await remove(prisma)
+
+ assert team_members_gauge.emitted == [("t1", "Alpha", ("keep",))]
+
+
@pytest.mark.asyncio
async def test_bulk_delete_evicts_jwt_key_mappings_of_the_deleted_users_keys():
issuer: Final = "https://issuer.example"
@@ -556,6 +760,44 @@ async def test_bulk_member_delete_removes_by_id_and_email_and_keeps_the_rest():
assert prisma.locks == ["t1"] and prisma.roster_reads == ["t1"]
+async def test_bulk_member_delete_keeps_a_team_a_push_added_the_member_to_after_the_delete_read_them():
+ pushed = itertools.count()
+
+ def push_commits_after_the_read(rows: dict[str, _UserRow]) -> None:
+ if next(pushed):
+ return
+ rows["u1"] = rows["u1"].model_copy(update={"teams": [*rows["u1"].teams, "g1"]})
+
+ prisma = _FakePrisma(
+ users=[_user("u1", "t1")],
+ teams=[_team("t1", "u1", "keep"), _team("g1", "u1")],
+ memberships=[("t1", "u1")],
+ after_user_read=push_commits_after_the_read,
+ )
+
+ results = await _remove(prisma, "t1", [{"user_id": "u1"}])
+
+ assert results[0].success is True
+ assert _roster(prisma, "t1") == ["keep"]
+ assert prisma.db.litellm_usertable.rows["u1"].teams == ["g1"]
+
+
+async def test_bulk_member_delete_locks_the_members_rows_in_id_order_before_detaching_them():
+ prisma = _FakePrisma(
+ users=[_user("u2", "t1"), _user("u10", "t1"), _user("u1", "t1")],
+ teams=[_team("t1", "u1", "u2", "u10")],
+ )
+
+ results = await _remove(prisma, "t1", [{"user_id": "u2"}, {"user_id": "u10"}, {"user_id": "u1"}])
+
+ assert all(result.success for result in results)
+ assert prisma.user_locks == [{"u1": ["t1"], "u10": ["t1"], "u2": ["t1"]}]
+ assert list(prisma.user_locks[0]) == ["u1", "u10", "u2"]
+ assert all(user.teams == [] for user in prisma.db.litellm_usertable.rows.values())
+
+
@pytest.mark.asyncio
async def test_bulk_member_delete_reports_members_not_on_the_team_without_rewriting_the_roster():
prisma = _FakePrisma(users=[_user("u1", "t1"), _user("elsewhere")], teams=[_team("t1", "u1")])
diff --git a/tests/unit/proxy/management_helpers/test_team_roster_sync.py b/tests/unit/proxy/management_helpers/test_team_roster_sync.py
new file mode 100644
index 00000000000..de7429a4683
--- /dev/null
+++ b/tests/unit/proxy/management_helpers/test_team_roster_sync.py
@@ -0,0 +1,933 @@
+import asyncio
+import copy
+import hashlib
+import json
+from collections.abc import Awaitable, Callable, Mapping, Sequence
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime
+from typing import Final, Literal
+from unittest.mock import patch
+
+import pytest
+from pydantic import BaseModel, ConfigDict, TypeAdapter
+
+import litellm.proxy.common_utils.auth_cache_invalidation_pubsub as pubsub_module
+from litellm.caching.in_memory_cache import InMemoryCache
+from litellm.proxy._types import LiteLLM_TeamTable, LitellmUserRoles, Member, UserAPIKeyAuth
+from litellm.proxy.auth.auth_checks import jwt_key_mapping_cache_key
+from litellm.proxy.common_utils.user_api_key_cache import (
+ UserApiKeyCache,
+ team_membership_auth_cache_key,
+ team_membership_reservation_cache_key,
+)
+from litellm.proxy.management_helpers.team_roster_sync import (
+ MembersMissing,
+ RosterDelta,
+ RosterPlan,
+ RosterSync,
+ RosterTarget,
+ TeamGone,
+ sync_team_roster,
+)
+
+ADMIN: Final = UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin")
+TEAM: Final = "t1"
+READS: Final = ("query_raw", "teamtable.find_unique", "usertable.find_many", "budgettable.find_unique")
+_STRINGS: Final = TypeAdapter(list[str])
+_FILTER: Final = TypeAdapter(dict[str, object])
+_FILTERS: Final = TypeAdapter(list[dict[str, object]])
+_MEMBERS: Final = TypeAdapter(list[Member])
+
+
+class _UserRow(BaseModel):
+ model_config = ConfigDict(extra="allow")
+
+ user_id: str
+ user_email: str | None = None
+ teams: list[str] = []
+
+
+class _Record(BaseModel):
+ """Attribute access like a Prisma row, over whatever columns the test seeded."""
+
+ model_config = ConfigDict(extra="allow")
+
+
+class _Ledger:
+ """Every statement the fake ran, shared by reference so a transaction snapshot never forks it."""
+
+ def __init__(self) -> None:
+ self.statements: list[str] = []
+ self.locked_users: list[list[str]] = []
+
+ def __deepcopy__(self, memo: dict[int, object]) -> "_Ledger":
+ return self
+
+
+def _clause_matches(row: Mapping[str, object], field: str, clause: object) -> bool:
+ if field == "OR":
+ return any(_matches(row, inner) for inner in _FILTERS.validate_python(clause))
+ if field == "AND":
+ return all(_matches(row, inner) for inner in _FILTERS.validate_python(clause))
+ if field == "NOT":
+ return not _matches(row, _FILTER.validate_python(clause))
+ if not isinstance(clause, dict):
+ return row.get(field) == clause
+ operator = _FILTER.validate_python(clause)
+ if "in" in operator:
+ return row.get(field) in set(_STRINGS.validate_python(operator["in"]))
+ if "has" in operator:
+ return operator["has"] in _STRINGS.validate_python(row.get(field) or [])
+ raise AssertionError(f"unsupported filter {field}={clause!r}")
+
+
+def _matches(row: Mapping[str, object], where: Mapping[str, object]) -> bool:
+ return all(_clause_matches(row, field, clause) for field, clause in where.items())
+
+
+class _Rows:
+ """A list-backed Prisma table over the filters the roster sync issues."""
+
+ def __init__(self, name: str, ledger: _Ledger, rows: Sequence[Mapping[str, object]] = ()) -> None:
+ self.name = name
+ self.ledger = ledger
+ self.rows: list[dict[str, object]] = [dict(r) for r in rows]
+
+ def _ran(self, method: str) -> None:
+ self.ledger.statements.append(f"{self.name}.{method}")
+
+ async def find_many(self, where: Mapping[str, object]) -> list[_Record]:
+ self._ran("find_many")
+ return [_Record.model_validate(r) for r in self.rows if _matches(r, where)]
+
+ async def find_unique(self, where: Mapping[str, object]) -> _Record | None:
+ self._ran("find_unique")
+ return next((_Record.model_validate(r) for r in self.rows if _matches(r, where)), None)
+
+ async def delete_many(self, where: Mapping[str, object]) -> int:
+ self._ran("delete_many")
+ before = len(self.rows)
+ self.rows = [r for r in self.rows if not _matches(r, where)]
+ return before - len(self.rows)
+
+ async def create_many(self, data: Sequence[Mapping[str, object]], skip_duplicates: bool = False) -> int:
+ self._ran("create_many")
+ present = {(r.get("team_id"), r.get("user_id")) for r in self.rows}
+ fresh = [dict(r) for r in data if not (skip_duplicates and (r.get("team_id"), r.get("user_id")) in present)]
+ self.rows.extend(fresh)
+ return len(fresh)
+
+
+class _UserTable:
+ def __init__(self, ledger: _Ledger, users: Sequence[_UserRow]) -> None:
+ self.ledger = ledger
+ self.rows: dict[str, _UserRow] = {u.user_id: u for u in users}
+
+ async def find_many(self, where: Mapping[str, object]) -> list[_UserRow]:
+ self.ledger.statements.append("usertable.find_many")
+ return [u for u in self.rows.values() if _matches(u.model_dump(), where)]
+
+ async def update_many(self, where: Mapping[str, object], data: Mapping[str, Mapping[str, Sequence[str]]]) -> int:
+ self.ledger.statements.append("usertable.update_many")
+ hit = [u for u in self.rows.values() if _matches(u.model_dump(), where)]
+ for user in hit:
+ self.rows[user.user_id] = user.model_copy(update={"teams": [*user.teams, *data["teams"]["push"]]})
+ return len(hit)
+
+ def detach(self, team_id: str, user_ids: Sequence[str]) -> None:
+ for user in (self.rows[user_id] for user_id in user_ids if user_id in self.rows):
+ self.rows[user.user_id] = user.model_copy(update={"teams": [t for t in user.teams if t != team_id]})
+
+
+class _TeamTable:
+ def __init__(self, ledger: _Ledger, teams: Sequence[LiteLLM_TeamTable], deleted_before_update: bool) -> None:
+ """``deleted_before_update`` stands for a team delete that commits after the roster read, before its write."""
+ self.ledger = ledger
+ self.rows: dict[str, LiteLLM_TeamTable] = {t.team_id: t for t in teams}
+ self.deleted_before_update = deleted_before_update
+
+ async def find_unique(self, where: Mapping[str, str]) -> LiteLLM_TeamTable | None:
+ self.ledger.statements.append("teamtable.find_unique")
+ return self.rows.get(where["team_id"])
+
+ async def update(self, where: Mapping[str, str], data: Mapping[str, str]) -> LiteLLM_TeamTable | None:
+ self.ledger.statements.append("teamtable.update")
+ if self.deleted_before_update:
+ return None
+ roster = _MEMBERS.validate_json(data["members_with_roles"])
+ updated = self.rows[where["team_id"]].model_copy(
+ update={"members_with_roles": roster, "updated_at": datetime.now(UTC)}
+ )
+ self.rows[where["team_id"]] = updated
+ return updated
+
+
+class _Db:
+ def __init__(
+ self,
+ ledger: _Ledger,
+ users: Sequence[_UserRow],
+ teams: Sequence[LiteLLM_TeamTable],
+ memberships: Sequence[tuple[str, str]],
+ tokens: Sequence[Mapping[str, object]],
+ budgets: Sequence[Mapping[str, object]],
+ jwt_mappings: Sequence[Mapping[str, object]],
+ team_deleted_before_update: bool = False,
+ ) -> None:
+ self.litellm_usertable = _UserTable(ledger, users)
+ self.litellm_teamtable = _TeamTable(ledger, teams, team_deleted_before_update)
+ self.litellm_teammembership = _Rows(
+ "teammembership", ledger, [{"team_id": t, "user_id": u, "budget_id": None} for t, u in memberships]
+ )
+ self.litellm_verificationtoken = _Rows("verificationtoken", ledger, tokens)
+ self.litellm_deletedverificationtoken = _Rows("deletedverificationtoken", ledger)
+ self.litellm_budgettable = _Rows("budgettable", ledger, budgets)
+ self.litellm_jwtkeymapping = _Rows("jwtkeymapping", ledger, jwt_mappings)
+
+
+class _Tx:
+ def __init__(self, db: _Db, ledger: _Ledger) -> None:
+ self.litellm_usertable = db.litellm_usertable
+ self.litellm_teamtable = db.litellm_teamtable
+ self.litellm_teammembership = db.litellm_teammembership
+ self.litellm_verificationtoken = db.litellm_verificationtoken
+ self.litellm_deletedverificationtoken = db.litellm_deletedverificationtoken
+ self.litellm_budgettable = db.litellm_budgettable
+ self.ledger = ledger
+
+ async def query_raw(self, sql: str, *args: object) -> list[dict[str, object]]:
+ self.ledger.statements.append("query_raw")
+ if "pg_advisory_xact_lock" in sql:
+ assert args == (TEAM,)
+ return [{"locked": False}]
+ assert 'ORDER BY user_id COLLATE "C" FOR UPDATE' in sql
+ user_ids = _STRINGS.validate_python(args[0])
+ self.ledger.locked_users.append(user_ids)
+ return [{"user_id": user_id} for user_id in user_ids if user_id in self.litellm_usertable.rows]
+
+ async def execute_raw(self, sql: str, *args: object) -> int:
+ self.ledger.statements.append("execute_raw")
+ assert "array_remove(teams, $1)" in sql
+ user_ids = _STRINGS.validate_python(args[1])
+ self.litellm_usertable.detach(str(args[0]), user_ids)
+ return len(user_ids)
+
+
+class _FakePrisma:
+ def __init__(
+ self,
+ users: Sequence[_UserRow] = (),
+ teams: Sequence[LiteLLM_TeamTable] = (),
+ memberships: Sequence[tuple[str, str]] = (),
+ tokens: Sequence[Mapping[str, object]] = (),
+ budgets: Sequence[Mapping[str, object]] = (),
+ jwt_mappings: Sequence[Mapping[str, object]] = (),
+ fail_commit: bool = False,
+ replica_teams: Sequence[LiteLLM_TeamTable] | None = None,
+ team_deleted_before_update: bool = False,
+ ) -> None:
+ """``db`` is the routed client, which a read replica may serve; ``writer_db`` is the writer."""
+ self.ledger = _Ledger()
+ self.writer_db = _Db(
+ self.ledger, users, teams, memberships, tokens, budgets, jwt_mappings, team_deleted_before_update
+ )
+ self.db = (
+ _Db(self.ledger, users, replica_teams, memberships, tokens, budgets, jwt_mappings)
+ if replica_teams is not None
+ else self.writer_db
+ )
+ self._fail_commit = fail_commit
+ self.transactions = 0
+
+ @asynccontextmanager
+ async def tx(self, *, timeout: object = None):
+ self.transactions += 1
+ snapshot = copy.deepcopy(self.writer_db)
+ try:
+ yield _Tx(self.writer_db, self.ledger)
+ if self._fail_commit:
+ raise RuntimeError("connection reset")
+ except BaseException:
+ self.writer_db.__dict__.update(snapshot.__dict__)
+ raise
+
+
+def _member(user_id: str, role: Literal["admin", "user"] = "user") -> Member:
+ return Member(user_id=user_id, user_email=f"{user_id}@example.com", role=role)
+
+
+def _team(
+ *members: Member,
+ default_team_member_models: list[str] | None = None,
+ metadata: dict[str, object] | None = None,
+) -> LiteLLM_TeamTable:
+ return LiteLLM_TeamTable(
+ team_id=TEAM,
+ members_with_roles=list(members),
+ default_team_member_models=default_team_member_models,
+ metadata=metadata,
+ )
+
+
+def _user(user_id: str, *teams: str) -> _UserRow:
+ return _UserRow(user_id=user_id, user_email=f"{user_id}@example.com", teams=list(teams))
+
+
+def _roster(prisma: _FakePrisma) -> list[tuple[str | None, str]]:
+ return [(m.user_id, m.role) for m in prisma.writer_db.litellm_teamtable.rows[TEAM].members_with_roles]
+
+
+def _memberships(prisma: _FakePrisma) -> list[tuple[object, object]]:
+ return sorted((r["team_id"], r["user_id"]) for r in prisma.writer_db.litellm_teammembership.rows)
+
+
+def _membership_budget(prisma: _FakePrisma, user_id: str) -> object:
+ return next(r["budget_id"] for r in prisma.writer_db.litellm_teammembership.rows if r["user_id"] == user_id)
+
+
+def _teams_of(prisma: _FakePrisma, user_id: str) -> list[str]:
+ return prisma.writer_db.litellm_usertable.rows[user_id].teams
+
+
+def _tokens(prisma: _FakePrisma) -> set[object]:
+ return {r["token"] for r in prisma.writer_db.litellm_verificationtoken.rows}
+
+
+def _writes(prisma: _FakePrisma) -> list[str]:
+ return [s for s in prisma.ledger.statements if s not in READS]
+
+
+def _cache_with(*keys: str) -> UserApiKeyCache:
+ cache = UserApiKeyCache()
+ for key in keys:
+ cache.set_cache(key=key, value={"cache_key": key})
+ return cache
+
+
+async def _sync(prisma: _FakePrisma, plan: RosterPlan, cache: UserApiKeyCache | None = None):
+ return await sync_team_roster(
+ prisma_client=prisma, # pyright: ignore[reportArgumentType] # fake stands in for PrismaClient
+ team_id=TEAM,
+ plan=plan,
+ user_api_key_dict=ADMIN,
+ litellm_proxy_admin_name="default_user_id",
+ user_api_key_cache=cache or UserApiKeyCache(),
+ proxy_logging_obj=None,
+ )
+
+
+async def test_target_adds_the_missing_members_and_removes_the_extra_ones():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM, "t2"), _user("carol")],
+ teams=[_team(_member("alice", role="admin"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob")],
+ )
+ cache = _cache_with("bob", "carol", f"team_id:{TEAM}")
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"alice", "carol"})), cache)
+
+ assert isinstance(outcome, RosterSync)
+ assert (outcome.added, outcome.removed) == (frozenset({"carol"}), frozenset({"bob"}))
+ written = prisma.writer_db.litellm_teamtable.rows[TEAM]
+ assert written.updated_at is not None and outcome.team.updated_at == written.updated_at
+ assert [(m.user_id, m.user_email, m.role) for m in outcome.team.members_with_roles] == [
+ ("alice", "[email protected]", "admin"),
+ ("carol", "[email protected]", "user"),
+ ]
+ assert _roster(prisma) == [("alice", "admin"), ("carol", "user")]
+ assert _memberships(prisma) == [(TEAM, "alice"), (TEAM, "carol")]
+ assert (_teams_of(prisma, "bob"), _teams_of(prisma, "carol")) == (["t2"], [TEAM])
+ assert (cache.get_cache("bob"), cache.get_cache("carol"), cache.get_cache(f"team_id:{TEAM}")) == (None, None, None)
+
+
+async def test_delta_touches_only_the_named_members_and_tolerates_drift():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM), _user("carol", TEAM), _user("dave")],
+ teams=[_team(_member("alice"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob"), (TEAM, "carol")],
+ )
+
+ outcome = await _sync(prisma, RosterDelta(add=frozenset({"alice", "carol"}), remove=frozenset({"bob", "dave"})))
+
+ assert isinstance(outcome, RosterSync)
+ assert (outcome.added, outcome.removed) == (frozenset({"carol"}), frozenset({"bob"}))
+ assert _roster(prisma) == [("alice", "user"), ("carol", "user")]
+ assert _memberships(prisma) == [(TEAM, "alice"), (TEAM, "carol")]
+ assert (_teams_of(prisma, "alice"), _teams_of(prisma, "carol"), _teams_of(prisma, "bob")) == (
+ [TEAM],
+ [TEAM],
+ [],
+ )
+
+
+async def test_a_plan_matching_the_roster_only_takes_the_lock_and_leaves_the_cached_team_in_place():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM)],
+ teams=[_team(_member("alice"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob")],
+ )
+ cache = _cache_with(f"team_id:{TEAM}")
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"alice", "bob"})), cache)
+
+ assert isinstance(outcome, RosterSync)
+ assert (outcome.added, outcome.removed) == (frozenset(), frozenset())
+ assert prisma.ledger.statements == ["query_raw", "teamtable.find_unique"]
+ assert cache.get_cache(f"team_id:{TEAM}") is not None
+
+
+async def test_a_delta_naming_nobody_reads_the_team_without_the_lock_or_a_transaction():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM)],
+ teams=[_team(_member("alice"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob")],
+ )
+
+ outcome = await _sync(prisma, RosterDelta(add=frozenset(), remove=frozenset()))
+
+ assert isinstance(outcome, RosterSync)
+ assert [m.user_id for m in outcome.team.members_with_roles] == ["alice", "bob"]
+ assert (outcome.added, outcome.removed) == (frozenset(), frozenset())
+ assert prisma.ledger.statements == ["teamtable.find_unique"]
+ assert prisma.transactions == 0
+
+
+async def test_a_delta_naming_nobody_reads_the_team_from_the_writer_not_the_replica():
+ prisma = _FakePrisma(
+ teams=[_team(_member("alice")).model_copy(update={"team_alias": "renamed"})],
+ replica_teams=[_team(_member("alice")).model_copy(update={"team_alias": "stale"})],
+ )
+
+ outcome = await _sync(prisma, RosterDelta(add=frozenset(), remove=frozenset()))
+
+ assert isinstance(outcome, RosterSync)
+ assert outcome.team.team_alias == "renamed"
+
+
+async def test_every_member_row_the_plan_touches_is_locked_in_id_order_before_the_first_write():
+ prisma = _FakePrisma(
+ users=[_user("carol", TEAM), _user("alice"), _user("bob")],
+ teams=[_team(_member("carol"))],
+ memberships=[(TEAM, "carol")],
+ )
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"bob", "alice"})))
+
+ assert isinstance(outcome, RosterSync)
+ assert (outcome.added, outcome.removed) == (frozenset({"alice", "bob"}), frozenset({"carol"}))
+ assert prisma.ledger.locked_users == [["alice", "bob", "carol"]]
+ first_write = next(index for index, statement in enumerate(prisma.ledger.statements) if statement not in READS)
+ assert prisma.ledger.statements.index("query_raw", 1) < first_write
+
+
+async def test_a_deleted_team_answers_team_gone_without_writing():
+ prisma = _FakePrisma(users=[_user("alice")])
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"alice"})))
+
+ assert outcome == TeamGone(team_id=TEAM)
+ assert _writes(prisma) == []
+
+
+async def test_a_team_deleted_before_the_roster_write_answers_team_gone_and_rolls_back_the_member_writes():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob")],
+ teams=[_team(_member("alice"))],
+ memberships=[(TEAM, "alice")],
+ tokens=[{"token": "k-alice", "user_id": "alice", "team_id": TEAM}],
+ team_deleted_before_update=True,
+ )
+ cache = _cache_with("k-alice", "alice")
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"bob"})), cache)
+
+ assert outcome == TeamGone(team_id=TEAM)
+ assert _memberships(prisma) == [(TEAM, "alice")]
+ assert (_teams_of(prisma, "alice"), _teams_of(prisma, "bob")) == ([TEAM], [])
+ assert _tokens(prisma) == {"k-alice"}
+ assert prisma.writer_db.litellm_deletedverificationtoken.rows == []
+ assert cache.get_cache("k-alice") is not None and cache.get_cache("alice") is not None
+
+
+async def test_an_unknown_member_answers_members_missing_and_leaves_the_roster_alone():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM)],
+ teams=[_team(_member("alice"))],
+ memberships=[(TEAM, "alice")],
+ )
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"zed", "ghost"})))
+
+ assert outcome == MembersMissing(team_id=TEAM, user_ids=("ghost", "zed"))
+ assert _roster(prisma) == [("alice", "user")]
+ assert _memberships(prisma) == [(TEAM, "alice")]
+ assert _teams_of(prisma, "alice") == [TEAM]
+ assert _writes(prisma) == []
+
+
+async def test_added_members_each_get_a_budget_when_the_team_scopes_member_models():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("carol"), _user("dave")],
+ teams=[_team(_member("alice"), default_team_member_models=["gpt-x"])],
+ memberships=[(TEAM, "alice")],
+ )
+
+ await _sync(prisma, RosterDelta(add=frozenset({"carol", "dave"}), remove=frozenset()))
+
+ budgets = prisma.writer_db.litellm_budgettable.rows
+ assert [(b["allowed_models"], b["created_by"], b["updated_by"]) for b in budgets] == [
+ (("gpt-x",), "admin", "admin")
+ ] * 2
+ assert {_membership_budget(prisma, "carol"), _membership_budget(prisma, "dave")} == {
+ b["budget_id"] for b in budgets
+ }
+ assert len({b["budget_id"] for b in budgets}) == 2
+ assert _membership_budget(prisma, "alice") is None
+
+
+ ("budgets", "expected_budget_id"),
+ [([{"budget_id": "b-team"}], "b-team"), ([], None)],
+ ids=["budget-row-present", "budget-row-gone"],
+)
+async def test_added_members_link_the_team_member_budget_when_the_team_names_one(
+ budgets: list[dict[str, object]], expected_budget_id: str | None
+):
+ prisma = _FakePrisma(
+ users=[_user("carol")],
+ teams=[_team(metadata={"team_member_budget_id": "b-team"})],
+ budgets=budgets,
+ )
+
+ await _sync(prisma, RosterDelta(add=frozenset({"carol"}), remove=frozenset()))
+
+ assert _membership_budget(prisma, "carol") == expected_budget_id
+ assert len(prisma.writer_db.litellm_budgettable.rows) == len(budgets)
+
+
+async def test_removed_members_lose_their_team_keys_and_every_cache_entry_for_them():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM, "t2")],
+ teams=[_team(_member("alice"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob")],
+ tokens=[
+ {"token": "k-bob", "user_id": "bob", "team_id": TEAM},
+ {"token": "k-bob-personal", "user_id": "bob"},
+ {"token": "k-alice", "user_id": "alice", "team_id": TEAM},
+ ],
+ jwt_mappings=[{"token": "k-bob", "jwt_claim_name": "sub", "jwt_claim_value": "bob-claim", "jwt_issuer": None}],
+ )
+ jwt_key = jwt_key_mapping_cache_key("sub", "bob-claim", None)
+ cache = _cache_with("k-bob", "k-alice", jwt_key, "bob")
+
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset({"alice"})), cache)
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset({"bob"})
+ assert _tokens(prisma) == {"k-bob-personal", "k-alice"}
+ assert [(r["token"], r["deleted_by"]) for r in prisma.writer_db.litellm_deletedverificationtoken.rows] == [
+ ("k-bob", "admin")
+ ]
+ assert _teams_of(prisma, "bob") == ["t2"]
+ assert (cache.get_cache("k-bob"), cache.get_cache(jwt_key), cache.get_cache("bob")) == (None, None, None)
+ assert cache.get_cache("k-alice") is not None
+
+
+class _Pipeline:
+ def __init__(self, send: Callable[[Sequence[str]], Awaitable[None]]) -> None:
+ self._send = send
+ self._messages: list[str] = []
+
+ def publish(self, channel: str, message: str) -> "_Pipeline":
+ self._messages.append(message)
+ return self
+
+ async def execute(self) -> None:
+ await self._send(tuple(self._messages))
+
+
+class _SlowPublishRedisClient:
+ def __init__(self, round_trip_seconds: float = 0.001) -> None:
+ self.published: list[str] = []
+ self.round_trips = 0
+ self._round_trip_seconds = round_trip_seconds
+
+ async def _send(self, messages: Sequence[str]) -> None:
+ self.round_trips += 1
+ await asyncio.sleep(self._round_trip_seconds)
+ self.published.extend(messages)
+
+ async def publish(self, channel: str, message: str) -> int:
+ await self._send((message,))
+ return 1
+
+ def pipeline(self, transaction: bool = True) -> _Pipeline:
+ return _Pipeline(self._send)
+
+
+class _PubSubRedisCache:
+ namespace = None
+
+ def __init__(self, client: "_SlowPublishRedisClient | _WedgedPublishRedisClient") -> None:
+ self._client = client
+
+ def init_pubsub_client(self) -> "_SlowPublishRedisClient | _WedgedPublishRedisClient":
+ return self._client
+
+
+async def _drain_publishes() -> None:
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
+
+async def test_removing_hundreds_of_members_at_once_broadcasts_every_key_and_member_eviction(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ client = _SlowPublishRedisClient()
+ removed = [f"u{index:03d}" for index in range(500)]
+ prisma = _FakePrisma(
+ users=[_user(u, TEAM) for u in removed],
+ teams=[_team(*(_member(u) for u in removed))],
+ memberships=[(TEAM, u) for u in removed],
+ tokens=[{"token": f"key-{u}-{k}", "user_id": u, "team_id": TEAM} for u in removed for k in range(3)],
+ )
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset()))
+ await _drain_publishes()
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset(removed)
+ broadcast = {json.loads(message)["cache_key"] for message in client.published}
+ assert {f"key-{u}-{k}" for u in removed for k in range(3)} <= broadcast
+ assert set(removed) <= broadcast
+
+
+class _WedgedPublishRedisClient:
+ def __init__(self) -> None:
+ self.release = asyncio.Event()
+
+ async def _send(self, messages: Sequence[str]) -> None:
+ await self.release.wait()
+
+ async def publish(self, channel: str, message: str) -> int:
+ await self._send((message,))
+ return 1
+
+ def pipeline(self, transaction: bool = True) -> _Pipeline:
+ return _Pipeline(self._send)
+
+
+async def test_removing_members_clears_this_worker_before_waiting_on_a_wedged_redis(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.5)
+ client = _WedgedPublishRedisClient()
+ removed = [f"u{index:03d}" for index in range(300)]
+ token_of = {u: hashlib.sha256(f"key-{u}".encode()).hexdigest() for u in removed}
+ member_keys = [
+ key
+ for u in removed
+ for key in (
+ u,
+ token_of[u],
+ team_membership_auth_cache_key(team_id=TEAM, user_id=u),
+ team_membership_reservation_cache_key(user_id=u, team_id=TEAM),
+ )
+ ] # comprehension-ok: a test fixture listing each member's four cache keys
+ cache = UserApiKeyCache(
+ in_memory_cache=InMemoryCache(max_size_in_memory=5_000),
+ key_object_in_memory_cache=InMemoryCache(max_size_in_memory=5_000),
+ )
+ for key in member_keys:
+ cache.in_memory_cache_for(key).set_cache(key=key, value={"cache_key": key})
+ seeded = [key for key in member_keys if cache.in_memory_cache_for(key).get_cache(key) is not None]
+ prisma = _FakePrisma(
+ users=[_user(u, TEAM) for u in removed],
+ teams=[_team(*(_member(u) for u in removed))],
+ memberships=[(TEAM, u) for u in removed],
+ tokens=[{"token": token_of[u], "user_id": u, "team_id": TEAM} for u in removed],
+ )
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ sync = asyncio.create_task(_sync(prisma, RosterTarget(member_ids=frozenset()), cache))
+ await asyncio.sleep(0.1)
+ still_cached = [key for key in seeded if cache.in_memory_cache_for(key).get_cache(key) is not None]
+ client.release.set()
+ outcome = await sync
+ await _drain_publishes()
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset(removed)
+ assert seeded == member_keys
+ assert still_cached == []
+
+
+class _AuthRedisCache:
+ namespace = None
+
+ def __init__(self, entries: dict[str, object]) -> None:
+ self.entries = dict(entries)
+ self.round_trips = 0
+
+ async def async_get_cache(self, key: str, **kwargs: object) -> object | None:
+ return self.entries.get(key)
+
+ def set_cache(self, key: str, value: object, **kwargs: object) -> None:
+ self.entries[key] = value
+
+ async def async_set_cache(self, key: str, value: object, **kwargs: object) -> None:
+ self.entries[key] = value
+
+ def delete_cache(self, key: str) -> None:
+ self.entries.pop(key, None)
+
+ async def async_delete_cache(self, key: str) -> None:
+ self.round_trips += 1
+ self.entries.pop(key, None)
+
+ async def delete_cache_keys(self, keys: Sequence[str]) -> None:
+ self.round_trips += 1
+ for key in keys:
+ self.entries.pop(key, None)
+
+
+async def test_removing_members_clears_the_redis_copies_before_waiting_on_a_wedged_redis(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.5)
+ client = _WedgedPublishRedisClient()
+ removed = [f"u{index:03d}" for index in range(300)]
+ token_of = {u: hashlib.sha256(f"key-{u}".encode()).hexdigest() for u in removed}
+ member_keys = [
+ key
+ for u in removed
+ for key in (
+ u,
+ token_of[u],
+ team_membership_auth_cache_key(team_id=TEAM, user_id=u),
+ team_membership_reservation_cache_key(user_id=u, team_id=TEAM),
+ )
+ ] # comprehension-ok: a test fixture listing each member's four cache keys
+ redis = _AuthRedisCache({key: {"cache_key": key} for key in member_keys})
+ cache = UserApiKeyCache(
+ in_memory_cache=InMemoryCache(max_size_in_memory=5_000),
+ key_object_in_memory_cache=InMemoryCache(max_size_in_memory=5_000),
+ )
+ cache.attach_redis_cache(redis) # pyright: ignore[reportArgumentType] # a dict-backed fake of the Redis layer
+ for key in member_keys:
+ cache.in_memory_cache_for(key).set_cache(key=key, value={"cache_key": key})
+ prisma = _FakePrisma(
+ users=[_user(u, TEAM) for u in removed],
+ teams=[_team(*(_member(u) for u in removed))],
+ memberships=[(TEAM, u) for u in removed],
+ tokens=[{"token": token_of[u], "user_id": u, "team_id": TEAM} for u in removed],
+ )
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ sync = asyncio.create_task(_sync(prisma, RosterTarget(member_ids=frozenset()), cache))
+ await asyncio.sleep(0.1)
+ refilled = [key for key in member_keys if await cache.async_get_cache(key=key) is not None]
+ client.release.set()
+ outcome = await sync
+ await _drain_publishes()
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset(removed)
+ assert refilled == []
+ assert not any(key in redis.entries for key in member_keys)
+
+
+class _SlowToAcknowledgeRedisCache(_AuthRedisCache):
+ def __init__(self, entries: dict[str, object]) -> None:
+ super().__init__(entries)
+ self.acknowledge = asyncio.Event()
+
+ async def delete_cache_keys(self, keys: Sequence[str]) -> None:
+ await super().delete_cache_keys(keys)
+ await self.acknowledge.wait()
+
+
+async def test_a_removed_members_team_key_cannot_refill_from_redis_while_the_eviction_waits_on_redis(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.5)
+ token = hashlib.sha256(b"key-bob").hexdigest()
+ redis = _SlowToAcknowledgeRedisCache({token: {"token": token}})
+ cache = UserApiKeyCache()
+ cache.attach_redis_cache(redis) # pyright: ignore[reportArgumentType] # a dict-backed fake of the Redis layer
+ cache.in_memory_cache_for(token).set_cache(key=token, value={"token": token})
+ prisma = _FakePrisma(
+ users=[_user("bob", TEAM)],
+ teams=[_team(_member("bob"))],
+ memberships=[(TEAM, "bob")],
+ tokens=[{"token": token, "user_id": "bob", "team_id": TEAM}],
+ )
+
+ sync = asyncio.create_task(_sync(prisma, RosterTarget(member_ids=frozenset()), cache))
+ await asyncio.sleep(0.1)
+ served_while_waiting = await cache.async_get_cache(key=token)
+ redis.acknowledge.set()
+ outcome = await sync
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset({"bob"})
+ assert served_while_waiting is None
+ assert token not in redis.entries
+
+
+def _removal_of(removed: Sequence[str]) -> tuple[_FakePrisma, set[str]]:
+ token_of = {u: hashlib.sha256(f"key-{u}".encode()).hexdigest() for u in removed}
+ prisma = _FakePrisma(
+ users=[_user(u, TEAM) for u in removed],
+ teams=[_team(*(_member(u) for u in removed))],
+ memberships=[(TEAM, u) for u in removed],
+ tokens=[{"token": token_of[u], "user_id": u, "team_id": TEAM} for u in removed],
+ )
+ evicted = {
+ key
+ for u in removed
+ for key in (
+ u,
+ token_of[u],
+ team_membership_auth_cache_key(team_id=TEAM, user_id=u),
+ team_membership_reservation_cache_key(user_id=u, team_id=TEAM),
+ )
+ } # comprehension-ok: a test fixture listing each member's four cache keys
+ return prisma, evicted
+
+
+async def test_removing_hundreds_of_members_through_a_slow_redis_broadcasts_every_eviction(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ monkeypatch.setattr(pubsub_module, "_BULK_EVICTION_WAIT_SECONDS", 0.05)
+ client = _SlowPublishRedisClient(round_trip_seconds=0.05)
+ removed = [f"u{index:03d}" for index in range(600)]
+ prisma, evicted = _removal_of(removed)
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset()))
+ await _drain_publishes()
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset(removed)
+ assert evicted <= {json.loads(message)["cache_key"] for message in client.published}
+
+
+async def test_the_redis_round_trips_do_not_grow_with_the_member_count(monkeypatch: pytest.MonkeyPatch):
+ """With a Redis-backed auth cache, removing 850 members used to cost a Redis delete per member."""
+ monkeypatch.setattr(pubsub_module, "_in_flight_publishes", asyncio.Semaphore(16))
+ monkeypatch.setattr(pubsub_module, "_pending_publishes", set())
+ round_trips: dict[int, tuple[int, int]] = {}
+ for size in (5, 300):
+ removed = [f"u{index:03d}" for index in range(size)]
+ prisma, _ = _removal_of(removed)
+ redis = _AuthRedisCache({})
+ cache = UserApiKeyCache()
+ cache.attach_redis_cache(redis) # pyright: ignore[reportArgumentType] # a dict-backed fake of the Redis layer
+ client = _SlowPublishRedisClient()
+
+ with patch(
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.coordination_redis_cache",
+ return_value=_PubSubRedisCache(client),
+ ):
+ outcome = await _sync(prisma, RosterTarget(member_ids=frozenset()), cache)
+ await _drain_publishes()
+
+ assert isinstance(outcome, RosterSync) and outcome.removed == frozenset(removed)
+ round_trips[size] = (redis.round_trips, client.round_trips)
+ assert round_trips[300] == round_trips[5]
+
+
+async def test_a_failed_commit_leaves_every_table_and_cache_entry_as_it_was():
+ prisma = _FakePrisma(
+ users=[_user("alice", TEAM), _user("bob", TEAM), _user("carol")],
+ teams=[_team(_member("alice"), _member("bob"))],
+ memberships=[(TEAM, "alice"), (TEAM, "bob")],
+ tokens=[{"token": "k-bob", "user_id": "bob", "team_id": TEAM}],
+ fail_commit=True,
+ )
+ cache = _cache_with("k-bob", "carol")
+
+ with pytest.raises(RuntimeError, match="connection reset"):
+ await _sync(prisma, RosterTarget(member_ids=frozenset({"alice", "carol"})), cache)
+
+ assert _roster(prisma) == [("alice", "user"), ("bob", "user")]
+ assert _memberships(prisma) == [(TEAM, "alice"), (TEAM, "bob")]
+ assert (_teams_of(prisma, "bob"), _teams_of(prisma, "carol")) == ([TEAM], [])
+ assert _tokens(prisma) == {"k-bob"}
+ assert prisma.writer_db.litellm_deletedverificationtoken.rows == []
+ assert cache.get_cache("k-bob") is not None and cache.get_cache("carol") is not None
+
+
+def _replace_with(member_ids: Sequence[str]) -> RosterPlan:
+ return RosterTarget(member_ids=frozenset(member_ids))
+
+
+def _add(member_ids: Sequence[str]) -> RosterPlan:
+ return RosterDelta(add=frozenset(member_ids), remove=frozenset())
+
+
+def _large_push(size: int) -> tuple[_FakePrisma, list[str], list[str]]:
+ old = [f"old-{index:03d}" for index in range(size)]
+ new = [f"new-{index:03d}" for index in range(size)]
+ prisma = _FakePrisma(
+ users=[*(_user(u, TEAM) for u in old), *(_user(u) for u in new)],
+ teams=[_team(*(_member(u) for u in old), default_team_member_models=["gpt-x"])],
+ memberships=[(TEAM, u) for u in old],
+ tokens=[{"token": f"key-{u}", "user_id": u, "team_id": TEAM} for u in old],
+ )
+ return prisma, old, new
+
+
[email protected](("plan_for", "keeps_old"), [(_replace_with, False), (_add, True)], ids=["replace", "add"])
+async def test_the_statement_count_does_not_grow_with_the_member_count(
+ plan_for: Callable[[Sequence[str]], RosterPlan], keeps_old: bool
+):
+ """A 500-member push used to run thousands of statements, one batch per member."""
+ counts: dict[int, int] = {}
+ for size in (5, 500):
+ prisma, old, new = _large_push(size)
+
+ outcome = await _sync(prisma, plan_for(new))
+
+ assert isinstance(outcome, RosterSync) and outcome.added == frozenset(new)
+ assert {user_id for user_id, _ in _roster(prisma)} == set(new) | (set(old) if keeps_old else set())
+ assert _memberships(prisma) == sorted((TEAM, u) for u in [*new, *(old if keeps_old else [])])
+ assert all(_teams_of(prisma, u) == [TEAM] for u in new)
+ assert _tokens(prisma) == ({f"key-{u}" for u in old} if keeps_old else set())
+ counts[size] = len(prisma.ledger.statements)
+ assert counts[500] == counts[5]