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(proxy): refresh cached team on /team/block and /team/unblock (#35643)

hamzashah-dev9b4f44135dfe
diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.py
index 3195394b9aa..4434fe57ab6 100644
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@ -457,7 +457,6 @@ class _ProxyDBLogger(CustomLogger):
update_cache_read_keys=update_cache_read_keys(
user_id=user_id,
end_user_id=end_user_id,
- team_id=team_id,
tags=tags,
response_cost=response_cost,
),
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 0f40662ad83..0595d23bd9a 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -5343,6 +5343,52 @@ async def team_member_me(
)
+async def _set_team_blocked(
+ team_id: str,
+ blocked: bool,
+ user_api_key_dict: UserAPIKeyAuth,
+) -> "prisma_models.LiteLLM_TeamTable":
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ if prisma_client is None:
+ raise Exception("No DB Connected.")
+
+ existing_team: Final = await _team_db(prisma_client).find_unique(where={"team_id": team_id})
+ if existing_team is None:
+ raise HTTPException(
+ status_code=404,
+ detail={"error": f"Team not found, passed team_id={team_id}"},
+ )
+
+ if not await get_team_access().allows(
+ user_api_key_dict, LiteLLM_TeamTable.model_validate(existing_team.model_dump()), TEAM_OR_ORG_ADMIN
+ ):
+ team_access_denied()
+
+ record: Final = await _team_db(prisma_client).update(
+ where={"team_id": team_id},
+ data={"blocked": blocked},
+ include=_TEAM_UPDATE_INCLUDE,
+ )
+ if record is None:
+ raise HTTPException(
+ status_code=404,
+ detail={"error": f"Team not found, passed team_id={team_id}"},
+ )
+
+ await refresh_cached_team(
+ team_row=record,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ return record.model_copy(update=dict.fromkeys(_TEAM_UPDATE_INCLUDE))
+
+
@router.post("/team/block", tags=["team management"], dependencies=[Depends(user_api_key_auth)])
@management_endpoint_wrapper
async def block_team(
@@ -5372,30 +5418,7 @@ async def block_team(
"""
- from litellm.proxy.proxy_server import prisma_client
-
- if prisma_client is None:
- raise Exception("No DB Connected.")
-
- existing_team: Final = await _team_db(prisma_client).find_unique(where={"team_id": data.team_id})
- if existing_team is None:
- raise HTTPException(
- status_code=404,
- detail={"error": f"Team not found, passed team_id={data.team_id}"},
- )
-
- # Verify caller has access to manage this team
- if not await get_team_access().allows(
- user_api_key_dict, LiteLLM_TeamTable.model_validate(existing_team.model_dump()), TEAM_OR_ORG_ADMIN
- ):
- team_access_denied()
-
- record: Final = await _team_db(prisma_client).update(
- where={"team_id": data.team_id},
- data={"blocked": True},
- )
-
- return record
+ return await _set_team_blocked(team_id=data.team_id, blocked=True, user_api_key_dict=user_api_key_dict)
@router.post("/team/unblock", tags=["team management"], dependencies=[Depends(user_api_key_auth)])
@@ -5421,30 +5444,7 @@ async def unblock_team(
}'
```
"""
- from litellm.proxy.proxy_server import prisma_client
-
- if prisma_client is None:
- raise Exception("No DB Connected.")
-
- existing_team: Final = await _team_db(prisma_client).find_unique(where={"team_id": data.team_id})
- if existing_team is None:
- raise HTTPException(
- status_code=404,
- detail={"error": f"Team not found, passed team_id={data.team_id}"},
- )
-
- # Verify caller has access to manage this team
- if not await get_team_access().allows(
- user_api_key_dict, LiteLLM_TeamTable.model_validate(existing_team.model_dump()), TEAM_OR_ORG_ADMIN
- ):
- team_access_denied()
-
- record: Final = await _team_db(prisma_client).update(
- where={"team_id": data.team_id},
- data={"blocked": False},
- )
-
- return record
+ return await _set_team_blocked(team_id=data.team_id, blocked=False, user_api_key_dict=user_api_key_dict)
@router.get(
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index c1102cee8d1..4ea3100f869 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -4194,7 +4194,6 @@ async def run_spend_counter_pipeline(pending: Sequence[PendingSpendIncrement]) -
def update_cache_read_keys(
user_id: str | None,
end_user_id: str | None,
- team_id: str | None,
tags: Sequence[object] | None,
response_cost: float | None,
) -> tuple[str, ...]:
@@ -4202,9 +4201,8 @@ def update_cache_read_keys(
return ()
user_keys: tuple[str, ...] = (user_id, GLOBAL_PROXY_SPEND_CACHE_KEY) if user_id is not None else ()
end_user_keys: tuple[str, ...] = (end_user_cache_key(end_user_id),) if end_user_id is not None else ()
- team_keys: tuple[str, ...] = (f"team_id:{team_id}",) if team_id is not None else ()
tag_keys: tuple[str, ...] = tuple(tag_cache_key(tag) for tag in tags or () if isinstance(tag, str) and tag)
- return user_keys + end_user_keys + team_keys + tag_keys
+ return user_keys + end_user_keys + tag_keys
_UPDATE_CACHE_PREFETCH_SLOT: Final = "update_cache_read"
@@ -4281,7 +4279,7 @@ async def update_cache(
with service_target(AUTH_OBJECTS_TARGET):
cached_values: Final = await _read_update_cache_values(
keys=update_cache_read_keys(
- user_id=user_id, end_user_id=end_user_id, team_id=team_id, tags=tags, response_cost=response_cost
+ user_id=user_id, end_user_id=end_user_id, tags=tags, response_cost=response_cost
),
parent_otel_span=parent_otel_span,
)
@@ -4431,35 +4429,28 @@ async def update_cache(
)
### UPDATE TEAM SPEND ###
- async def _update_team_cache():
+ def _update_team_cache():
if team_id is None or response_cost is None:
return
_id: Final = f"team_id:{team_id}"
try:
- cached_team: Final = cached_values.get(_id)
- if cached_team is None:
- # do nothing if team not in api key cache
- return
- existing_spend_obj: Final[LiteLLM_TeamTableCachedObj | None] = CacheCodec.deserialize(
- cached_team, LiteLLM_TeamTableCachedObj
+ current_team: Final = CacheCodec.deserialize(
+ user_api_key_cache.get_cache(key=_id, local_only=True), LiteLLM_TeamTableCachedObj
)
- if existing_spend_obj is None:
+ if current_team is None:
return
verbose_proxy_logger.debug(
- "_update_team_db: existing spend: %s; response_cost: %s", existing_spend_obj, response_cost
+ "_update_team_db: existing spend: %s; response_cost: %s", current_team, response_cost
)
-
- existing_spend: Final[float] = existing_spend_obj.spend or 0.0
- # Calculate the new cost by adding the existing cost and response_cost
- new_spend: Final = existing_spend + response_cost
-
- existing_spend_obj.spend = new_spend
- values_to_update_in_cache.append(
- (
- _id,
- CacheCodec.serialize(existing_spend_obj, model_type=LiteLLM_TeamTableCachedObj),
- )
+ user_api_key_cache.set_cache(
+ key=_id,
+ value=CacheCodec.serialize(
+ current_team.model_copy(update={"spend": (current_team.spend or 0.0) + response_cost}),
+ model_type=LiteLLM_TeamTableCachedObj,
+ ),
+ local_only=True,
+ ttl=get_management_object_ttl(user_api_key_cache),
)
except Exception as e:
verbose_proxy_logger.warning(
@@ -4536,7 +4527,7 @@ async def update_cache(
await _update_end_user_cache()
if team_id is not None:
- await _update_team_cache()
+ _update_team_cache()
if tags is not None:
await _update_tag_cache()
diff --git a/tests/integration/management/test_team_block.py b/tests/integration/management/test_team_block.py
index 3d1f9e430ea..9a340944569 100644
--- a/tests/integration/management/test_team_block.py
+++ b/tests/integration/management/test_team_block.py
@@ -1,14 +1,21 @@
+import itertools
+import threading
import uuid
from collections.abc import Iterator
+from concurrent.futures import ThreadPoolExecutor
from typing import Final
import httpx
import pytest
-from pydantic import BaseModel, JsonValue
+from pydantic import BaseModel, ConfigDict, JsonValue
-from tests.integration._support.client import Gateway, string_value
+from tests.integration._support.client import Gateway, eventually, held, string_value
from tests.integration._support.database import read_rows
+IN_FLIGHT_CALLERS_PER_PROXY: Final = 8
+BLOCK_CYCLES: Final = 4
+PROBES_PER_PROXY: Final = 6
+
class _ObservedRequest(BaseModel):
body: dict[str, JsonValue]
@@ -35,6 +42,16 @@ class _ErrorResponse(BaseModel):
error: _ProxyError
+class _Message(BaseModel):
+ model_config = ConfigDict(frozen=True)
+ content: str
+
+
+class _ChatBody(BaseModel):
+ model_config = ConfigDict(frozen=True)
+ messages: tuple[_Message, ...]
+
+
@pytest.fixture
def upstream(gateway: Gateway) -> Iterator[httpx.Client]:
with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:
@@ -58,6 +75,87 @@ def _models(client: httpx.Client) -> tuple[str, ...]:
return tuple(string_value(request.body["model"]) for request in observations.requests)
+def _texts(client: httpx.Client) -> tuple[str, ...]:
+ response: Final = client.get("/__observations")
+ assert response.status_code == 200, response.text
+ observations: Final = _Observations.model_validate_json(response.text)
+ return tuple(
+ message.content
+ for message in itertools.chain.from_iterable(
+ _ChatBody.model_validate(request.body).messages for request in observations.requests
+ )
+ )
+
+
+def _keep_calling(proxy: Gateway, model: str, key: str, stop: threading.Event) -> tuple[int, ...]:
+ return tuple(
+ _chat(proxy, model, key, f"in flight {uuid.uuid4().hex}").status_code
+ for _ in itertools.takewhile(lambda _: not stop.is_set(), itertools.count())
+ )
+
+
+def _statuses_on_fresh_connections(proxies: tuple[Gateway, ...], model: str, key: str, marker: str) -> tuple[int, ...]:
+ return tuple(
+ proxy.request(
+ "POST",
+ "/v1/chat/completions",
+ {"model": model, "messages": [{"role": "user", "content": f"{marker} {uuid.uuid4().hex}"}]},
+ key=key,
+ headers={"connection": "close"},
+ ).status_code
+ for proxy in proxies * PROBES_PER_PROXY
+ )
+
+
+def _block_while_team_traffic_is_in_flight(
+ gateway: Gateway, peer: Gateway, upstream: httpx.Client, model: str, key: str, team: str
+) -> tuple[httpx.Response, tuple[int, ...]]:
+ stop: Final = threading.Event()
+ with ThreadPoolExecutor(max_workers=2 * IN_FLIGHT_CALLERS_PER_PROXY) as pool:
+ callers: Final = tuple(
+ pool.submit(_keep_calling, proxy, model, key, stop)
+ for proxy in (gateway, peer) * IN_FLIGHT_CALLERS_PER_PROXY
+ )
+ try:
+ eventually(
+ lambda: len(_models(upstream)), lambda served: served >= 4 * IN_FLIGHT_CALLERS_PER_PROXY, seconds=30
+ )
+ blocked: Final = gateway.request("POST", "/team/block", {"team_id": team})
+ finally:
+ stop.set()
+ statuses: Final = tuple(itertools.chain.from_iterable(caller.result() for caller in callers))
+ return blocked, statuses
+
+
+def _block_and_unblock_under_team_traffic(
+ gateway: Gateway, peer: Gateway, upstream: httpx.Client, model: str, key: str, team: str, cycle: int
+) -> None:
+ upstream.delete("/__observations").raise_for_status()
+ blocked, in_flight = _block_while_team_traffic_is_in_flight(gateway, peer, upstream, model, key, team)
+ assert blocked.status_code == 200, blocked.text
+ assert in_flight.count(200) >= 4 * IN_FLIGHT_CALLERS_PER_PROXY, repr(in_flight)
+ assert set(in_flight) <= {200, 401}, repr(in_flight)
+
+ marker: Final = f"after block {cycle} {uuid.uuid4().hex}"
+ refused: Final = held(
+ lambda: _statuses_on_fresh_connections((gateway, peer), model, key, marker),
+ lambda statuses: set(statuses) == {401},
+ holding=5,
+ seconds=15,
+ )
+ assert refused == (401,) * (2 * PROBES_PER_PROXY), repr(refused)
+ leaked: Final = tuple(text for text in _texts(upstream) if text.startswith(marker))
+ assert leaked == (), repr(leaked)
+
+ unblocked: Final = gateway.request("POST", "/team/unblock", {"team_id": team})
+ assert unblocked.status_code == 200, unblocked.text
+ eventually(
+ lambda: _statuses_on_fresh_connections((gateway, peer), model, key, f"after unblock {cycle}"),
+ lambda statuses: set(statuses) == {200},
+ seconds=15,
+ )
+
+
def test_team_block_and_unblock_update_endpoint_info_and_db_state(
gateway: Gateway, peer: Gateway, upstream: httpx.Client
) -> None:
@@ -126,8 +224,6 @@ def test_team_block_and_unblock_update_endpoint_info_and_db_state(
def test_unblocking_a_team_restores_warmed_keys_on_both_proxies(
gateway: Gateway, peer: Gateway, upstream: httpx.Client
) -> None:
- pytest.skip("BUG: SLP-605 /team/unblock does not restore warmed team-key access after blocked auth is cached")
-
with gateway.scenario() as scenario:
provider_model: Final = f"team-block-{uuid.uuid4().hex}"
model: Final = scenario.model(model=f"openai/{provider_model}")
@@ -166,8 +262,6 @@ def test_unblocking_a_team_restores_warmed_keys_on_both_proxies(
def test_warmed_team_keys_are_refused_on_both_proxies_after_block(
gateway: Gateway, peer: Gateway, upstream: httpx.Client
) -> None:
- pytest.skip("BUG: SLP-605 blocking a team does not refresh warmed team-key auth state")
-
with gateway.scenario() as scenario:
provider_model: Final = f"team-block-{uuid.uuid4().hex}"
model: Final = scenario.model(model=f"openai/{provider_model}")
@@ -202,8 +296,6 @@ def test_warmed_team_keys_are_refused_on_both_proxies_after_block(
def test_a_new_team_key_is_refused_on_a_peer_that_cached_the_team_before_block(
gateway: Gateway, peer: Gateway, upstream: httpx.Client
) -> None:
- pytest.skip("BUG: SLP-605 a peer proxy that cached the team before /team/block admits a never-seen team key")
-
with gateway.scenario() as scenario:
provider_model: Final = f"team-block-{uuid.uuid4().hex}"
model: Final = scenario.model(model=f"openai/{provider_model}")
@@ -229,3 +321,45 @@ def test_a_new_team_key_is_refused_on_a_peer_that_cached_the_team_before_block(
assert peer_denied.status_code == 401, peer_denied.text
assert _ErrorResponse.model_validate_json(peer_denied.text).error.type == "auth_error", peer_denied.text
assert after_block == (), repr(after_block)
+
+
+def test_a_team_model_alias_still_routes_on_both_proxies_after_block_and_unblock(
+ gateway: Gateway, peer: Gateway, upstream: httpx.Client
+) -> None:
+ with gateway.scenario() as scenario:
+ provider_model: Final = f"team-block-{uuid.uuid4().hex}"
+ model: Final = scenario.model(model=f"openai/{provider_model}")
+ alias: Final = f"alias-{uuid.uuid4().hex}"
+ team: Final = scenario.team(models=[model], model_aliases={alias: model})
+ key: Final = scenario.key(team_id=team, models=[model])
+
+ warmed: Final = tuple(
+ _chat(proxy, alias, key, f"team alias warm {uuid.uuid4().hex}").status_code for proxy in (gateway, peer)
+ )
+ assert warmed == (200, 200), repr(warmed)
+ assert _models(upstream) == (provider_model, provider_model)
+ upstream.delete("/__observations").raise_for_status()
+
+ blocked: Final = gateway.request("POST", "/team/block", {"team_id": team})
+ assert blocked.status_code == 200, blocked.text
+ unblocked: Final = gateway.request("POST", "/team/unblock", {"team_id": team})
+ assert unblocked.status_code == 200, unblocked.text
+
+ after_unblock: Final = _statuses_on_fresh_connections((gateway, peer), alias, key, "team alias after unblock")
+ assert after_unblock == (200,) * (2 * PROBES_PER_PROXY), repr(after_unblock)
+ assert _models(upstream) == (provider_model,) * (2 * PROBES_PER_PROXY)
+
+
+def test_a_block_issued_while_team_traffic_is_in_flight_holds_on_every_worker(
+ gateway: Gateway, peer: Gateway, upstream: httpx.Client
+) -> None:
+ with gateway.scenario() as scenario:
+ provider_model: Final = f"team-block-{uuid.uuid4().hex}"
+ model: Final = scenario.model(
+ model=f"openai/{provider_model}", input_cost_per_token=0.000001, output_cost_per_token=0.000002
+ )
+ team: Final = scenario.team(models=[model])
+ key: Final = scenario.key(team_id=team)
+
+ for cycle in range(BLOCK_CYCLES):
+ _block_and_unblock_under_team_traffic(gateway, peer, upstream, model, key, team, cycle)
diff --git a/tests/unit/proxy/auth/test_jwt.py b/tests/unit/proxy/auth/test_jwt.py
index a7aa379ad37..fb512539126 100644
--- a/tests/unit/proxy/auth/test_jwt.py
+++ b/tests/unit/proxy/auth/test_jwt.py
@@ -860,35 +860,6 @@ async def test_allowed_routes_admin(
import pytest
-async def test_team_cache_update_called():
- import litellm
- from litellm.proxy.proxy_server import user_api_key_cache
-
- # Use setattr to replace the method on the user_api_key_cache object
- cache = DualCache()
-
- setattr(
- litellm.proxy.proxy_server,
- "user_api_key_cache",
- cache,
- )
-
- with patch.object(cache, "async_batch_get_cache", new=AsyncMock(return_value=[None])) as mock_call_cache:
- # Call the function under test
- await litellm.proxy.proxy_server.update_cache(
- token=None,
- user_id=None,
- end_user_id=None,
- team_id="1234",
- response_cost=20,
- parent_otel_span=None,
- ) # type: ignore
-
- await asyncio.sleep(3)
- mock_call_cache.assert_awaited_once_with(keys=["team_id:1234"], parent_otel_span=None, throttle_redis=False)
-
-
@pytest.fixture
def public_jwt_key():
import json
diff --git a/tests/unit/proxy/management_endpoints/test_team_endpoints.py b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
index a379b424aeb..5063ae0b357 100644
--- a/tests/unit/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
@@ -2636,10 +2636,99 @@ async def test_team_model_add_delete_keep_model_aliases_in_team_cache(endpoint_n
assert team_model_aliases(cached_team) == {"fast": "gpt-4o"}
[email protected](("endpoint_name", "blocked"), [("block_team", True), ("unblock_team", False)])
+async def test_team_block_unblock_reach_warmed_auth_on_every_worker(
+ endpoint_name: str, blocked: bool, monkeypatch: pytest.MonkeyPatch
+):
+ import litellm.proxy.common_utils.auth_cache_invalidation_pubsub as pubsub_module
+ from litellm.proxy._types import BlockTeamRequest
+ from litellm.proxy.auth.auth_checks import get_team_object
+ from litellm.proxy.auth.team_grants import team_model_aliases
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.management_endpoints import team_endpoints
+
+ team_id: Final = "team-kill-switch"
+ columns: Final = {"team_id": team_id, "team_alias": "kill-switch", "blocked": not blocked}
+ alias_table: Final = {"id": 1, "model_aliases": '{"fast": "gpt-4o"}', "created_by": "admin", "updated_by": "admin"}
+
+ async def update(
+ where: Mapping[str, str], data: Mapping[str, bool], include: Mapping[str, bool] | None = None
+ ) -> LiteLLM_TeamTable:
+ relations: Final = {"litellm_model_table": alias_table} if (include or {}).get("litellm_model_table") else {}
+ return LiteLLM_TeamTable.model_validate({**columns, **data, **relations})
+
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=LiteLLM_TeamTable(**columns))
+ prisma_client.db.litellm_teamtable.update = AsyncMock(side_effect=update)
+ cache: Final = UserApiKeyCache()
+ redis: Final = _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", prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", None)
+
+ warmed: Final = await get_team_object(team_id=team_id, prisma_client=prisma_client, user_api_key_cache=cache)
+ assert warmed.blocked is not blocked
+
+ response: Final = await getattr(team_endpoints, endpoint_name)(
+ data=BlockTeamRequest(team_id=team_id),
+ http_request=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"),
+ )
+ await asyncio.gather(*pubsub_module._pending_publishes) # pyright: ignore[reportPrivateUsage] # drain module-level tasks
+
+ seen_by_auth: Final = await get_team_object(team_id=team_id, prisma_client=prisma_client, user_api_key_cache=cache)
+ assert seen_by_auth.blocked is blocked
+ assert team_model_aliases(seen_by_auth) == {"fast": "gpt-4o"}
+ assert redis.broadcast_keys == [f"team_id:{team_id}", "team_alias:kill-switch"]
+ assert (response.blocked, response.litellm_model_table, response.object_permission) == (blocked, None, None)
+
+
[email protected]("endpoint_name", ["block_team", "unblock_team"])
+ ("caller", "stored_team", "status_code"),
+ [
+ (
+ UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice"),
+ LiteLLM_TeamTable(team_id="team-1234", members_with_roles=[Member(user_id="alice", role="user")]),
+ 403,
+ ),
+ (UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"), None, 404),
+ ],
+)
+async def test_team_block_unblock_refuse_before_writing(
+ endpoint_name: str,
+ caller: UserAPIKeyAuth,
+ stored_team: LiteLLM_TeamTable | None,
+ status_code: int,
+ monkeypatch: pytest.MonkeyPatch,
+):
+ from litellm.proxy._types import BlockTeamRequest
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.management_endpoints import team_endpoints
+
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=stored_team)
+ prisma_client.db.litellm_teamtable.update = AsyncMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", UserApiKeyCache())
+
+ with pytest.raises(HTTPException) as exc_info:
+ await getattr(team_endpoints, endpoint_name)(
+ data=BlockTeamRequest(team_id="team-1234"), http_request=MagicMock(), user_api_key_dict=caller
+ )
+
+ assert exc_info.value.status_code == status_code
+ prisma_client.db.litellm_teamtable.update.assert_not_awaited()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"endpoint_name",
- ["team_model_add", "team_model_delete", "update_team_member_permissions"],
+ ["team_model_add", "team_model_delete", "update_team_member_permissions", "block_team", "unblock_team"],
)
async def test_team_write_404s_when_row_vanishes_before_update(endpoint_name):
"""A team deleted between the read and the write must 404.
@@ -2662,9 +2751,12 @@ async def test_team_write_404s_when_row_vanishes_before_update(endpoint_name):
TeamModelDeleteRequest,
UserAPIKeyAuth,
)
+ from litellm.proxy._types import BlockTeamRequest
from litellm.proxy.management_endpoints.team_endpoints import (
+ block_team,
team_model_add,
team_model_delete,
+ unblock_team,
update_team_member_permissions,
)
@@ -2701,6 +2793,16 @@ async def test_team_write_404s_when_row_vanishes_before_update(endpoint_name):
http_request=mock_request,
user_api_key_dict=mock_user_api_key_dict,
),
+ "block_team": lambda: block_team(
+ data=BlockTeamRequest(team_id="team-1234"),
+ http_request=mock_request,
+ user_api_key_dict=mock_user_api_key_dict,
+ ),
+ "unblock_team": lambda: unblock_team(
+ data=BlockTeamRequest(team_id="team-1234"),
+ http_request=mock_request,
+ user_api_key_dict=mock_user_api_key_dict,
+ ),
}[endpoint_name]
with (
diff --git a/tests/unit/proxy/proxy_server/test_spend_counters.py b/tests/unit/proxy/proxy_server/test_spend_counters.py
index 01400384842..3ff4293ba93 100644
--- a/tests/unit/proxy/proxy_server/test_spend_counters.py
+++ b/tests/unit/proxy/proxy_server/test_spend_counters.py
@@ -22,6 +22,7 @@ Pins covered:
from __future__ import annotations
import asyncio
+from collections.abc import Awaitable, Callable
from datetime import datetime
from typing import Final, cast
from unittest.mock import AsyncMock, MagicMock
@@ -29,6 +30,10 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
import litellm.proxy.proxy_server as ps
+from litellm.models.team import LiteLLM_TeamTable, LiteLLM_TeamTableCachedObj
+from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import evict_local
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+from litellm.proxy.management_endpoints.team_endpoints import refresh_cached_team
from .conftest import normalize
@@ -1575,7 +1580,6 @@ async def test_update_cache_no_cached_entities_schedules_pipeline_flush(monkeypa
"u1",
f"{ps.litellm_proxy_admin_name}:spend",
"end_user_id:eu1",
- "team_id:t1",
"tag:x",
]
@@ -1600,3 +1604,70 @@ async def test_update_cache_user_cache_failure_invalid_state_is_swallowed(monkey
)
assert result is None
+
+
+async def _drain_spend_cache_writes() -> None:
+ for _ in range(3):
+ await asyncio.sleep(0)
+
+
+async def _update_team_spend(team_id: str, response_cost: float) -> None:
+ await ps.update_cache(
+ token=None,
+ user_id=None,
+ end_user_id=None,
+ team_id=team_id,
+ response_cost=response_cost,
+ parent_otel_span=None,
+ )
+
+
+async def test_update_cache_adds_spend_to_the_cached_team_only(monkeypatch: pytest.MonkeyPatch) -> None:
+ cache: Final = UserApiKeyCache()
+ cache.set_cache(key="team_id:warm", value=LiteLLM_TeamTableCachedObj(team_id="warm", spend=5.0, blocked=True))
+ monkeypatch.setattr(ps, "user_api_key_cache", cache)
+
+ await _update_team_spend(team_id="warm", response_cost=2.5)
+ await _update_team_spend(team_id="cold", response_cost=2.5)
+ await _drain_spend_cache_writes()
+
+ warm: Final = cache.get_cache(key="team_id:warm", model_type=LiteLLM_TeamTableCachedObj)
+ assert warm is not None
+ assert (warm.spend, warm.blocked) == (7.5, True)
+ assert cache.get_cache(key="team_id:cold") is None
+
+
+async def _block_on_this_worker(cache: UserApiKeyCache, team_id: str) -> None:
+ await refresh_cached_team(
+ team_row=LiteLLM_TeamTable(team_id=team_id, blocked=True),
+ user_api_key_cache=cache,
+ proxy_logging_obj=ps.proxy_logging_obj,
+ )
+
+
+async def _invalidated_by_a_peer(cache: UserApiKeyCache, team_id: str) -> None:
+ evict_local(cache_keys=(f"team_id:{team_id}",), user_api_key_cache=cache)
+
+
+ ("management_write", "expected_blocked"),
+ [(_block_on_this_worker, True), (_invalidated_by_a_peer, None)],
+)
+async def test_update_cache_never_restores_a_team_a_management_write_replaced(
+ management_write: Callable[[UserApiKeyCache, str], Awaitable[None]],
+ expected_blocked: bool | None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ team_id: Final = "kill-switch"
+ cache: Final = UserApiKeyCache()
+ cache.set_cache(key=f"team_id:{team_id}", value=LiteLLM_TeamTableCachedObj(team_id=team_id, blocked=False))
+ monkeypatch.setattr(ps, "user_api_key_cache", cache)
+
+ await _update_team_spend(team_id=team_id, response_cost=1.0)
+ await management_write(cache, team_id)
+ await _drain_spend_cache_writes()
+
+ seen_by_auth: Final = cache.get_cache(key=f"team_id:{team_id}", model_type=LiteLLM_TeamTableCachedObj)
+ assert (seen_by_auth.blocked if seen_by_auth is not None else None) == expected_blocked