Repository navigation
fix(proxy): track team member spend when the member has no budget #41349
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
de4b520
d9b48ac
6dce85c
7c068a4
efef6ab
60077e9
499c334
2d61fa6
b6f4ad1
61d4c5b
c21e86a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,7 +18,7 @@ | |
| from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, cast, overload | ||
| from urllib.parse import quote, unquote | ||
|
|
||
| from typing_extensions import ReadOnly, TypedDict | ||
| from typing_extensions import LiteralString, ReadOnly, TypedDict | ||
|
|
||
| import litellm | ||
| from litellm._logging import verbose_proxy_logger | ||
|
|
@@ -136,6 +136,8 @@ async def __aexit__(self, exc_type: object, exc_value: object, traceback: object | |
| class _SpendTransaction(Protocol): | ||
| def batch_(self) -> _SpendBatchManager: ... | ||
|
|
||
| async def execute_raw(self, query: LiteralString, *args: object) -> int: ... | ||
|
|
||
|
|
||
| class _SpendTransactionManager(Protocol): | ||
| async def __aenter__(self) -> _SpendTransaction: ... | ||
|
|
@@ -161,6 +163,44 @@ def _spend_update_tx(prisma_client: PrismaClient) -> _SpendTransactionManager: | |
| return tx | ||
|
|
||
|
|
||
| # The per-team advisory lock the team endpoints hold while changing a roster (TEAM_ADVISORY_LOCK_SQL), | ||
| # so the roster check below cannot interleave with their writes. A row lock would deadlock with the | ||
| # access-group endpoints, which lock a team row after an access-group lock. | ||
| _TEAM_ADVISORY_LOCK_SQL: Final = "SELECT pg_advisory_xact_lock(hashtext($1)) IS NULL AS locked" | ||
|
|
||
| # One statement adds every member's cost to their membership row. A missing row is created only | ||
| # while the user is still on the team's roster, so a spend flush landing after a removal never | ||
| # recreates the member. | ||
| _TEAM_MEMBER_SPEND_SQL: Final = """ | ||
| INSERT INTO "LiteLLM_TeamMembership" (user_id, team_id, spend, total_spend) | ||
| SELECT p.user_id, p.team_id, p.cost, p.cost | ||
| FROM unnest($1::text[], $2::text[], $3::float8[]) AS p(user_id, team_id, cost) | ||
| WHERE EXISTS ( | ||
| SELECT 1 FROM "LiteLLM_TeamTable" t | ||
| WHERE t.team_id = p.team_id | ||
| AND t.members_with_roles @> jsonb_build_array(jsonb_build_object('user_id', p.user_id)) | ||
| ) | ||
| OR EXISTS (SELECT 1 FROM "LiteLLM_TeamMembership" m WHERE m.user_id = p.user_id AND m.team_id = p.team_id) | ||
| ON CONFLICT (user_id, team_id) DO UPDATE | ||
| SET spend = "LiteLLM_TeamMembership".spend + EXCLUDED.spend, | ||
| total_spend = "LiteLLM_TeamMembership".total_spend + EXCLUDED.total_spend | ||
| """ | ||
|
|
||
|
|
||
| async def _write_team_member_spend(transaction: _SpendTransaction, spend_by_member_key: Mapping[str, float]) -> None: | ||
| # key is "team_id::<value>::user_id::<value>"; locks are taken in sorted team_id order like the team endpoints | ||
| rows: Final = sorted((key.split("::")[1], key.split("::")[3], cost) for key, cost in spend_by_member_key.items()) | ||
| team_ids: Final = tuple(team_id for team_id, _user_id, _cost in rows) | ||
| for team_id in dict.fromkeys(team_ids): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorting the composite keys orders team ids like
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch. Rows are now sorted by (team_id, user_id) and locks follow sorted distinct team ids, matching /team/delete. Regression test pins eng before eng2 |
||
| _ = await transaction.execute_raw(_TEAM_ADVISORY_LOCK_SQL, team_id) | ||
| _ = await transaction.execute_raw( | ||
| _TEAM_MEMBER_SPEND_SQL, | ||
| tuple(user_id for _team_id, user_id, _cost in rows), | ||
| team_ids, | ||
| tuple(cost for _team_id, _user_id, cost in rows), | ||
| ) | ||
|
|
||
|
|
||
| def get_llm_router(): | ||
| """The proxy's router, or None outside a running proxy. | ||
|
|
||
|
|
@@ -1685,21 +1725,7 @@ async def _commit_spend_updates_to_db( | |
| start_time = time.time() | ||
| try: | ||
| async with _spend_update_tx(prisma_client) as transaction: | ||
| async with transaction.batch_() as batcher: | ||
| # Sort by composite key for consistent lock ordering across pods to prevent deadlocks. | ||
| # Key format "team_id::<v>::user_id::<v>" makes the string sort equivalent to sorting by (team_id, user_id). | ||
| for key, response_cost in sorted(team_member_list_transactions.items()): | ||
| # key is "team_id::<value>::user_id::<value>" | ||
| team_id = key.split("::")[1] | ||
| user_id = key.split("::")[3] | ||
|
|
||
| batcher.litellm_teammembership.update_many( # 'update_many' prevents error from being raised if no row exists | ||
| where={"team_id": team_id, "user_id": user_id}, | ||
| data={ | ||
| "spend": {"increment": response_cost}, | ||
| "total_spend": {"increment": response_cost}, | ||
| }, | ||
| ) | ||
| await _write_team_member_spend(transaction, team_member_list_transactions) | ||
| # Transaction succeeded, break out of retry loop | ||
| break | ||
| except Exception as e: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2904,10 +2904,15 @@ async def _process_team_members( | |
| if member_allowed_models is None and team_default_member_models: | ||
| member_allowed_models = team_default_member_models | ||
|
|
||
| if isinstance(data.member, Member): | ||
| requested_members: Final[Sequence[Member]] = ( | ||
| (data.member,) if isinstance(data.member, Member) else tuple(data.member) | ||
| ) | ||
| for m in requested_members: | ||
| if _member_already_in_team(m, complete_team_data): | ||
| continue | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Skip misses create orphan member budgetsMedium Severity The already-on-team skip only consults the roster from before this request, so a bulk Additional Locations (1)Reviewed by Cursor Bugbot for commit dc49001. Configure here. |
||
| try: | ||
| updated_user, updated_tm = await add_new_member( | ||
| new_member=data.member, | ||
| new_member=m, | ||
| max_budget_in_team=data.max_budget_in_team, | ||
| prisma_client=prisma_client, | ||
| user_api_key_dict=user_api_key_dict, | ||
|
|
@@ -2921,34 +2926,11 @@ async def _process_team_members( | |
| except Exception as e: | ||
| raise HTTPException( | ||
| status_code=500, | ||
| detail={"error": f"Unable to add user - {data.member}, to team - {data.team_id}, for reason - {e}"}, | ||
| detail={"error": f"Unable to add user - {m}, to team - {data.team_id}, for reason - {e}"}, | ||
| ) | ||
| updated_users.append(updated_user) | ||
| if updated_tm is not None: | ||
| updated_team_memberships.append(updated_tm) | ||
| elif isinstance(data.member, list): | ||
| for m in data.member: | ||
| try: | ||
| updated_user, updated_tm = await add_new_member( | ||
| new_member=m, | ||
| max_budget_in_team=data.max_budget_in_team, | ||
| prisma_client=prisma_client, | ||
| user_api_key_dict=user_api_key_dict, | ||
| litellm_proxy_admin_name=litellm_proxy_admin_name, | ||
| team_id=data.team_id, | ||
| default_team_budget_id=default_team_budget_id, | ||
| allowed_models=member_allowed_models, | ||
| budget_duration=data.budget_duration, | ||
| tx=tx, | ||
| ) | ||
| except Exception as e: | ||
| raise HTTPException( | ||
| status_code=500, | ||
| detail={"error": f"Unable to add user - {m}, to team - {data.team_id}, for reason - {e}"}, | ||
| ) | ||
| updated_users.append(updated_user) | ||
| if updated_tm is not None: | ||
| updated_team_memberships.append(updated_tm) | ||
|
|
||
| return updated_users, updated_team_memberships | ||
|
|
||
|
|
||


Uh oh!
There was an error while loading. Please reload this page.