Repository navigation
fix(team): apply team_member_budget updates to members still on the team default (backport of #41347 to rc/1.102.0) - #41935
Conversation
…eam default Backport of #41347 to rc/1.102.0. Cherry-picked from merge commit 4bb1ae1 (main), originally by app/devin-ai-integration. Conflicts: main's #41349 (membership rows written through upsert) is not on this line, so add_new_member keeps its create call and still writes no membership row when no budget resolves. The picked tests are adapted to that and to this line's _check_team_member_budget, which loads the membership itself.
|
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Team update leaves membership cache stale
- /team/update now evicts team_membership and team_member_default_budget cache keys after a shared member-budget change so the new cap is enforced on the next request.
Or push these changes by commenting:
@cursor push 12b46e722a
Preview (12b46e722a)
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -94,7 +94,11 @@
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.callback_utils import encrypt_callback_vars
from litellm.proxy.common_utils.json_merge_patch import apply_json_merge_patch
-from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+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_endpoints.common_daily_activity import (
get_daily_activity_aggregated,
)
@@ -431,6 +435,63 @@
)
+def _team_member_budget_id_from_metadata(metadata: object) -> str | None:
+ if not isinstance(metadata, dict):
+ return None
+ budget_id: Final = metadata.get("team_member_budget_id")
+ return budget_id if isinstance(budget_id, str) else None
+
+
+def _team_member_user_ids(members_with_roles: object) -> tuple[str, ...]:
+ if not isinstance(members_with_roles, Sequence) or isinstance(members_with_roles, (str, bytes)):
+ return ()
+ return tuple(
+ user_id
+ for member in members_with_roles
+ if isinstance(
+ user_id := (member.get("user_id") if isinstance(member, dict) else getattr(member, "user_id", None)),
+ str,
+ )
+ )
+
+
+async def _invalidate_shared_team_member_budget_cache(
+ team_id: str,
+ team_member_budget_id: str | None,
+ members_with_roles: object,
+ user_api_key_cache: UserApiKeyCache,
+) -> None:
+ """
+ Drop the cached default member budget and every membership join that
+ may still carry the pre-update cap.
+
+ Inherited members share `metadata.team_member_budget_id`. Auth and
+ reservation both prefer `team_membership.litellm_budget_table.max_budget`
+ from the cached LiteLLM_TeamMembership row, so refreshing the team
+ object alone leaves a lowered `team_member_budget` unenforced until
+ those keys expire. `/team/member_update` already evicts the per-member
+ keys; `/team/update` must evict them for the whole roster plus the
+ shared default-budget cache.
+ """
+ from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import evict_and_broadcast
+
+ member_user_ids: Final = _team_member_user_ids(members_with_roles)
+ cache_keys: Final = (
+ *((f"team_member_default_budget:{team_member_budget_id}",) if team_member_budget_id is not None else ()),
+ *(
+ key
+ for user_id in member_user_ids
+ for key in (
+ team_membership_auth_cache_key(team_id=team_id, user_id=user_id),
+ team_membership_reservation_cache_key(user_id=user_id, team_id=team_id),
+ )
+ ),
+ )
+ if not cache_keys:
+ return
+ await evict_and_broadcast(cache_keys=cache_keys, user_api_key_cache=user_api_key_cache)
+
+
async def _verify_team_access(
team_obj: LiteLLM_TeamTable,
user_api_key_dict: UserAPIKeyAuth,
@@ -2313,6 +2374,14 @@
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
+ if _team_member_fields_in_request:
+ await _invalidate_shared_team_member_budget_cache(
+ team_id=team_row.team_id,
+ team_member_budget_id=_team_member_budget_id_from_metadata(existing_team_row.metadata)
+ or _team_member_budget_id_from_metadata(team_row.metadata),
+ members_with_roles=existing_team_row.members_with_roles,
+ user_api_key_cache=user_api_key_cache,
+ )
if is_audit_logging_enabled():
await _create_team_update_audit_log(
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -2969,6 +2969,7 @@
mock_prisma_client.jsonify_team_object = MagicMock(
side_effect=lambda db_data: db_data
)
+ mock_cache.async_delete_cache = AsyncMock()
def mock_upsert_side_effect(
team_table,
@@ -14150,6 +14151,168 @@
assert real_spend_counter_cache.in_memory_cache.get_cache(key="spend:team_member:member-1:team-1") == 1.5
+@pytest.mark.asyncio
+async def test_update_team_invalidates_inherited_member_budget_cache(
+ disable_audit_logging_for_mocked_team,
+ monkeypatch,
+):
+ """Lowering team_member_budget on /team/update writes the shared default
+ row that inherited members now join. Auth and reservation both prefer the
+ cached LiteLLM_TeamMembership join, so the membership keys and the
+ team_member_default_budget entry must be evicted or the old cap stays
+ live until TTL. The live spend counter must stay: only the cap changed.
+ Asserted against real cache reads, not mock call args."""
+ from fastapi import Request
+
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ real_cache = UserApiKeyCache()
+ await real_cache.async_set_cache(key="team-1_member-1", value="stale-membership")
+ await real_cache.async_set_cache(key="team_membership:member-1:team-1", value="stale-membership")
+ await real_cache.async_set_cache(key="team_member_default_budget:budget-1", value="stale-default-budget")
+ await real_cache.async_set_cache(key="unrelated-key", value="keep-me")
+ real_spend_counter_cache = DualCache()
+ real_spend_counter_cache.in_memory_cache.set_cache(key="spend:team_member:member-1:team-1", value=999.0)
+
+ existing_team = MagicMock()
+ existing_team.team_id = "team-1"
+ existing_team.organization_id = None
+ existing_team.max_budget = None
+ existing_team.metadata = {"team_member_budget_id": "budget-1"}
+ existing_team.members_with_roles = [{"user_id": "member-1", "role": "user"}]
+ existing_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "organization_id": None,
+ "metadata": {"team_member_budget_id": "budget-1"},
+ "members_with_roles": [{"user_id": "member-1", "role": "user"}],
+ }
+
+ updated_team = MagicMock()
+ updated_team.team_id = "team-1"
+ updated_team.metadata = {"team_member_budget_id": "budget-1"}
+ updated_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "metadata": {"team_member_budget_id": "budget-1"},
+ }
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated_team)
+ mock_prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[])
+ mock_prisma_client.db.litellm_teammembership.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.update_many = AsyncMock(return_value=0)
+ mock_prisma_client.jsonify_team_object = MagicMock(side_effect=lambda db_data: db_data)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", real_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+ monkeypatch.setattr("litellm.proxy.proxy_server.spend_counter_cache", real_spend_counter_cache)
+
+ with (
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.TeamMemberBudgetHandler.upsert_team_member_budget_table",
+ AsyncMock(
+ side_effect=lambda team_table, user_api_key_dict, updated_kv, **kwargs: {
+ key: value for key, value in updated_kv.items() if key != "team_member_budget"
+ }
+ ),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.sync_team_access_group_membership",
+ AsyncMock(),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints._cache_team_object",
+ AsyncMock(),
+ ),
+ ):
+ await update_team(
+ data=UpdateTeamRequest(team_id="team-1", team_member_budget=1.0),
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
+ ),
+ )
+
+ assert await real_cache.async_get_cache(key="team-1_member-1") is None
+ assert await real_cache.async_get_cache(key="team_membership:member-1:team-1") is None
+ assert await real_cache.async_get_cache(key="team_member_default_budget:budget-1") is None
+ assert await real_cache.async_get_cache(key="unrelated-key") == "keep-me"
+ assert real_spend_counter_cache.in_memory_cache.get_cache(key="spend:team_member:member-1:team-1") == 999.0
+
+
+@pytest.mark.asyncio
+async def test_update_team_skips_membership_cache_invalidation_when_member_budget_untouched(
+ disable_audit_logging_for_mocked_team,
+ monkeypatch,
+):
+ """A team alias-only /team/update does not rewrite the shared member
+ budget, so cached membership joins and the default-budget entry must
+ stay in place."""
+ from fastapi import Request
+
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ real_cache = UserApiKeyCache()
+ await real_cache.async_set_cache(key="team-1_member-1", value="still-fresh-membership")
+ await real_cache.async_set_cache(key="team_membership:member-1:team-1", value="still-fresh-membership")
+ await real_cache.async_set_cache(key="team_member_default_budget:budget-1", value="still-fresh-default")
+
+ existing_team = MagicMock()
+ existing_team.team_id = "team-1"
+ existing_team.organization_id = None
+ existing_team.max_budget = None
+ existing_team.metadata = {"team_member_budget_id": "budget-1"}
+ existing_team.members_with_roles = [{"user_id": "member-1", "role": "user"}]
+ existing_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "organization_id": None,
+ "metadata": {"team_member_budget_id": "budget-1"},
+ "members_with_roles": [{"user_id": "member-1", "role": "user"}],
+ }
+
+ updated_team = MagicMock()
+ updated_team.team_id = "team-1"
+ updated_team.metadata = {"team_member_budget_id": "budget-1"}
+ updated_team.model_dump.return_value = {"team_id": "team-1"}
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated_team)
+ mock_prisma_client.jsonify_team_object = MagicMock(side_effect=lambda db_data: db_data)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", real_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ with (
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.sync_team_access_group_membership",
+ AsyncMock(),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints._cache_team_object",
+ AsyncMock(),
+ ),
+ ):
+ await update_team(
+ data=UpdateTeamRequest(team_id="team-1", team_alias="renamed"),
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
+ ),
+ )
+
+ assert await real_cache.async_get_cache(key="team-1_member-1") == "still-fresh-membership"
+ assert await real_cache.async_get_cache(key="team_membership:member-1:team-1") == "still-fresh-membership"
+ assert await real_cache.async_get_cache(key="team_member_default_budget:budget-1") == "still-fresh-default"
+
+
def _team_spend_by_user_team(team_id: str, team_alias: str, member: Member, permissions: list[str]) -> MagicMock:
team = MagicMock(spec=LiteLLM_TeamTable)
team.team_id = team_idYou can send follow-ups to the cloud agent here.
| default_budget: Final = await _budget_table(prisma_client, tx).find_unique( | ||
| where={"budget_id": default_team_budget_id} | ||
| ) | ||
| return default_team_budget_id if default_budget is not None else None |
There was a problem hiding this comment.
Team update leaves membership cache stale
Medium Severity
Linking inherited members to the shared default now makes enforcement read max_budget from the cached LiteLLM_TeamMembership join. /team/update updates that budget row and refreshes the team object, but it does not evict team_membership:{user_id}:{team_id} or {team_id}_{user_id}. Active inherited members can keep the old cap until the membership TTL expires, so a lowered team_member_budget may not 429 on the next request.
Reviewed by Cursor Bugbot for commit 868052b. Configure here.
There was a problem hiding this comment.
Pre-existing here: /team/update never evicted the team_member_default_budget key either, and the spend flush evicts membership. Main closes this in #40657, unlabeled for backport
|
Bugbot Autofix prepared a fix for the issue found in the latest run.
Or push these changes by commenting: Preview (12b46e722a)diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -94,7 +94,11 @@
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.callback_utils import encrypt_callback_vars
from litellm.proxy.common_utils.json_merge_patch import apply_json_merge_patch
-from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+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_endpoints.common_daily_activity import (
get_daily_activity_aggregated,
)
@@ -431,6 +435,63 @@
)
+def _team_member_budget_id_from_metadata(metadata: object) -> str | None:
+ if not isinstance(metadata, dict):
+ return None
+ budget_id: Final = metadata.get("team_member_budget_id")
+ return budget_id if isinstance(budget_id, str) else None
+
+
+def _team_member_user_ids(members_with_roles: object) -> tuple[str, ...]:
+ if not isinstance(members_with_roles, Sequence) or isinstance(members_with_roles, (str, bytes)):
+ return ()
+ return tuple(
+ user_id
+ for member in members_with_roles
+ if isinstance(
+ user_id := (member.get("user_id") if isinstance(member, dict) else getattr(member, "user_id", None)),
+ str,
+ )
+ )
+
+
+async def _invalidate_shared_team_member_budget_cache(
+ team_id: str,
+ team_member_budget_id: str | None,
+ members_with_roles: object,
+ user_api_key_cache: UserApiKeyCache,
+) -> None:
+ """
+ Drop the cached default member budget and every membership join that
+ may still carry the pre-update cap.
+
+ Inherited members share `metadata.team_member_budget_id`. Auth and
+ reservation both prefer `team_membership.litellm_budget_table.max_budget`
+ from the cached LiteLLM_TeamMembership row, so refreshing the team
+ object alone leaves a lowered `team_member_budget` unenforced until
+ those keys expire. `/team/member_update` already evicts the per-member
+ keys; `/team/update` must evict them for the whole roster plus the
+ shared default-budget cache.
+ """
+ from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import evict_and_broadcast
+
+ member_user_ids: Final = _team_member_user_ids(members_with_roles)
+ cache_keys: Final = (
+ *((f"team_member_default_budget:{team_member_budget_id}",) if team_member_budget_id is not None else ()),
+ *(
+ key
+ for user_id in member_user_ids
+ for key in (
+ team_membership_auth_cache_key(team_id=team_id, user_id=user_id),
+ team_membership_reservation_cache_key(user_id=user_id, team_id=team_id),
+ )
+ ),
+ )
+ if not cache_keys:
+ return
+ await evict_and_broadcast(cache_keys=cache_keys, user_api_key_cache=user_api_key_cache)
+
+
async def _verify_team_access(
team_obj: LiteLLM_TeamTable,
user_api_key_dict: UserAPIKeyAuth,
@@ -2313,6 +2374,14 @@
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
+ if _team_member_fields_in_request:
+ await _invalidate_shared_team_member_budget_cache(
+ team_id=team_row.team_id,
+ team_member_budget_id=_team_member_budget_id_from_metadata(existing_team_row.metadata)
+ or _team_member_budget_id_from_metadata(team_row.metadata),
+ members_with_roles=existing_team_row.members_with_roles,
+ user_api_key_cache=user_api_key_cache,
+ )
if is_audit_logging_enabled():
await _create_team_update_audit_log(
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -2969,6 +2969,7 @@
mock_prisma_client.jsonify_team_object = MagicMock(
side_effect=lambda db_data: db_data
)
+ mock_cache.async_delete_cache = AsyncMock()
def mock_upsert_side_effect(
team_table,
@@ -14150,6 +14151,168 @@
assert real_spend_counter_cache.in_memory_cache.get_cache(key="spend:team_member:member-1:team-1") == 1.5
+@pytest.mark.asyncio
+async def test_update_team_invalidates_inherited_member_budget_cache(
+ disable_audit_logging_for_mocked_team,
+ monkeypatch,
+):
+ """Lowering team_member_budget on /team/update writes the shared default
+ row that inherited members now join. Auth and reservation both prefer the
+ cached LiteLLM_TeamMembership join, so the membership keys and the
+ team_member_default_budget entry must be evicted or the old cap stays
+ live until TTL. The live spend counter must stay: only the cap changed.
+ Asserted against real cache reads, not mock call args."""
+ from fastapi import Request
+
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ real_cache = UserApiKeyCache()
+ await real_cache.async_set_cache(key="team-1_member-1", value="stale-membership")
+ await real_cache.async_set_cache(key="team_membership:member-1:team-1", value="stale-membership")
+ await real_cache.async_set_cache(key="team_member_default_budget:budget-1", value="stale-default-budget")
+ await real_cache.async_set_cache(key="unrelated-key", value="keep-me")
+ real_spend_counter_cache = DualCache()
+ real_spend_counter_cache.in_memory_cache.set_cache(key="spend:team_member:member-1:team-1", value=999.0)
+
+ existing_team = MagicMock()
+ existing_team.team_id = "team-1"
+ existing_team.organization_id = None
+ existing_team.max_budget = None
+ existing_team.metadata = {"team_member_budget_id": "budget-1"}
+ existing_team.members_with_roles = [{"user_id": "member-1", "role": "user"}]
+ existing_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "organization_id": None,
+ "metadata": {"team_member_budget_id": "budget-1"},
+ "members_with_roles": [{"user_id": "member-1", "role": "user"}],
+ }
+
+ updated_team = MagicMock()
+ updated_team.team_id = "team-1"
+ updated_team.metadata = {"team_member_budget_id": "budget-1"}
+ updated_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "metadata": {"team_member_budget_id": "budget-1"},
+ }
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated_team)
+ mock_prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[])
+ mock_prisma_client.db.litellm_teammembership.create_many = AsyncMock()
+ mock_prisma_client.db.litellm_teammembership.update_many = AsyncMock(return_value=0)
+ mock_prisma_client.jsonify_team_object = MagicMock(side_effect=lambda db_data: db_data)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", real_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+ monkeypatch.setattr("litellm.proxy.proxy_server.spend_counter_cache", real_spend_counter_cache)
+
+ with (
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.TeamMemberBudgetHandler.upsert_team_member_budget_table",
+ AsyncMock(
+ side_effect=lambda team_table, user_api_key_dict, updated_kv, **kwargs: {
+ key: value for key, value in updated_kv.items() if key != "team_member_budget"
+ }
+ ),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.sync_team_access_group_membership",
+ AsyncMock(),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints._cache_team_object",
+ AsyncMock(),
+ ),
+ ):
+ await update_team(
+ data=UpdateTeamRequest(team_id="team-1", team_member_budget=1.0),
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
+ ),
+ )
+
+ assert await real_cache.async_get_cache(key="team-1_member-1") is None
+ assert await real_cache.async_get_cache(key="team_membership:member-1:team-1") is None
+ assert await real_cache.async_get_cache(key="team_member_default_budget:budget-1") is None
+ assert await real_cache.async_get_cache(key="unrelated-key") == "keep-me"
+ assert real_spend_counter_cache.in_memory_cache.get_cache(key="spend:team_member:member-1:team-1") == 999.0
+
+
+@pytest.mark.asyncio
+async def test_update_team_skips_membership_cache_invalidation_when_member_budget_untouched(
+ disable_audit_logging_for_mocked_team,
+ monkeypatch,
+):
+ """A team alias-only /team/update does not rewrite the shared member
+ budget, so cached membership joins and the default-budget entry must
+ stay in place."""
+ from fastapi import Request
+
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ real_cache = UserApiKeyCache()
+ await real_cache.async_set_cache(key="team-1_member-1", value="still-fresh-membership")
+ await real_cache.async_set_cache(key="team_membership:member-1:team-1", value="still-fresh-membership")
+ await real_cache.async_set_cache(key="team_member_default_budget:budget-1", value="still-fresh-default")
+
+ existing_team = MagicMock()
+ existing_team.team_id = "team-1"
+ existing_team.organization_id = None
+ existing_team.max_budget = None
+ existing_team.metadata = {"team_member_budget_id": "budget-1"}
+ existing_team.members_with_roles = [{"user_id": "member-1", "role": "user"}]
+ existing_team.model_dump.return_value = {
+ "team_id": "team-1",
+ "organization_id": None,
+ "metadata": {"team_member_budget_id": "budget-1"},
+ "members_with_roles": [{"user_id": "member-1", "role": "user"}],
+ }
+
+ updated_team = MagicMock()
+ updated_team.team_id = "team-1"
+ updated_team.metadata = {"team_member_budget_id": "budget-1"}
+ updated_team.model_dump.return_value = {"team_id": "team-1"}
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing_team)
+ mock_prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=updated_team)
+ mock_prisma_client.jsonify_team_object = MagicMock(side_effect=lambda db_data: db_data)
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", real_cache)
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
+ monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+
+ with (
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints.sync_team_access_group_membership",
+ AsyncMock(),
+ ),
+ patch( # test-quality-ok: no live DB here; matches this file's established convention for endpoint-logic unit tests
+ "litellm.proxy.management_endpoints.team_endpoints._cache_team_object",
+ AsyncMock(),
+ ),
+ ):
+ await update_team(
+ data=UpdateTeamRequest(team_id="team-1", team_alias="renamed"),
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
+ ),
+ )
+
+ assert await real_cache.async_get_cache(key="team-1_member-1") == "still-fresh-membership"
+ assert await real_cache.async_get_cache(key="team_membership:member-1:team-1") == "still-fresh-membership"
+ assert await real_cache.async_get_cache(key="team_member_default_budget:budget-1") == "still-fresh-default"
+
+
def _team_spend_by_user_team(team_id: str, team_alias: str, member: Member, permissions: list[str]) -> MagicMock:
team = MagicMock(spec=LiteLLM_TeamTable)
team.team_id = team_idYou can send follow-ups to the cloud agent here. |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 868052b. Configure here.



