Skip to content
Closed
26 changes: 25 additions & 1 deletion litellm/proxy/management_endpoints/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,31 @@ async def _upsert_budget_and_membership(
and existing_budget_id == team_default_budget_id
)

# If multiple memberships still point at this budget row, treat it as
# shared and clone-on-write — otherwise mutating the row here would
# silently move every other member's cap with it (LIT-3359).
shared_with_other_memberships = False
if existing_budget_id is not None and not is_shared_default:
try:
membership_refs = await tx.litellm_teammembership.count(
where={"budget_id": existing_budget_id}
)
shared_with_other_memberships = (membership_refs or 0) > 1
except Exception as e:
# Refusing to mutate on count failures is safer than risking a
# cross-member overwrite; fall through to the clone-on-write path.
verbose_proxy_logger.debug(
f"_upsert_budget_and_membership: ref-count probe failed for "
f"budget_id={existing_budget_id} (team_id={team_id}, "
f"user_id={user_id}): {e}. Defaulting to clone-on-write."
)
shared_with_other_memberships = True

Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if (
existing_budget_id is not None
and not is_shared_default
and not shared_with_other_memberships
):
# Update the existing budget in-place to preserve fields not being changed.
# Only write fields that the caller explicitly provided (non-None).
update_data: Dict[str, Any] = {
Expand Down Expand Up @@ -483,7 +507,7 @@ async def _upsert_budget_and_membership(

# If we're forking off the shared default, seed the new row with the
# default's values so fields the caller did not change carry over.
if is_shared_default:
if is_shared_default or shared_with_other_memberships:
default_budget_row = await tx.litellm_budgettable.find_unique(
where={"budget_id": existing_budget_id}
)
Expand Down
196 changes: 196 additions & 0 deletions tests/litellm/proxy/management_endpoints/test_common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,199 @@ def test_non_empty_team_member_key_duration_triggers_premium_check(
}
_update_metadata_fields(updated_kv)
mock_check.assert_called()


# ---------------------------------------------------------------------------
# Tests for _upsert_budget_and_membership clone-on-write (LIT-3359)
# ---------------------------------------------------------------------------

from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.management_endpoints.common_utils import (
_upsert_budget_and_membership,
)


def _make_tx(*, ref_count: int, default_budget_fields=None):
"""Build a minimal mock prisma transaction with the methods the
function uses: count, update, find_unique, create, upsert."""

default_budget_fields = default_budget_fields or {
"budget_id": "shared-bdg-1",
"max_budget": 100.0,
"soft_budget": None,
"max_parallel_requests": None,
"tpm_limit": None,
"rpm_limit": None,
"model_max_budget": None,
"budget_duration": None,
"allowed_models": None,
}

tx = SimpleNamespace()
tx.litellm_teammembership = SimpleNamespace(
count=AsyncMock(return_value=ref_count),
update=AsyncMock(),
upsert=AsyncMock(),
)
fake_budget_row = MagicMock()
fake_budget_row.model_dump = MagicMock(return_value=default_budget_fields)
created = SimpleNamespace(budget_id="new-bdg-uuid")
tx.litellm_budgettable = SimpleNamespace(
update=AsyncMock(),
find_unique=AsyncMock(return_value=fake_budget_row),
create=AsyncMock(return_value=created),
)
return tx


@pytest.mark.asyncio
class TestUpsertBudgetMembershipSharedRow:
"""LIT-3359: when multiple memberships still point at the same budget_id,
`_upsert_budget_and_membership` MUST clone-on-write — never mutate the
shared row in place."""

async def test_shared_row_triggers_clone_on_write(self):
"""Two memberships share budget_id -> create new budget, repoint."""
tx = _make_tx(ref_count=2)
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=42.0,
existing_budget_id="shared-bdg-1",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id=None,
)
# Must NOT have mutated the shared row in place
tx.litellm_budgettable.update.assert_not_called()
# Must have created a NEW private budget for Alice
tx.litellm_budgettable.create.assert_called_once()
create_data = tx.litellm_budgettable.create.call_args.kwargs["data"]
assert create_data["max_budget"] == 42.0
# Must have re-linked Alice's membership to the new budget
tx.litellm_teammembership.upsert.assert_called_once()
upsert_kwargs = tx.litellm_teammembership.upsert.call_args.kwargs
assert upsert_kwargs["where"]["user_id_team_id"]["user_id"] == "alice"
assert (
upsert_kwargs["data"]["update"]["litellm_budget_table"]["connect"][
"budget_id"
]
== "new-bdg-uuid"
)

async def test_solo_membership_still_updates_in_place(self):
"""Single membership owning its budget_id keeps the cheaper in-place
update path (no regression in normal behaviour)."""
tx = _make_tx(ref_count=1)
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=42.0,
existing_budget_id="solo-bdg",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id=None,
)
tx.litellm_budgettable.update.assert_called_once()
update_args = tx.litellm_budgettable.update.call_args.kwargs
assert update_args["where"]["budget_id"] == "solo-bdg"
assert update_args["data"]["max_budget"] == 42.0
tx.litellm_budgettable.create.assert_not_called()
tx.litellm_teammembership.upsert.assert_not_called()

