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(team): sweep dangling team references and cache on team delete (#36819)

Yassin Kortam3615cccfef56
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 4d9f0a58bd7..0239368ad0e 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -65,6 +65,7 @@ from litellm.proxy.auth.budget_throttle import (
should_throttle_budget_exceeded,
)
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.cache_pydantic_utils import CacheCodec
from litellm.proxy.common_utils.http_parsing_utils import (
_safe_get_request_headers,
@@ -2016,6 +2017,44 @@ async def _cache_team_object(
)
+async def delete_cache_team_object(
+ team_id: str,
+ team_alias: str | None,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+) -> None:
+ """
+ Evict both keys `_cache_team_object` writes.
+
+ `get_team_object` reads the id key and the JWT `team_alias_jwt_field` path reads the alias key,
+ so leaving either behind keeps a deleted team resolvable for auth until its TTL expires.
+
+ Mirrors `delete_cached_project_object`: evicting locally only reaches the worker handling the
+ delete, so every key is also broadcast to drop the other workers' in-memory copies.
+
+ Eviction is best-effort, matching `_cache_team_object`. `delete_team` calls this after the team
+ rows are already gone, so letting an unreachable cache backend raise here would fail a request
+ whose delete has committed.
+ """
+ keys: Final = (f"team_id:{team_id}", *((f"team_alias:{team_alias}",) if team_alias else ()))
+
+ for key in keys:
+ try:
+ user_api_key_cache.delete_cache(key=key)
+
+ ## UPDATE REDIS CACHE ##
+ if proxy_logging_obj is not None:
+ await proxy_logging_obj.internal_usage_cache.dual_cache.async_delete_cache(key=key)
+ except Exception as e: # noqa: BLE001 # best-effort invalidation: any cache backend error must not abort the delete
+ verbose_proxy_logger.warning(
+ "Failed to invalidate cached team entry %s on delete; "
+ "a deleted team may be served until its TTL expires: %s",
+ key,
+ e,
+ )
+ await publish_auth_cache_invalidation(cache_key=key)
+
+
async def _cache_key_object(
hashed_token: str,
user_api_key_obj: UserAPIKeyAuth,
@@ -2068,6 +2107,44 @@ class TeamNotFoundError(HTTPException):
)
+async def delete_cache_key_objects(
+ hashed_tokens: Sequence[str],
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging | None,
+) -> None:
+ """
+ Evict a batch of key objects, for callers that delete keys in bulk rather than through
+ `/key/delete`. Auth resolves a cached key object without re-reading its team, so a key left
+ cached after its row is gone keeps buying access until its TTL expires.
+
+ Evicting locally only reaches this worker, so each token is also broadcast: a deleted key left
+ in a peer worker's in-memory cache still authenticates there until its TTL expires.
+
+ 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,
+ )
+ await publish_auth_cache_invalidation(cache_key=hashed_token)
+
+
@log_db_metrics
async def _get_team_db_check(
team_id: str, prisma_client: PrismaClient, team_id_upsert: bool | None = None
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 452828edc9e..b72b5d218b2 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -77,6 +77,8 @@ from litellm.proxy.auth.auth_checks import (
_cache_team_object,
allowed_route_check_inside_route,
can_org_access_model,
+ delete_cache_key_objects,
+ delete_cache_team_object,
get_org_object,
get_team_membership,
get_team_object,
@@ -313,6 +315,11 @@ class _TeamIdInFilter(TypedDict, total=False):
team_id: Mapping[str, Sequence[str]]
+_STRIP_DELETED_TEAM_FROM_USERS_SQL: Final = """
+UPDATE "LiteLLM_UserTable" SET teams = array_remove(teams, $1) WHERE $1 = ANY(teams)
+"""
+
+
def _team_db(prisma_client: PrismaClient | None) -> "_PrismaTableActions[LiteLLM_TeamTable]":
return _typed_table(TeamRepository(prisma_client), LiteLLM_TeamTable)
@@ -2657,6 +2664,11 @@ async def _add_team_members_to_team(
serialize on the row lock and each appends onto the other's committed
result, instead of both rewriting the whole JSON array from a stale
snapshot (which silently drops one member on the losing write).
+
+ The same lock serializes this against /team/delete: the delete cannot remove
+ the row while the reconcile holds it, and a reconcile that finds the row
+ already gone cleans up after itself rather than leaving the member pointing
+ at a deleted team id.
"""
# Process and add new members
updated_users, updated_team_memberships = await _process_team_members(
@@ -2667,11 +2679,42 @@ async def _add_team_members_to_team(
litellm_proxy_admin_name=litellm_proxy_admin_name,
)
- async with prisma_client.tx() as tx:
- complete_team_data.members_with_roles = await TeamRepository(prisma_client).get_members_with_roles_locked(
- tx, data.team_id
+ updated_team: Final = await _write_members_with_roles_locked(
+ data=data,
+ complete_team_data=complete_team_data,
+ prisma_client=prisma_client,
+ updated_users=updated_users,
+ )
+ if updated_team is None:
+ await _sweep_deleted_team_references(team_ids=(data.team_id,), prisma_client=prisma_client)
+ raise HTTPException(
+ status_code=404,
+ detail={"error": f"Team={data.team_id} was deleted while this member add was running"},
)
+ return updated_team, updated_users, updated_team_memberships
+
+
+async def _write_members_with_roles_locked(
+ data: TeamMemberAddRequest,
+ complete_team_data: LiteLLM_TeamTable,
+ prisma_client: PrismaClient,
+ updated_users: list[LiteLLM_UserTable],
+) -> LiteLLM_TeamTable | None:
+ """Reconcile members_with_roles under the team row lock. None when the team row is gone.
+
+ That read is at least as recent as the user and membership writes the caller
+ already made, so a missing row means /team/delete committed after them. Its
+ post-delete sweep can have run before those writes landed, which is why the
+ caller sweeps this team id again rather than only reporting the 404.
+ """
+ async with prisma_client.tx() as tx:
+ locked_members: Final = await TeamRepository(prisma_client).get_members_with_roles_locked(tx, data.team_id)
+ if locked_members is None:
+ return None
+
+ complete_team_data.members_with_roles = locked_members
+
await _update_team_members_list(
data=data,
complete_team_data=complete_team_data,
@@ -2679,13 +2722,11 @@ async def _add_team_members_to_team(
)
_db_team_members: Final = [m.model_dump() for m in complete_team_data.members_with_roles]
- updated_team: Final = await tx.litellm_teamtable.update(
+ return await tx.litellm_teamtable.update(
where={"team_id": data.team_id},
data={"members_with_roles": json.dumps(_db_team_members)},
)
- return updated_team, updated_users, updated_team_memberships
-
def _emit_team_members_metric(team: LiteLLM_TeamTable) -> None:
"""Update the Prometheus team members gauge after a membership change.
@@ -3653,6 +3694,8 @@ async def delete_team(
create_audit_log_for_update,
litellm_proxy_admin_name,
prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
)
if prisma_client is None:
@@ -3746,6 +3789,12 @@ async def delete_team(
await prisma_client.delete_data(team_id_list=data.team_ids, table_name="key")
+ await _invalidate_deleted_key_cache(
+ keys=keys_to_delete,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
## DELETE ASSOCIATED BYOK MODELS
# Runs before the team rows are deleted so a mid-flight failure never leaves
# the team gone with its models orphaned.
@@ -3779,11 +3828,90 @@ async def delete_team(
)
await asyncio.gather(*tasks)
+ await _sweep_deleted_team_references(team_ids=data.team_ids, prisma_client=prisma_client)
+
## DELETE TEAMS
deleted_teams: Final = await prisma_client.delete_data(team_id_list=data.team_ids, table_name="team")
+
+ # Evict AFTER the rows are gone. Both writers of these keys (`_cache_team_object` and
+ # `get_team_object_by_alias`) hydrate from the db, so evicting first leaves a window where a
+ # concurrent auth lookup re-caches the still-present team and the delete looks like it never
+ # invalidated anything. Nothing fallible runs between the delete and this, or a failure there
+ # would strand the deleted team in cache.
+ await _invalidate_deleted_team_cache(
+ teams=team_rows,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ # Sweep again now the team is gone. A `/team/member_add` that landed between the first sweep
+ # and the delete would have re-appended the reference; an add still in flight sees the row
+ # missing under its own row lock and sweeps what it wrote. Both passes are idempotent, and
+ # keeping the first one means a failure here still leaves a team the admin can retry deleting.
+ await _sweep_deleted_team_references(team_ids=data.team_ids, prisma_client=prisma_client)
+
return deleted_teams
+async def _sweep_deleted_team_references(team_ids: Sequence[str], prisma_client: PrismaClient) -> None:
+ """
+ Strip the deleted team ids from every user row and team-membership row that still references them.
+
+ The per-member `team_member_delete` pass above only reaches users listed in the team's
+ `members_with_roles`, so a user row that outlived its roster entry is invisible to it and keeps
+ surfacing the team on `/user/info` after the team is gone.
+
+ #36839 closed the route that created that drift, by resolving member removal off the roster
+ entry's `user_id` rather than the identifier the caller happened to pass. It does not backfill
+ 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.
+ """
+ for team_id in team_ids:
+ _ = await prisma_client.db.execute_raw(_STRIP_DELETED_TEAM_FROM_USERS_SQL, team_id)
+
+ _ = await _team_membership_db(prisma_client).delete_many(where=_TeamIdInFilter(team_id={"in": tuple(team_ids)}))
+
+
+async def _invalidate_deleted_key_cache(
+ keys: Sequence[LiteLLM_VerificationToken],
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging,
+) -> None:
+ """
+ Evict the auth cache entry for every key deleted along with the team.
+
+ `/key/delete` evicts as it goes, but the bulk delete above writes straight to the db. Auth
+ resolves a cached key object without re-reading the team, so a key belonging to a deleted team
+ keeps buying access until its TTL expires.
+ """
+ await delete_cache_key_objects(
+ hashed_tokens=tuple(key.token for key in keys),
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+async def _invalidate_deleted_team_cache(
+ teams: Sequence[LiteLLM_TeamTable],
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging,
+) -> None:
+ _ = await asyncio.gather(
+ *(
+ 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,
+ )
+ for team in teams
+ )
+ )
+
+
def _transform_teams_to_deleted_records(
teams: list[LiteLLM_TeamTable],
user_api_key_dict: UserAPIKeyAuth,
diff --git a/litellm/repositories/team_repository.py b/litellm/repositories/team_repository.py
index a4908af561a..7efd32288e4 100644
--- a/litellm/repositories/team_repository.py
+++ b/litellm/repositories/team_repository.py
@@ -57,9 +57,13 @@ class TeamRepository(BaseRepository[LiteLLM_TeamTable]):
return LiteLLM_TeamTable.model_validate(data)
- async def get_members_with_roles_locked(self, tx: "Prisma", team_id: str) -> list[Member]:
+ async def get_members_with_roles_locked(self, tx: "Prisma", team_id: str) -> list[Member] | None:
"""Return the team's members_with_roles, locking the row FOR UPDATE.
+ ``None`` when the team row is gone, which a caller holding the lock can
+ only see if a delete committed under it, as opposed to ``[]`` for a team
+ that simply has no members.
+
Must be called inside a transaction so the row lock is held until
commit. This serializes concurrent membership writers on the team row
so the losing writer appends onto the winner's committed result instead
@@ -69,7 +73,9 @@ class TeamRepository(BaseRepository[LiteLLM_TeamTable]):
'SELECT members_with_roles FROM "LiteLLM_TeamTable" WHERE team_id = $1 FOR UPDATE',
team_id,
)
- raw_value: Final = rows[0]["members_with_roles"] if rows else None
+ if not rows:
+ return None
+ raw_value: Final = rows[0]["members_with_roles"]
parsed: Final = json.loads(raw_value) if isinstance(raw_value, str) else raw_value
if not parsed:
return []
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
index fe844db9865..f038af4c7a1 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -4,7 +4,7 @@ import os
import sys
from datetime import datetime, timezone
from typing import Optional, cast
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
from fastapi import HTTPException
@@ -39,6 +39,7 @@ from litellm.proxy.management_endpoints.team_endpoints import (
from litellm.proxy.management_endpoints.team_endpoints import (
GetTeamMemberPermissionsResponse,
UpdateTeamMemberPermissionsRequest,
+ _STRIP_DELETED_TEAM_FROM_USERS_SQL,
_persist_deleted_team_records,
_save_deleted_team_records,
_transform_teams_to_deleted_records,
@@ -1829,6 +1830,63 @@ async def test_add_team_members_reconciles_against_freshly_locked_row():
assert [m.user_id for m in updated_team.members_with_roles] == ["zed", "alice", "bob"]
+async def test_add_team_members_cleans_up_when_the_team_is_deleted_mid_request():
+ """
+ Regression pin for the /team/member_add vs /team/delete race.
+
+ The user row and membership writes land before the reconcile takes the team
+ row lock, so a /team/delete that commits in between has already run its own
+ reference sweep and cannot see them. The empty locked SELECT is the only
+ signal that happened, and leaving it at that would strand the member on a
+ deleted team id, which authorization paths that trust `user.teams` would
+ treat as membership if the id were ever recreated. So the request must sweep
+ the references it just wrote and fail, not report success.
+ """
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ _add_team_members_to_team,
+ )
+
+ tx = MagicMock()
+ tx.query_raw = AsyncMock(return_value=[])
+ tx.litellm_teamtable.update = AsyncMock()
+
+ 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)
+ prisma_client.db.execute_raw = AsyncMock()
+ prisma_client.db.litellm_teammembership.delete_many = AsyncMock()
+
+ with patch(
+ "litellm.proxy.management_endpoints.team_endpoints._process_team_members",
+ new=AsyncMock(return_value=([], [])),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await _add_team_members_to_team(
+ data=TeamMemberAddRequest(
+ team_id="team-deleted-mid-add",
+ member=Member(user_id="bob", role="user"),
+ ),
+ complete_team_data=LiteLLM_TeamTable(team_id="team-deleted-mid-add", 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 exc_info.value.status_code == 404
+ tx.litellm_teamtable.update.assert_not_awaited()
+
+ assert prisma_client.db.execute_raw.await_args_list == [
+ call(_STRIP_DELETED_TEAM_FROM_USERS_SQL, "team-deleted-mid-add")
+ ]
+ prisma_client.db.litellm_teammembership.delete_many.assert_awaited_once_with(
+ where={"team_id": {"in": ("team-deleted-mid-add",)}}
+ )
+
+
def test_add_new_models_to_team_with_existing_models():
"""
Test add_new_models_to_team function with existing models
@@ -7238,6 +7296,367 @@ async def test_delete_team_persists_deleted_teams(monkeypatch):
assert records[0]["litellm_changed_by"] == "admin-user"
+async def test_delete_team_sweeps_references_outside_members_with_roles(monkeypatch):
+ """
+ Regression pin for LIT-5511: a deleted team stayed visible on user records.
+
+ `delete_team` drove all of its cleanup off `team.members_with_roles`, so a user row that
+ referenced the team by any other route (`/user/update`, SSO sync, a membership row written
+ without a matching roster entry) kept the dangling team id forever and `/user/info` kept
+ listing the deleted team. The roster here is deliberately EMPTY, so nothing the per-member
+ `team_member_delete` path does can make this test pass.
+
+ Both cache keys `_cache_team_object` writes are asserted in the same delete: the id key feeds
+ `get_team_object` and the alias key feeds the JWT `team_alias_jwt_field` path, so either one
+ surviving keeps the deleted team resolvable for auth until its TTL expires.
+ """
+ from litellm.proxy._types import DeleteTeamRequest
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ doomed_team = LiteLLM_TeamTable(
+ team_id="team-doomed",
+ team_alias="doomed-team",
+ members_with_roles=[],
+ metadata={},
+ model_max_budget={},
+ model_spend={},
+ )
+
+ cache_state_when_rows_deleted = {}
+
+ async def record_cache_state_then_delete(*args, **kwargs):
+ if kwargs.get("table_name") == "team":
+ cache_state_when_rows_deleted["doomed_still_cached"] = (
+ fresh_cache.get_cache(key="team_id:team-doomed") is not None
+ )
+ return {"deleted_teams": ["team-doomed"]}
+
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=doomed_team)
+ mock_prisma_client.delete_data = AsyncMock(side_effect=record_cache_state_then_delete)
+ mock_prisma_client.db.litellm_deletedteamtable.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+
+ mock_execute_raw = AsyncMock()
+ mock_prisma_client.db.execute_raw = mock_execute_raw
+ mock_membership_delete_many = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.delete_many = mock_membership_delete_many
+
+ mock_tx = AsyncMock()
+ mock_tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_tx_cm = MagicMock()
+ mock_tx_cm.__aenter__ = AsyncMock(return_value=mock_tx)
+ mock_tx_cm.__aexit__ = AsyncMock(return_value=False)
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
+
+ fresh_cache = UserApiKeyCache()
+ for cached_team_id, cached_alias in (
+ ("team-doomed", "doomed-team"),
+ ("team-kept", "kept-team"),
+ ):
+ cached_obj = LiteLLM_TeamTableCachedObj(
+ team_id=cached_team_id, team_alias=cached_alias
+ )
+ fresh_cache.set_cache(key=f"team_id:{cached_team_id}", value=cached_obj)
+ fresh_cache.set_cache(key=f"team_alias:{cached_alias}", value=cached_obj)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", fresh_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", AsyncMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ await delete_team(
+ data=DeleteTeamRequest(team_ids=["team-doomed"]),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin-user",
+ api_key="sk-admin",
+ user_role=LitellmUserRoles.PROXY_ADMIN.value,
+ ),
+ 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"),
+ ], "the sweep must run once before the team row is deleted and again after, so a member_add racing the delete cannot leave the reference behind"
+
+ # same two passes: the second one reaps a membership row inserted while the delete was running
+ assert mock_membership_delete_many.await_args_list == [
+ call(where={"team_id": {"in": ("team-doomed",)}}),
+ call(where={"team_id": {"in": ("team-doomed",)}}),
+ ]
+
+ assert fresh_cache.get_cache(key="team_id:team-doomed") is None
+ assert fresh_cache.get_cache(key="team_alias:doomed-team") is None
+ assert fresh_cache.get_cache(key="team_id:team-kept") is not None
+ assert fresh_cache.get_cache(key="team_alias:kept-team") is not None
+
+ # Eviction must run AFTER the rows are gone: both writers of these keys hydrate from the db,
+ # so evicting first lets a concurrent auth lookup re-cache the still-present team.
+ assert cache_state_when_rows_deleted["doomed_still_cached"] is True
+
+
+async def test_delete_team_evicts_the_auth_cache_of_the_keys_it_deletes(monkeypatch):
+ """
+ A virtual key scoped to the team is deleted from the db with the team, but auth resolves a
+ cached key object without re-reading the team, so leaving the cache entry behind lets that key
+ keep buying access until its TTL expires. Verified live: without this eviction the same key
+ still returns HTTP 200 on /v1/chat/completions right after /team/delete.
+ """
+ from litellm.proxy._types import DeleteTeamRequest, LiteLLM_VerificationToken
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ team = LiteLLM_TeamTable(
+ team_id="team-doomed",
+ team_alias="doomed-team",
+ members_with_roles=[],
+ metadata={},
+ model_max_budget={},
+ model_spend={},
+ )
+ team_key = LiteLLM_VerificationToken(token="hashed-doomed-key", team_id="team-doomed")
+
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team)
+ mock_prisma_client.delete_data = AsyncMock(return_value={"deleted_teams": ["team-doomed"]})
+ mock_prisma_client.db.litellm_deletedteamtable.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[team_key])
+ mock_prisma_client.db.execute_raw = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.delete_many = AsyncMock()
+
+ mock_tx = AsyncMock()
+ mock_tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_tx_cm = MagicMock()
+ mock_tx_cm.__aenter__ = AsyncMock(return_value=mock_tx)
+ mock_tx_cm.__aexit__ = AsyncMock(return_value=False)
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
+
+ fresh_cache = UserApiKeyCache()
+ fresh_cache.set_cache(key="hashed-doomed-key", value=UserAPIKeyAuth(token="hashed-doomed-key", team_id="team-doomed"))
+ fresh_cache.set_cache(key="hashed-unrelated-key", value=UserAPIKeyAuth(token="hashed-unrelated-key"))
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", fresh_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", AsyncMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ await delete_team(
+ data=DeleteTeamRequest(team_ids=["team-doomed"]),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin-user",
+ api_key="sk-admin",
+ user_role=LitellmUserRoles.PROXY_ADMIN.value,
+ ),
+ litellm_changed_by="admin-user",
+ )
+
+ assert fresh_cache.get_cache(key="hashed-doomed-key") is None
+ # a key that had nothing to do with the deleted team must survive
+ assert fresh_cache.get_cache(key="hashed-unrelated-key") is not None
+
+
+async def test_delete_team_failing_reconcile_sweep_cannot_strand_the_team_in_cache(monkeypatch):
+ """
+ The reconcile sweep runs after the team row is committed deleted. If it ran before cache
+ eviction, a sweep failure would return an error with the team gone from the db but still
+ served from cache, which is the exact bug this PR exists to fix.
+ """
+ from litellm.proxy._types import DeleteTeamRequest
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ team = LiteLLM_TeamTable(
+ team_id="team-doomed",
+ team_alias="doomed-team",
+ members_with_roles=[],
+ metadata={},
+ model_max_budget={},
+ model_spend={},
+ )
+
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team)
+ mock_prisma_client.delete_data = AsyncMock(return_value={"deleted_teams": ["team-doomed"]})
+ mock_prisma_client.db.litellm_deletedteamtable.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+ mock_prisma_client.db.litellm_teammembership.delete_many = AsyncMock()
+ # the first sweep succeeds, the post-delete reconcile sweep blows up
+ mock_prisma_client.db.execute_raw = AsyncMock(side_effect=[None, ConnectionError("db went away")])
+
+ mock_tx = AsyncMock()
+ mock_tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_tx_cm = MagicMock()
+ mock_tx_cm.__aenter__ = AsyncMock(return_value=mock_tx)
+ mock_tx_cm.__aexit__ = AsyncMock(return_value=False)
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
+
+ fresh_cache = UserApiKeyCache()
+ cached_obj = LiteLLM_TeamTableCachedObj(team_id="team-doomed", team_alias="doomed-team")
+ fresh_cache.set_cache(key="team_id:team-doomed", value=cached_obj)
+ fresh_cache.set_cache(key="team_alias:doomed-team", value=cached_obj)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", fresh_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", AsyncMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ with pytest.raises(ConnectionError):
+ await delete_team(
+ data=DeleteTeamRequest(team_ids=["team-doomed"]),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin-user",
+ api_key="sk-admin",
+ user_role=LitellmUserRoles.PROXY_ADMIN.value,
+ ),
+ litellm_changed_by="admin-user",
+ )
+
+ # the delete committed, so the cache must not still be serving the team
+ assert fresh_cache.get_cache(key="team_id:team-doomed") is None
+ assert fresh_cache.get_cache(key="team_alias:doomed-team") is None
+
+
+async def test_delete_team_broadcasts_cache_invalidation_to_other_workers(monkeypatch):
+ """
+ Evicting locally only reaches the worker that handled the delete. Without the broadcast, every
+ other worker keeps serving the deleted team, and the deleted team's keys, out of its own
+ in-memory cache until the TTL, so both stay usable for auth cluster-wide.
+ """
+ from litellm.proxy._types import DeleteTeamRequest, LiteLLM_VerificationToken
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ team = LiteLLM_TeamTable(
+ team_id="team-doomed",
+ team_alias="doomed-team",
+ members_with_roles=[],
+ metadata={},
+ model_max_budget={},
+ model_spend={},
+ )
+
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team)
+ mock_prisma_client.delete_data = AsyncMock(return_value={"deleted_teams": ["team-doomed"]})
+ mock_prisma_client.db.litellm_deletedteamtable.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
+ return_value=[LiteLLM_VerificationToken(token="hashed-doomed-key", team_id="team-doomed")]
+ )
+ mock_prisma_client.db.execute_raw = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.delete_many = AsyncMock()
+
+ mock_tx = AsyncMock()
+ mock_tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_tx_cm = MagicMock()
+ mock_tx_cm.__aenter__ = AsyncMock(return_value=mock_tx)
+ mock_tx_cm.__aexit__ = AsyncMock(return_value=False)
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
+
+ published = []
+
+ async def record_publish(cache_key):
+ published.append(cache_key)
+
+ monkeypatch.setattr("litellm.proxy.auth.auth_checks.publish_auth_cache_invalidation", record_publish)
+ 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())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ await delete_team(
+ data=DeleteTeamRequest(team_ids=["team-doomed"]),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin-user",
+ api_key="sk-admin",
+ user_role=LitellmUserRoles.PROXY_ADMIN.value,
+ ),
+ litellm_changed_by="admin-user",
+ )
+
+ # 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"]
+
+
+async def test_delete_team_survives_a_failing_cache_backend(monkeypatch):
+ """
+ Cache eviction runs after the reference sweep has already committed, so a cache backend that
+ is unreachable must not abort the delete. If it did, `/team/delete` would fail with the team
+ row still present but its user references and membership rows already gone.
+ """
+ from litellm.proxy._types import DeleteTeamRequest, LiteLLM_VerificationToken
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ team = LiteLLM_TeamTable(
+ team_id="team-doomed",
+ team_alias="doomed-team",
+ members_with_roles=[],
+ metadata={},
+ model_max_budget={},
+ model_spend={},
+ )
+
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team)
+ mock_delete_data = AsyncMock(return_value={"deleted_teams": ["team-doomed"]})
+ mock_prisma_client.delete_data = mock_delete_data
+ mock_prisma_client.db.litellm_deletedteamtable.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()
+ # a key to evict: its eviction runs after the key rows are already deleted, so it must not
+ # raise either
+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
+ return_value=[LiteLLM_VerificationToken(token="hashed-doomed-key", team_id="team-doomed")]
+ )
+ mock_prisma_client.db.execute_raw = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.delete_many = AsyncMock()
+
+ mock_tx = AsyncMock()
+ mock_tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_tx_cm = MagicMock()
+ mock_tx_cm.__aenter__ = AsyncMock(return_value=mock_tx)
+ mock_tx_cm.__aexit__ = AsyncMock(return_value=False)
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_tx_cm)
+
+ exploding_logging_obj = MagicMock()
+ exploding_logging_obj.internal_usage_cache.dual_cache.async_delete_cache = AsyncMock(
+ side_effect=ConnectionError("redis is down")
+ )
+
+ 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.proxy_logging_obj", exploding_logging_obj)
+ monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", AsyncMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ result = await delete_team(
+ data=DeleteTeamRequest(team_ids=["team-doomed"]),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin-user",
+ api_key="sk-admin",
+ user_role=LitellmUserRoles.PROXY_ADMIN.value,
+ ),
+ litellm_changed_by="admin-user",
+ )
+
+ assert result == {"deleted_teams": ["team-doomed"]}
+ mock_delete_data.assert_any_await(team_id_list=["team-doomed"], table_name="team")
+ assert exploding_logging_obj.internal_usage_cache.dual_cache.async_delete_cache.await_count > 0
+
+
@pytest.mark.asyncio
async def test_team_member_delete_persists_deleted_keys(monkeypatch):
from litellm.proxy._types import TeamMemberDeleteRequest
diff --git a/tests/test_litellm/repositories/test_repositories.py b/tests/test_litellm/repositories/test_repositories.py
index 3f567397e1a..38af52f165c 100644
--- a/tests/test_litellm/repositories/test_repositories.py
+++ b/tests/test_litellm/repositories/test_repositories.py
@@ -546,12 +546,19 @@ class TestTeamRepository:
@pytest.mark.asyncio
async def test_get_members_with_roles_locked_missing_row(self, repo):
+ """None, not [], so a caller can tell a deleted team from an empty one.
+
+ /team/member_add reconciles membership under this lock and has to fail,
+ and clean up the references it already wrote, when a /team/delete
+ committed underneath it. An empty list would look like a live team with
+ no members and it would carry on writing.
+ """
tx = MagicMock()
tx.query_raw = AsyncMock(return_value=[])
members = await repo.get_members_with_roles_locked(tx, "missing")
- assert members == []
+ assert members is None
@pytest.mark.asyncio
async def test_create_team_all_fields(self, repo):