TLDR
Problem this solves:
backport-stableafter fix: backport eight backport-stable fixes to rc/1.102.0 (#40596, #41046, #41086, #41171, #41178, #41283, #41495, #41689) #41854 landed on this linerc/1.102.0(1a993c3) still gives every new member a private copy of the team default/team/updatewithteam_member_budgetnever reaches those membersHow it solves it:
rc/1.102.0, provenance in the commit body/team/member_addlinks members to the shared team default againUser Flow
Before: an admin lowers the team's default member budget and nothing changes for the people already on the team
{"team_alias": "lit8123", "team_member_budget": 100}and get back ateam_idbudget_idandmax_budget: 100{"team_id": "...", "team_member_budget": 0.000001}and gets 200max_budget: 100After: the same update reaches every member who is still on the team default
{"team_alias": "lit8123", "team_member_budget": 100}and get back ateam_idteam-lit8123-budget-...id atmax_budget: 100{"team_id": "...", "team_member_budget": 0.000001}and gets 200max_budget: 1e-06; a member who was givenmax_budget_in_team: 50through/team/member_updatestays at 50Budget has been exceeded! TeamMember=..., and the member with their own budget still gets 200Backported PR
/team/updatebudget changes skip members on the team defaultCherry-picked from merge commit 4bb1ae1 on main with
-m 1. Two hunks conflicted, both in how this line writes the membership row, and both are resolved to this line's existing behavior with nothing new:/team/member_addto upsert the membership row and write it even when no budget resolves; this line keeps itscreatecall, so a member whose team has no default budget still gets no membership row here, exactly as on the rc tipStill open on main with the label and not in this PR: #41235.
stable/1.101.xis untouchedRelevant issues
Fixes #40783
Affected release
regression in v1.83.11 (#29119), present in v1.102.0-rc.2 and at the current tip of
rc/1.102.0Linear ticket
Resolves LIT-8123
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
test_team_update_reaches_inherited_members_but_not_overridden_onesplus its two/team/member_addlinking tests come along, adapted to this line)uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes): 5/5 after the re-reviewDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Shared setup: two proxies booted from this line, each on its own fresh Postgres database and its own port, both with
master_key: sk-lit8123and oneopenai/gpt-5.4-minideployment namedgpt-5.4-mini. Before is a detached checkout of therc/1.102.0tip 1a993c3, After is this branch.$AUTHbelow is-H "Authorization: Bearer sk-lit8123" -H "Content-Type: application/json". Every chat call is a real OpenAI request, and/team/infois read 20 seconds after the chat calls so spend has landedChat body used in every step:
{"model":"gpt-5.4-mini","messages":[{"role":"user","content":"say hi"}],"max_tokens":5}The regression-test case runs
tests/test_litellm/proxy/management_helpers/test_management_helpers_utils.pyfrom this branch in the worktree venv (Python 3.14.3); the Before run copies that file into a detached checkout of the rc tip and runs it from there, withlitellmverified to import from that checkoutBefore (1a993c3)
Lowering the team default after members joined
team-lit8123-budget-...id/key/generatewith the team id and user id), one real chat call each, then the membershipsThe picked regression tests on the rc tip
<worktree venv>/python -m pytest -q tests/test_litellm/proxy/management_helpers/test_management_helpers_utils.pyfrom the detached rc-tip checkout, with this branch's copy of the file3 failed, 19 passed, the three beingtest_add_new_member_links_default_team_budget_id,test_add_new_member_with_user_email_links_default_budget, andtest_team_update_reaches_inherited_members_but_not_overridden_onesAfter (868052b)
Lowering the team default after members joined
team-lit8123-budget-...idThe picked regression tests on this branch
.venv/bin/python -m pytest -q tests/test_litellm/proxy/management_helpers/test_management_helpers_utils.pyfrom the worktree root22 passedBASE_REF=origin/rc/1.102.0 make check: Python lint, the ruff-strict, type-discipline, test-quality, and basedpyright budget gates (all measured againstorigin/rc/1.102.0), the circular-import check, andruff format --checkall pass; the lazy OpenAPI snapshot note is under CaveatsType
🐛 Bug Fix
Caveats (if any)
Medium
/team/member_updateper member or the bulk member budget UI, or re-add thembudget_durationstill gets a private clone, so later team-level changes do not reach themLow
budget_idsince fix(proxy): track team member spend when the member has no budget #41349, which is not labeled for backport and is not picked heretest_add_new_member_no_budget_when_default_budget_row_is_missingasserts that no-row behavior here, where main's copy asserts the row without abudget_idmake checkran under Python 3.14 flagged the lazy OpenAPI snapshot as stale on the untouched rc tip too; the only diff is Python 3.13+ docstring dedent in one route description, so the regenerated file was discardedbackport-stableand is open on main; it is not in this PR and needs its own pick once mergedlocal_testing_part1,local_testing_part2, andllm_translation_testingare expected red on Together AI tests hard-coded toopenai/gpt-oss-20b, the same failures fix: backport eight backport-stable fixes to rc/1.102.0 (#40596, #41046, #41086, #41171, #41178, #41283, #41495, #41689) #41854 and fix(license): backport the wildcard license auto_router grant to rc/1.102.0 (#41684) #41701 had on this line; main rewrote those tests after the rc cut (1aa2e19 and follow-ups, test-only)/team/updateon this line does not evict the cached membership row, so a lowered default cap can lag for a member until their next spend flush (which evictsteam_membership:{user_id}:{team_id}) or the cache TTL. That window is pre-existing here: theteam_member_default_budget:{id}key the inherited path read before this pick was never evicted by/team/updateeither. Main closes it with_evict_created_membership_cachesfrom fix(auth): refresh lite login session token grants from the live user and team rows #40657, which is not labeled for backport and is not picked hereFinal Attestation