async def test_clone_seeds_unchanged_fields_from_shared_row(self):
"""When forking off a shared row, fields the caller did NOT change
(e.g. tpm_limit, allowed_models) must carry over from the shared row
into the new private budget."""
shared = {
"budget_id": "shared-bdg-2",
"max_budget": 100.0,
"soft_budget": 80.0,
"max_parallel_requests": 5,
"tpm_limit": 1000,
"rpm_limit": 60,
"model_max_budget": {"gpt-4o": 50.0},
"budget_duration": "30d",
"allowed_models": ["gpt-4o", "claude-3-haiku"],
}
tx = _make_tx(ref_count=3, default_budget_fields=shared)
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=42.0, # only changing this
existing_budget_id="shared-bdg-2",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id=None,
)
tx.litellm_budgettable.update.assert_not_called()
create_data = tx.litellm_budgettable.create.call_args.kwargs["data"]
# Caller override wins:
assert create_data["max_budget"] == 42.0
# Carry-over from shared row:
assert create_data["soft_budget"] == 80.0
assert create_data["max_parallel_requests"] == 5
assert create_data["tpm_limit"] == 1000
assert create_data["rpm_limit"] == 60
assert create_data["budget_duration"] == "30d"
assert create_data["allowed_models"] == ["gpt-4o", "claude-3-haiku"]
assert create_data["model_max_budget"] == {"gpt-4o": 50.0}

async def test_team_default_match_still_clones(self):
"""Pre-existing behaviour: membership pointing at team_default_budget_id
clones-on-write regardless of ref-count."""
tx = _make_tx(ref_count=1) # only one ref, but it's the team default
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=42.0,
existing_budget_id="team-default-bdg",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id="team-default-bdg",
)
tx.litellm_budgettable.update.assert_not_called()
tx.litellm_budgettable.create.assert_called_once()
tx.litellm_teammembership.upsert.assert_called_once()
# And we did NOT bother running the ref-count probe in this path
tx.litellm_teammembership.count.assert_not_called()

async def test_count_probe_failure_defaults_to_clone_on_write(self):
"""If the ref-count probe raises, the function must take the safer
clone-on-write branch (never silently fall through to in-place update
of a possibly-shared row)."""
tx = _make_tx(ref_count=1)
tx.litellm_teammembership.count = AsyncMock(
side_effect=RuntimeError("simulated DB failure")
)
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=42.0,
existing_budget_id="some-bdg",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id=None,
)
tx.litellm_budgettable.update.assert_not_called()
tx.litellm_budgettable.create.assert_called_once()

async def test_all_limits_none_still_disconnects(self):
"""When every limit is None the function must disconnect the
budget (and not run the ref-count probe at all)."""
tx = _make_tx(ref_count=2)
await _upsert_budget_and_membership(
tx,
team_id="t1",
user_id="alice",
max_budget=None,
existing_budget_id="shared-bdg-1",
user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
team_default_budget_id=None,
)
tx.litellm_teammembership.update.assert_called_once()
tx.litellm_teammembership.upsert.assert_not_called()
tx.litellm_teammembership.count.assert_not_called()
Loading