Repository navigation
feat(proxy): split Azure PTU deployments across teams with per-team PTU ceilings and PTU-hour reporting - #43043
Conversation
A PTU deployment's model_info takes ptu_shares (team_id -> whole PTUs adding up to ptu_count) in place of a single team_id. With LITELLM_ENABLE_PTU_COST_ATTRIBUTION on, routing hides the deployment from teams holding no share, the v3 limiter enforces each share as a per-team TPM ceiling from Azure's per-model TPM-per-PTU sizing, the daily flat-cost rollup splits the hourly cost by share, and /team/daily/activity plus the Team Usage page report PTU-hours next to tokens.
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
…r_team # Conflicts: # tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…deployments by public name The PTU flag is read from the process environment on every check instead of through the secret-manager path, so a proxy with a hosted secret manager does not pay a round trip per request. A team's ceiling now carries the model's cached-input ratio and settlement charges cache reads at that ratio, matching how Azure sizes a PTU. A deployment registered for one team is found by its team_public_model_name for PTU-hours and the ceiling, since its model_name is rewritten to a unique internal name. ptu_shares are StrictInt on ModelInfo and parsed_ptu_shares refuses booleans, strings, and non-string team ids, a fractional ptu_count reserves nothing, and models_processed counts distinct deployments rather than holdings.
…ting flag-independent, and warn only shared or Azure reservations
|
bugbot run |
Comments Outside DiffThese findings could not be posted inline.
|
…aw output tokens and escape the exported team id
|
bugbot run |
1 similar comment
|
@litereview code-review |
|
bugbot run |
Adds ptu_hours and total_ptu_hours to the daily activity integration goldens and fixtures, since every route now reports them
|
@litereview code-review |
|
bugbot run |
…st attribution and config regex timing
|
@litereview code-review |
|
bugbot run |
Dismissing my own earlier approval so a second reviewer signs off on this PR before it merges
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Judge: skipped, the rules alone decided. Pushes do not re-run this check. Comment |
…r_team # Conflicts: # litellm/proxy/management_endpoints/scim/scim_v2.py
|
Automatic reviews are disabled for this repository. |
|
bugbot run |
|
Merged main at cdce71e, keeping both sides of one import conflict. The PR diff against main is unchanged, so QA and audit carry over |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit cdce71e. Configure here.
| request_kwargs: Mapping[str, object], share_teams: frozenset[str] | ||
| ) -> Mapping[str, object] | None: | ||
| """``request_kwargs`` when the caller's team is in ``share_teams``, else None.""" | ||
| return request_kwargs if get_request_team_id(request_kwargs) in share_teams else None |
There was a problem hiding this comment.
Share-holder retries ignore model scope
Medium Severity
share_holder_request_kwargs treats a team as a share holder if it holds a PTU share on any deployment, then retries, the priority queue, and /v1/messages stream retries pass that team's request_kwargs for every model. A team that both holds a share and owns a team_id deployment therefore gets team-aware retries on the owned deployment, which can issue extra upstream calls on failure instead of main's single attempt.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit cdce71e. Configure here.
There was a problem hiding this comment.
Agreed, but narrow. On main a team-owned deployment gets no retries at all, and a tracked follow-up gives every owning team retries, ending this gap
| return None | ||
| allocated: Final = sum(shares.values()) | ||
| if allocated != ptu_count: | ||
| return _named(f"ptu_shares must add up to ptu_count ({allocated} of {ptu_count} allocated)", model_name) |
There was a problem hiding this comment.
Invalid ptu_count skips share-sum check
Medium Severity
_ptu_holder_error returns success when ptu_count is present but not a positive whole number in range, so the ptu_shares sum is never compared. ptu_config_error has no other bounds check, so POST /model/new can accept ptu_count: 0 (or another out-of-range value) with shares that do not add up. The share filter and per-team ceiling still apply from the map, while ptu_terms fails and flat cost is not rolled up.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit cdce71e. Configure here.
There was a problem hiding this comment.
ModelInfo's validator rejects a ptu_count outside 1 to 1,000,000 on /model/new, PATCH and config load, so this check never sees one
…43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…les, and fix SCIM and MCP integration tests on CircleCI (#47037) * fix(test-harness): preserve sibling auth modules in isolated worker configs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect servers in MCP connect-flow descriptions Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect ptu_hours in daily activity metrics after #43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): kill every serving worker once the SCIM push blocks on the row lock * fix(cost): price exact cost-map names before price-free capability rule matches * test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): price an explicit base_model under its own provider after candidate reordering Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): retain priced generalized candidates and skip explicit-pricing lookups Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(cost): assert custom pricing makes no remote model-info requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(cost): keep the per-candidate pricing provider final Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments * fix(cost): sort cost candidates from the static cost map and rules, without provider lookups * test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yuneng Jiang <yuneng@berri.ai>
…in (#47090) * fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings (#46936) * fix(bedrock): block realtime replay after input starts the session and reject non-string instructions and voice * test(bedrock): name the malformed realtime setting test for its string cases * fix(bedrock): replay the opening realtime message until Bedrock accepts the stream and refuse any fallback after commit Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params. * fix(bedrock): replay a refused opening message on any fallback and reject OpenAI voices and non-string audio formats * fix(realtime): read the client scope only when the websocket has one and reject any-case OpenAI and empty Bedrock voices * test(bedrock): cover realtime replay, refusal and committed failure through a real proxy Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again (cherry picked from commit 3ef0b35) * test(integration): write worker configs beside test-supplied configs (#47066) Under worker isolation the harness rewrote every proxy config into the owned proxy's directory, so modules a test placed next to its own config (custom_auth) no longer resolved and the proxy died at boot. The copy now lands next to a test-supplied config, while configs inside the checkout still go to the worker directory so nothing is written into the repo tree (cherry picked from commit e754857) * test(e2e): keep the prompt-caching affinity test on the live provider (#47072) With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the shared response cache. Each call's recording expires on its own, so a run could replay the cache-writing call while a follow-up went live against a cold provider cache, recording creation instead of a read. That recording then replayed as a failure for 24 hours. Mark the test provider_live, as PROVIDER_CACHE.md requires for prompt-caching tests (cherry picked from commit 6b45a19) * test(integration): send post-kill requests on a fresh connection in two worker-kill tests (#47080) kill() returns once the killed worker's main thread is a zombie, but its other threads can still be exiting and holding its sockets open. A keep-alive connection pooled to that worker still looks healthy, so the next request goes out on it and the closing socket answers with a reset. The old reap wait used to hide this. A new connection can only be accepted by a live worker, so the surviving-worker assertions now run on a fresh client (cherry picked from commit c32eea6) * fix(caching): keep prompt cache usage on streamed cache hits (#47073) * fix(caching): keep prompt cache usage on streamed cache hits A stream=true request served from the response cache rebuilt its usage from the prompt, completion and total counts only, so prompt_tokens_details and the cache read and creation counts were dropped on the replayed stream. /v1/messages clients routed to Bedrock Converse saw input_tokens equal to the whole prompt and no cache tokens on a hit. Both replays now build the usage through one helper that also restores prompt_tokens_details and the integer cache read and creation counts, skipping cached values that do not validate. * fix(caching): coerce replayed token counts the way the live usage does The replay accepted only exact ints for the token counts, so an integral float or numeric string in a cached entry became 0 where the previous replay kept it. Counts now go through pydantic int coercion and fall back only when they do not validate. (cherry picked from commit d346d76) * fix(logging): keep the async request's logging payload when the sync success thread runs late (#47019) * fix(logging): keep the async request's logging payload when sync callbacks run late Treat the "cache" success callback as internal when deciding whether to start the sync success thread for async requests. It has no branch in the sync handler, so with `cache: true` that thread did nothing except rebuild and overwrite model_call_details["standard_logging_object"]. When the sync handler does run for an async request (a real sync-only logger is configured), it now builds its own payload and hands it only to its own callbacks. The async handler keeps sole ownership of the shared payload, so edits made by async logging hooks (for example the v3 rate limiter's mirrored x-ratelimit headers that Prometheus reads) are no longer discarded. Sync requests keep their existing behavior. * fix(logging): keep sync cache hits logged and isolate the async-request payload build The sync completion cache-hit path reused handle_sync_success_callbacks_for_async_calls, so treating "cache" as internal silently dropped sync callbacks on sync cache hits. It now submits the sync handler through its own method, as it effectively always did. For async requests the sync handler builds its payload from a copy of the call details, so message redaction cannot rewrite the shared standard_logging_object, and when it builds no payload its callbacks keep the shared one instead of getting None. * test(caching): lock sync cache-hit logging for completion, embedding and text_completion * test(logging): keep sync hook edits off a caller-supplied payload for async requests * fix(logging): give sync hooks a copy of the async payload when the thread builds none * test(logging): check every legacy sync logger gets the thread's own payload * test(logging): cover traceloop and supabase sync logging for async requests (cherry picked from commit a4e0570) * fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI (#47037) * fix(test-harness): preserve sibling auth modules in isolated worker configs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect servers in MCP connect-flow descriptions Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect ptu_hours in daily activity metrics after #43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): kill every serving worker once the SCIM push blocks on the row lock * fix(cost): price exact cost-map names before price-free capability rule matches * test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): price an explicit base_model under its own provider after candidate reordering Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): retain priced generalized candidates and skip explicit-pricing lookups Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(cost): assert custom pricing makes no remote model-info requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(cost): keep the per-candidate pricing provider final Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments * fix(cost): sort cost candidates from the static cost map and rules, without provider lookups * test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yuneng Jiang <yuneng@berri.ai> (cherry picked from commit 4a58784) * test(e2e): warm the memory test up with two batches before the measured one (#47087) * test(e2e): warm the memory test up with two batches before the measured one On a cold worker the second batch of failing requests can still raise the allocator's high-water mark by about 50 MB while the live Python heap stays flat, so the 48 MB budget failed about 1 in 10 Buildkite runs without a leak. The test now runs two warmup batches, measures the third against the same budget, and records every batch's settled growth per worker as an rss_batch_growth JUnit property for later calibration * test(e2e): record each memory batch's growth as soon as it settles A failure in a later batch no longer drops the growth already measured, and the worker keys are no longer sorted, which raised on a mix of named and unnamed hosts * test(e2e): silence the xunit2 record_property warning on the memory test (cherry picked from commit 1fd7f81) * test: import pytest and Final for the backported #47073 test on rc On main these imports came from an earlier commit that is not on rc/1.107.0, so the picked test failed collection with NameError --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>


TLDR
Problem this solves:
How it solves it:
model_info.ptu_sharessplitsptu_countacross teams in whole PTUsDocs for the new fields, the ceiling, and the cost split are in BerriAI/litellm-docs#1700 (
docs/proxy/ptu_flat_cost.mdanddocs/proxy/dynamic_rate_limit.md), to merge after this PRUser Flow
Before: a proxy admin cannot split one PTU deployment across teams, and no team sees its PTU use
ptu_sharesand noteam_idgets 400team_id is required when PTU fields are setteam_id, team B's key gets 400Invalid model nameon POST https://litellm-domain/v1/chat/completionsmodel_tpm_limiton POST https://litellm-domain/team/updateflat_coston team A with no PTU figure, and https://litellm-domain/ui/usage shows tokens onlyAfter: the admin declares the split once, and the proxy enforces it and bills each team
reserved for the teams holding a PTU shareretry-after, and team B keeps its 20 PTUflat_cost720 and 480 and addsptu_hours, and https://litellm-domain/ui/usage adds a PTU Hours tileFull steps with request bodies and error text
Before: a proxy admin cannot split one PTU deployment across two departments, and neither department ever sees PTU consumption
model_info: {"ptu_count": 50, "cost_per_ptu_per_hour": 1.0, "ptu_effective_from": "2026-09-23T00:00:00Z", "ptu_shares": {"<team-a>": 30, "<team-b>": 20}}and gets 400team_id is required when PTU fields are set (one model maps to one team)"team_id": "<team-a>"instead, and team B's key then gets 400Invalid model name passed in model=gpt-4.1-ptuon POST https://litellm-domain/v1/chat/completionsmetadata.model_tpm_limitthrough POST https://litellm-domain/team/update to a TPM number they worked out by hand, and nothing keeps that number in step with the reservationflat_costunder team A, nothing under team B, and no PTU figure anywhere; the Team Usage view at https://litellm-domain/ui/usage shows tokens onlyAfter: the admin declares the split in PTUs once, the proxy enforces it per team, and cost and PTU-hours land on each team
ptu_sharesand noteam_idand gets 200; shares that do not add up toptu_count, or ateam_idnext toptu_shares, get a 400 saying sogpt-4.1-ptu, while a key from a team holding no share gets 400Deployment gpt-4.1-ptu is reserved for the teams holding a PTU share of itRate limit exceeded for model_per_team_ptu: <team-a>:gpt-4.1-ptuwith aretry-after, a single request bigger than the whole 30 PTU gets 400This request needs ... so it can never be admitted. Lower max_tokens or shorten the prompt., and team B keeps its own 20 PTUflat_costsplit 720 under team A and 480 under team B (30 and 20 of the $1,200 day) plusptu_hoursper model group next to the tokens, for one team when the GET names only that team, and the Team Usage page shows a PTU Hours tileDesign decisions
22 design decisions, each with the alternative it rejected
ptu_sharesandteam_idare mutually exclusive and the shares must add up toptu_countexactly. The alternative, letting a partial split leave the rest unowned, would silently drop cost, so the deployment either belongs to one team the old way or is fully split. For the same reasonptu_shareswithoutptu_countandcost_per_ptu_per_houris refused too: a split with no count has nothing to add up to, and the deployment would route and cap by share while its flat cost never rolled upptu_sharesdeployments. A single-teamteam_iddeployment gets no new 429s, since the team already owns all of it, but its usage does report PTU-hourslitellm/llms/azure/ptu_capacity.py) with the source URL and the date it was read. A deployment declaring shares, or an Azure deployment reserved for one team, whose model has no row logs a warning at registration and fails open (no ceiling, zero PTU-hours); a single-team reservation on another provider only ever fed the flat-cost rollup, which needs no sizing, so it is not warned about.model_info.base_modelis the preferred lookup key because an Azure deployment name is arbitrarymax_tokensgets the proxy's usual output floor, but measured against the share expressed in raw output tokens (the ceiling divided by the model's output ratio), so the floor and the implicitmax_tokenscap the proxy writes stay in raw tokens and an uncapped request never reserves more than a quarter of the share: one PTU of gpt-4.1 admits four uncapped requests a minute instead of refusing the first. Main writes that cap, min(1,024, a quarter of the limit), whenever any configured TPM limit is under 4,096, and the share follows the same rule, so a small share does cut long uncapped replies withfinish_reason: length: 3 PTU of gpt-5.4-mini caps them at 987 output tokens and 1 PTU of gpt-5.4 at 100. A client that sends its ownmax_tokensis never rewritten. Leaving uncapped requests unbounded was the alternative, and it would let one of them reserve nothing and then overrun the shareGET /team/daily/activityfrom the tokens already stored, so no schema change and no new rollup. Per-key, per-user and per-tag rows, and each team's row underbreakdown.entities, keepptu_hoursat zero because those rows carry no model group today, so one team's PTU-hours are read from a GET naming only that team. A row is sized only by a reservation whoseptu_effective_fromtoptu_effective_towindow covers the row's day, so tokens from before a reservation starts or after it ends read no PTU-hoursptu_sharesis declared, flag or no flag, because a declared split is an access rule and a proxy that ignored it would hand one department's reservation to another. The ceiling, the cost split, PTU-hours, and the registration validation stay gated onLITELLM_ENABLE_PTU_COST_ATTRIBUTION, like the existing flat-cost attribution, so a proxy with neither the flag nor shares behaves exactly as before, with one carve-out: a config.yaml entry that declaresptu_shareshas its PTU fields validated with the flag off too, since the split it declares is enforced either way and a malformed one is better dropped at load, with the startup log naming the model and the reason, than honoured or ignored without a word (the model endpoints already refuse every PTU field with the flag off). The drop follows how the proxy has handled a malformed PTU entry with the flag on since before this PR: the router raises, the proxy'signore_invalid_deploymentslogs the error and starts without that deployment, and a request to its group gets a 400 with no healthy deployments, so this release adds no startup refusalmodel_per_team_ptu:<team_id>:<model group>) on the same window as the team'smodel_tpm_limit, so a 429 from it reads and resets the same way as the limits admins already know. A rolling hour was considered and rejected because Azure sizes a PTU per minuteLITELLM_ENABLE_PTU_COST_ATTRIBUTIONis read from a configured secret manager first wheneverget_secretwould ask one for it, and from the process environment otherwise, the same orderget_secretuses for every other setting. The router and the limiter check it on every request, so a secret-manager read is cached for a minute, and the limiter asks only once the calling team is found to hold a share in the group, so traffic with no share never waits on the secret manager. Reading the environment first was the alternative, and it would let a stale environment value override the secret manager an admin uses for every other settingptu_countand every share are whole PTUs, which is how Azure sells them:100.0is accepted as 100, and100.5is refused at registration fromPOST /model/newand config.yaml alikemodel_nameand keeps the public one inmodel_info.team_public_model_name, so the sizing lookup for PTU-hours and the ceiling matches on either name; usage rows carry the public nameptu_sharesis checked against the team table onPOST /model/newandPATCH /model/{model_id}/update, the same checkteam_idalready gets there, so a mistyped id is a 400 naming it instead of a share no key can ever use. config.yaml registration stays unchecked, since the router loads before the database, exactly as it does forteam_idteam_idis not switched toptu_sharesby a PATCH: the row is team-scoped (internal routing name, entry in the team's model list) and a shared row is proxy-wide, so the switch is a delete and aPOST /model/newwith the samemodel_info.id, which keeps the id the flat-cost rows are keyed on, and the docs say so. The alternative, letting an explicitteam_id: nullclear it in place, would need the PATCH path to repeat the delete path's team cleanup on a field the update endpoint deliberately keeps team admins from clearingmodel_info.idor provider model (litellm_params.model), or through a routing group ormodel_group_alias, counts against the ceiling of the group where the calling team holds its share, and settlement credits that same counter. A group name wins over a colliding deployment id, and a deployment id wins over any wildcard, as in the router. A name served through a wildcard counts against the group of the deployment behind the one pattern the router picks for it, the most specific proxy-wide pattern or, when none matches, the team's own, so a team's wildcard reservation behind an open*route is never charged or sized for traffic*serves. A provider model or routing group that also reaches an open deployment serves a share holder from its shared deployment alone (decision 19), so the counter matches what served the call. A team with shares in two groups over one provider model is counted against the first in config order. A usage row keyed by any of those names (the router stamps the row with the name the request used) is sized by the same resolution, aliases included, so the PTU-hours a team reads back match what the ceiling charged however it named the deployment. One team's usage page sizes the row by the deployment that team is served from behind the name, its shared one first and never one reserved for another team (the router's own team-ownership rule, now one shared predicate), so a team with no share on a name, or served by an open deployment next to another team's reservation, reads no PTU-hours on it; a page spanning several or all teams merges every team into one row per name and sizes it by the first reserved deployment behind the name. Charging a two-group team against the group that served the call was the alternative, and the pre-call check runs before routing picks that group. Sizing the all-teams page team by team was the alternative there, and it needs rows grouped by team, which that page's query merges awayPOST /team/delete,DELETE /organization/deletefor an organization owning such a team, checked before anything is deleted, and SCIMDELETE /scim/v2/Groups/{id}), since the other shares would stop adding up toptu_countand the deleted team's slice would go unbilled. Moving the share first is one PATCHmax_tokens, in normalized tokens) is larger than the team's whole per-minute share gets a 400 and charges nothing, since no retry could ever admit it. A 429 was the alternative, and a client would retry it forever. Large output budgets need large shares: a request asking for 32,000 output tokens needs about 80 PTU of gpt-5.4 or 25 PTU of gpt-5.4-mini before any share admits it, so a team with less has to lowermax_tokensmodel_info.team_id: a failing call there went from one upstream call on main to three withnum_retries: 2, a change outside what this PR shipsPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<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 moreDelays 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
Last updated: cdce71e, a merge of main that kept both sides of one import conflict in
scim_v2.py. This PR's diff against main is line for line the same after it, so QA, /live-pr-risk and /audit carry over it. QA and /live-pr-risk ran on 109f9bc, the last commit with a product diff, against its merge base aa879f7 on 2026-10-14 UTCRig, shared helpers and transcripts
Both legs ran the same script against fresh databases. Each leg is two proxies, P1 and P2, each booted with
--num_workers 2, sharing one Postgres database and one Redis, withLITELLM_ENABLE_PTU_COST_ATTRIBUTION=TrueandLITELLM_LICENSEexported, and calling the real Azure deployment behindazure/gpt-5.4-mini. Teams are created on P1 and keys on P2, and model calls alternate between the two. Case 13 adds P3 and P4 on the same database and Redis, P3 booted withoutLITELLM_ENABLE_PTU_COST_ATTRIBUTIONin its environment and P4 with it set toFalse(the before leg booted both without it, and the base reads no such flag), and both withkey_management_system: custompointing at a small store that holds the flag and logs every read. The deployment under test is 5 PTU of gpt-5.4-mini at $10 per PTU-hour, so $1,200 a day. Azure sizes gpt-5.4-mini at 7,900 tokens per PTU per minute with output counted 6x, so team A's 3 PTU is a ceiling of 23,700 and team B's 2 PTU is 15,800. Each P1 serves the dashboard built from its own worktree's ui/ treeshow.pyprints the status,retry-after,ptu R/Lfrom thex-ratelimit-model_per_team_ptu-remaining-tokensand-limit-tokensresponse headers, thex-litellm-model-groupheader, thex-litellm-model-idheader asserved by(ids print as<shared id>,<open id>and<split id>), the usage and the error message, andshowstream.pyprints the same for a stream with its chunk count.flat_cost_by_team.pyprintstotal_flat_cost,total_ptu_hoursand each day'sflat_costper team, andptu_by_group.pyprintstotal_tokens,total_ptu_hoursandptu_hoursper model group. Team ids print as team A, B and C. The daily flat-cost rollup and its backfill are the proxy's scheduled job, so the rig calls them once from the leg's own worktree:run_rollup.pyrollup <day>...awaitsrun_ptu_flat_cost_rollupfor each day andrun_rollup.py backfill <today>awaitsrun_ptu_flat_cost_backfill, whilerun_sched.pylock|nolock <day>awaitsrun_scheduled_ptu_rollup, the job the proxy runs at 00:15 UTC, with a Redis lock manager or with none, as on a proxy with no Redis (a QA window cannot wait for the real 00:15 UTC trigger, so the rig calls the function that trigger calls, with the same kind of lock manager), and every verdict is then read back throughGET /team/daily/activityor the Admin UIEach case below shows its steps once, then both legs' output. The User Flow's cases carry raw output here, and the rest are in a table with the full before and after transcripts
Case 1: register one PTU deployment split between team A (3 PTU) and team B (2 PTU)
Steps and output
ptu_sharesand noteam_id, then, since that is refused, the documented single-team registration, then GET /model/info on P2 after its database pollBefore
After
Case 2: who may call the deployment, on all three unified endpoints
Steps and output
Before
Team B, which should hold 2 PTU, cannot call the deployment at all, streaming or not
After
Teams A and B are served, each against its own share, on every endpoint and when streaming, and team C gets a 400 naming the reason
Case 3: team A's share is a per-minute ceiling, and team B keeps its own
Steps and output
Before
No ceiling applies to team A, so all three long calls run in one minute, and team B has no access
After
The call no minute could ever admit gets a 400 that says to lower max_tokens, so a client does not retry it. Two of the three concurrent 1,800-token calls fit in team A's minute and the third gets a 429 with 2,064 left, across both proxies. Team B is unaffected, and a small call that fits is still served
Case 6: the daily rollup splits the flat cost by share, and moving a share does not bill a paid day again
Steps and output
Before
The whole flat cost lands on team A, which holds the single-team registration
Before, step 3
The locked rerun moves 2026-10-12 to team C, but the rerun with no lock adds team C's row next to team A's, so 2026-10-13 is billed twice at $2,400
After
Each day is split 720 and 480 by share, and team C is not billed again for days team B already paid. Both scheduled reruns bill their day 720 and 480 to teams A and C, so no day is billed twice, with the lock or without it
Case 11: a team holding a share cannot be deleted until its share moves
Steps and output
After (the base cannot register a share, so there is no before)
Case 14: deleting the organization of a team holding a share, or that team through SCIM
Steps and output
Before
Both deletes go through, so team D's key stops working and team A, which held 3 PTU, is gone
After
Both deletes get a 400 naming the deployment, so team D and team A keep their shares and keep calling
Case 12: Team Usage page in the Admin UI
Steps and output
Before, on that leg's P1 at http://127.0.0.1:38511, at the merge base aa879f7 (the file name carries the head hash at upload time)
All teams read $3,600.00 and team A reads $3,600.00, the whole flat cost on team A, with five tiles and no PTU figure
After, on that leg's P1 at http://127.0.0.1:43934
All teams read $4,800.00 (the three split days plus the 2026-10-09 day) with a PTU Hours tile of 0.12, and team A reads $2,880.00, four days at $720, with the same tile and its tooltip explaining how to read PTU-hours
Other cases
The steps and raw output for these are in the full before and after transcripts
ptu_hoursfield/azurerouteFalseon P4Earlier rounds as controls
Bugs earlier rounds caught
At 2d1d021 a settlement landing after its minute rolled over moved the next minute's counter, which Case 4 now covers. At 17abc6e a split day whose write failed for one team kept the other team's row, so the backfill counted the day as priced and never billed the missing team, which Case 7 now covers. At 8a97ba4 a request bigger than the whole ceiling got a 429 with retry-after 60, so a retrying client would never get through, which Case 3 now covers with a 400
/live-pr-risk at 109f9bc
Scenarios, dependents and what was not verified
Base aa879f7 and head 109f9bc ran the same scenarios on two proxies with 2 workers each, one Postgres and Redis per side, and a forwarding recorder in front of Azure that counts every upstream call
Breaking. None found at 109f9bc
Backward incompatible. At ff7b7f0 a failing call to a deployment a team owns through
team_idmade 3 upstream calls on head and 1 on base, on chat and/v1/messages. 1251658 fixed it by keeping the team-aware retry lookup to PTU share holders, and a retry A/B at 109f9bc shows a team-owned deployment gets one upstream call on both sides. Every daily activity route (team, user, tag, organization) now returnsptu_hoursin each metrics block andtotal_ptu_hoursin metadata, both 0.0 when no PTU deployment exists. This is additive, the same shape change main made forflat_cost, and the integration goldens carry it in 109f9bcRegression risk. The sync
Router.completionpath is reachable only from the SDK, so the unit tests cover it and the rig does not./queue/chat/completionsis admin-only, so a team key gets the same 400 on both sides and the scheduler path for team keys is covered by unit tests alone. A cross-worker/model/info400 right after a PATCH reproduces on base too, so it is pre-existing/v1/chat/completions/v1/messages/v1/responsespriorityin body/queue/chat/completions/model/new,/model/{id}/update/model/info,/v2/model/infoRouter.completionThe integration suites passed with management at 62 tests on 1251658, and accounting at 31 and routing at 92 on 109f9bc
Not verified. The 00:15 UTC rollup was run in-process with the scheduler's own lock type, since that hour cannot fall inside a QA window. No Azure provisioned deployment was available, so PTU counts ran against a standard Azure deployment
Audit round 1 of 3
Matrix, 17 rows over 66 cells, all PASS but one Low flake
Every cell ran at 109f9bc against the merge base aa879f7, with two workers per proxy, a scripted Azure and Anthropic upstream and real Postgres and Redis. The head selection ran twice with seed 4106601 and the same collected and passed cells. The cells are the four test files in c106f93. The base drops a deployment declaring
ptu_shareswithoutteam_id, so its group answers 400ptu_hourson 5 routesbase_modeltimingThe one red control is
test_team_model_tpm_limit.py::test_concurrent_team_model_tpm_requests_reserve_tokens_before_reaching_the_provider, where three concurrent requests all got 429 and none was served. The reservation code it runs is identical on the merge base, so it is a Low caveat, and its fix is tracked separatelyRecent commits
Commits since the last product change
c106f93 adds the audit's integration tests for PTU shares, tests only
109f9bc moves the share-holder check for the retry lookups into
ptu_shares.py, with the same behavior, and addsptu_hoursandtotal_ptu_hoursto the daily activity integration goldens, since every route now reports them1251658 scopes the retry, priority queue and /v1/messages stream retry lookups to the caller only for teams holding a PTU share, so a deployment a team owns keeps main's single call on failure (design decision 22)
ff7b7f0 reads the PTU flag from a configured secret manager before the environment, the order
get_secretuses for every other setting (design decision 12)6d9a3d0 and 4d5903d delete a deployment day's PTU charge rows in the transaction that writes them, scoped by the day and the deployment, so a rerun after the shares moved bills the new holders alone, on a proxy without the Redis lock too (design decision 18)
1a4b393 writes each deployment-day's team charges in one Prisma batch with the retry around the whole batch, so a day is fully written or not at all (design decision 18)
8a97ba4 merges main at aa879f7 with no conflicts. Main touched no PR file in that range except the generated
schema.d.ts, and the PR diff is unchangedb70f6f7 refuses a request bigger than the team's whole ceiling with a 400 instead of a 429, serves a share holder only from its shared deployment, refuses to delete a team that still holds a share, reads the feature flag from a secret manager when the env var is unset, caches each team's ceiling until the model list changes, and adds a PTU Hours tooltip on Team Usage (design decisions 12 and 19 to 21)
e3492ae lists the two cached ceiling helpers in the router coverage check's ignore list, tests only
a5f9321 reads the PTU flag only once a team holds a share, refuses org and SCIM deletes of a team holding a share, keeps share holders on their shared deployment through retries, the priority scheduler and /v1/messages stream retries, and dates PTU-hours by the terms in force that day (design decisions 5, 8, 12, 20 and 21)
Type
🆕 New Feature
Caveats (if any)
Medium
max_tokensbigger than the team's whole share gets a 400 every time/azurepass-through route skips the share ceiling, as on mainptu_hours, and other usage rows show 0Medium caveats with workarounds and how main behaves
max_tokensget min(1,024, a quarter of the share in output tokens), 987 on 3 PTU of gpt-5.4-mini, and stop withfinish_reason: length(design decision 5)model_tpm_limitof the same 23,700 counts output once, stays above 4,096 and never gets the cap, so a team moving from that setup toptu_sharesloses those longer uncapped repliesmax_tokensyourself to pick the cap; capped requests are untouchedmax_tokensalone is bigger than the team's whole share gets a 400 every time, for example 32,000 output tokens on less than 80 PTU of gpt-5.4 (design decision 21)max_tokensor give the team a bigger share/azurepass-through route skip the share ceiling, so a share holder can use more than its share thereptu_hours: 0breakdown.model_groupsknow their model groupLow
30 low caveats, each left unfixed as net-negative to fix
breakdown.entitieskeepsptu_hoursat 0 on every page, so one team's PTU-hours come from a GET naming only that teamptu_effective_fromandptu_effective_to, so share holders keep the deployment and its ceiling outside those dates, while PTU-hours and the flat cost count only inside themteam_idrestriction ignores the dates the same wayptu_sharesgets Azure's ceiling and PTU-hoursopenai/with an Azure base URL, so a provider check would drop real reservations/utils/token_counteron a shared group counts by the public model name, since it passes no request to the router, as on mainptu_shareseditor yetPOST /model/newGET /v1/modelsfor share-less teams, andGET /health?model=<group>from such a team still probes it onceGET /team/daily/activitycarries the full valueptu_shareshas no cap on how many teams it names, and the team existence check looks them up in chunks under the database'sINlist boundteam_idis split by deleting it and registering it again withptu_sharesand the samemodel_info.id, not by a PATCH, which refuses the mix with a 400 (design decision 16, documented)fail_closed_rate_limit_enforcement: trueand Redis down, share-holding teams get a 503 on the shared deploymentptu_sharesin config.yaml is not checked against the team table, onlyPOST /model/newand the PATCH are*route also matches it/azurepass-through gets a 500 instead of the 400, and nothing reaches Azureptu_sharesmap written to the model table before this release, by a client posting the then-unknown key, is enforced at load: the deployment serves only the teams it names, sized from their shares, with no flat cost attributed until its terms existPATCH /model/{id}/updatewithptu_count,cost_per_ptu_per_hourandptu_effective_fromcompletes it, or delete and re-register the deployment without the mapPOST /model/newwrote, so it bills nothing on either path until the PATCHPOST /model/newwhile the flag was on serves for free once the flag is off: its token prices were zeroed at registration and no flat cost accrues without the flag, while a config.yaml entry keeps its token pricesteam_idreservations, now also the case for shared ones; turn the flag back on or re-register the deploymentptu_shareswithoutptu_countandcost_per_ptu_per_houris dropped at load, flag on or off: the startup log names the model and the reason, the proxy starts without it, and a request to its group gets a 400 with no healthy deploymentsPOST /v1/messageswithoutmax_tokensis a 500 from the Anthropic handler on main and on this branch for a team under no ceiling; under a ceiling this branch writes the implicit cap before the handler runs, so the same call is 200osv-scanfails on the tip for an upstream advisory on a dashboard dev dependency with no fixed release, in a lockfile this PR does not touch; it is not a required checkGET /team/daily/activitycarry the figuretest_concurrent_team_model_tpm_requests_reserve_tokens_before_reaching_the_providerwent red once in the audit, with three concurrent requests all refused because each held one of the key and team limitsFinal Attestation
The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
b41eed4 passes /live-pr-risk
e4b33bc passes /live-pr-risk
6f3915b passes /live-pr-risk
109f9bc passes /live-pr-risk
c106f93 passes /audit
Bugbot summary