Skip to content

feat(proxy): split Azure PTU deployments across teams with per-team PTU ceilings and PTU-hour reporting - #43043

Merged
mateo-berri merged 44 commits into
mainfrom
litellm_ptu_shares_per_team
Oct 15, 2026
Merged

mateo-berri merged 44 commits into
mainfrom
litellm_ptu_shares_per_team

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • One Azure PTU deployment belongs to exactly one team
  • Sharing it means hand-converting PTUs into per-team TPM limits
  • Flat cost lands on one team, usage never shows PTUs

How it solves it:

  • model_info.ptu_shares splits ptu_count across teams in whole PTUs
  • Only teams holding a share get routed to the deployment
  • Each share becomes a per-minute team token ceiling
  • Daily rollup splits the flat cost across teams by share
  • Team usage API and page report PTU-hours next to tokens

Docs for the new fields, the ceiling, and the cost split are in BerriAI/litellm-docs#1700 (docs/proxy/ptu_flat_cost.md and docs/proxy/dynamic_rate_limit.md), to merge after this PR

User Flow

Before: a proxy admin cannot split one PTU deployment across teams, and no team sees its PTU use

  1. POST https://litellm-domain/model/new with ptu_shares and no team_id gets 400 team_id is required when PTU fields are set
  2. Registered for team A through team_id, team B's key gets 400 Invalid model name on POST https://litellm-domain/v1/chat/completions
  3. Capping team A takes a hand-computed model_tpm_limit on POST https://litellm-domain/team/update
  4. GET https://litellm-domain/team/daily/activity puts the whole flat_cost on team A with no PTU figure, and https://litellm-domain/ui/usage shows tokens only

After: the admin declares the split once, and the proxy enforces it and bills each team

  1. The same POST https://litellm-domain/model/new gets 200, and a split that does not add up gets 400
  2. Teams A and B both get 200 on POST https://litellm-domain/v1/chat/completions, and a team with no share gets 400 reserved for the teams holding a PTU share
  3. Past 30 PTU of tokens in a minute team A gets 429 with retry-after, and team B keeps its 20 PTU
  4. GET https://litellm-domain/team/daily/activity splits flat_cost 720 and 480 and adds ptu_hours, and https://litellm-domain/ui/usage adds a PTU Hours tile
  5. Deleting a team holding a share, its organization, or its SCIM group gets 400 until the share moves
Full 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

  1. The admin sends POST https://litellm-domain/model/new with 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 400 team_id is required when PTU fields are set (one model maps to one team)
  2. They register it the documented way with "team_id": "<team-a>" instead, and team B's key then gets 400 Invalid model name passed in model=gpt-4.1-ptu on POST https://litellm-domain/v1/chat/completions
  3. To cap team A at its 30 PTU they set metadata.model_tpm_limit through POST https://litellm-domain/team/update to a TPM number they worked out by hand, and nothing keeps that number in step with the reservation
  4. GET https://litellm-domain/team/daily/activity?team_ids=&team_ids=&start_date=...&end_date=... shows the whole day's flat_cost under team A, nothing under team B, and no PTU figure anywhere; the Team Usage view at https://litellm-domain/ui/usage shows tokens only

After: the admin declares the split in PTUs once, the proxy enforces it per team, and cost and PTU-hours land on each team

  1. The admin sends the same POST https://litellm-domain/model/new with ptu_shares and no team_id and gets 200; shares that do not add up to ptu_count, or a team_id next to ptu_shares, get a 400 saying so
  2. Team A's and team B's keys both get 200 on POST https://litellm-domain/v1/chat/completions to gpt-4.1-ptu, while a key from a team holding no share gets 400 Deployment gpt-4.1-ptu is reserved for the teams holding a PTU share of it
  3. Once team A's requests pass 30 PTU worth of Azure-normalized tokens in a minute (30 x 3,000 TPM on gpt-4.1, output counted at 4x) the next one gets 429 Rate limit exceeded for model_per_team_ptu: <team-a>:gpt-4.1-ptu with a retry-after, a single request bigger than the whole 30 PTU gets 400 This request needs ... so it can never be admitted. Lower max_tokens or shorten the prompt., and team B keeps its own 20 PTU
  4. The same GET https://litellm-domain/team/daily/activity shows the day's flat_cost split 720 under team A and 480 under team B (30 and 20 of the $1,200 day) plus ptu_hours per 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 tile
  5. POST https://litellm-domain/team/delete for a team that still holds a share, DELETE https://litellm-domain/organization/delete for the organization that team belongs to, and SCIM DELETE https://litellm-domain/scim/v2/Groups/ each get 400 naming the deployments, until the admin moves its share to another team

Design decisions

22 design decisions, each with the alternative it rejected
  1. ptu_shares and team_id are mutually exclusive and the shares must add up to ptu_count exactly. 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 reason ptu_shares without ptu_count and cost_per_ptu_per_hour is 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 up
  2. A shared deployment is not team-scoped in the database, so it keeps the public model name and stays visible in model lists. Callers holding no share, the master key and team-less keys included, are dropped at routing the way access windows drop them, so a request from a share-less team fails with a 400 that names the reason instead of the generic invalid-model error
  3. The ceiling applies only to ptu_shares deployments. A single-team team_id deployment gets no new 429s, since the team already owns all of it, but its usage does report PTU-hours
  4. The Azure sizing table lives in one module under the Azure provider (litellm/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_model is the preferred lookup key because an Azure deployment name is arbitrary
  5. The limiter charges Azure's normalized tokens (uncached input, cached input at the model's cached ratio, output times the model's output ratio) so the ceiling matches how Azure sizes a PTU. The pre-call reservation against the ceiling is taken in those same units, the output budget weighted by the model's output ratio, so a burst of concurrent requests cannot admit more than the share the way a raw-token reservation would (300 output tokens reserve 1,200 normalized tokens at 4:1, not 300). It is settled after the call at the response's normalized usage, on a failed stream at the recovered partial usage, and refunded whole on a proxy-side rejection, always with the ceiling admission resolved even if the share changed meanwhile. When usage cannot be resolved it charges the raw total the other scopes charge. A request without max_tokens gets 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 implicit max_tokens cap 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 with finish_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 own max_tokens is never rewritten. Leaving uncapped requests unbounded was the alternative, and it would let one of them reserve nothing and then overrun the share
  6. Two shared deployments of different models in one model group take the larger output ratio and the larger cached-input ratio, which over-counts on the cheaper model rather than under-counting on the dearer one
  7. GPT-6 cache-write and long-context weights from the Azure page are ignored; only the cached-input tenth is modeled. Weighting long-context requests was the alternative, but the daily rows sum a day's tokens and cannot tell which requests crossed the long-context threshold
  8. PTU-hours are computed on the read path of GET /team/daily/activity from 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 under breakdown.entities, keep ptu_hours at 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 whose ptu_effective_from to ptu_effective_to window covers the row's day, so tokens from before a reservation starts or after it ends read no PTU-hours
  9. The share filter (which teams a shared deployment is served to) applies whenever ptu_shares is 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 on LITELLM_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 declares ptu_shares has 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's ignore_invalid_deployments logs 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 refusal
  10. The Team Usage page adds a sixth "PTU Hours" tile only for a team whose window consumed PTU-hours; every other team sees the same five tiles as before
  11. The ceiling is a per-minute descriptor (model_per_team_ptu:<team_id>:<model group>) on the same window as the team's model_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 minute
  12. LITELLM_ENABLE_PTU_COST_ATTRIBUTION is read from a configured secret manager first whenever get_secret would ask one for it, and from the process environment otherwise, the same order get_secret uses 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 setting
  13. ptu_count and every share are whole PTUs, which is how Azure sells them: 100.0 is accepted as 100, and 100.5 is refused at registration from POST /model/new and config.yaml alike
  14. A deployment registered for one team gets a unique internal model_name and keeps the public one in model_info.team_public_model_name, so the sizing lookup for PTU-hours and the ceiling matches on either name; usage rows carry the public name
  15. Every team id named in ptu_shares is checked against the team table on POST /model/new and PATCH /model/{model_id}/update, the same check team_id already 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 for team_id
  16. A deployment one team owns through team_id is not switched to ptu_shares by 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 a POST /model/new with the same model_info.id, which keeps the id the flat-cost rows are keyed on, and the docs say so. The alternative, letting an explicit team_id: null clear 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 clearing
  17. A request naming the shared deployment by model_info.id or provider model (litellm_params.model), or through a routing group or model_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 away
  18. Each deployment-day's team charges are written in one database transaction, retried as a whole, because the backfill counts a deployment-day as priced once any team's row for it exists, so a partial write would leave the missing team unbilled for good. Checking that a day's rows add up to its flat cost was the alternative, but it bills a day again whenever the rate or the shares change afterwards. Storing the share map each day was billed under would also work and needs a new column. The same transaction first deletes the day's rows for that deployment, so a rerun after the shares moved bills the new holders alone, also on a proxy without the Redis lock. Deleting only the rows of teams no longer charged was the alternative, and it needs a negated team list of no fixed size
  19. A team holding a share in a group is served only from its shared deployments there, and the group's open deployments serve the teams holding none. Letting holders spill onto an open pay-as-you-go deployment was the alternative, but the ceiling would 429 them while open capacity sat idle and PTU-hours would count tokens the reservation never served. Azure's own spillover is the documented way to overflow a reservation
  20. Deleting a team that still holds a share is refused with a 400 naming the deployment on every route that deletes teams (POST /team/delete, DELETE /organization/delete for an organization owning such a team, checked before anything is deleted, and SCIM DELETE /scim/v2/Groups/{id}), since the other shares would stop adding up to ptu_count and the deleted team's slice would go unbilled. Moving the share first is one PATCH
  21. A request whose own token budget (prompt plus max_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 lower max_tokens
  22. Router retries, the priority queue and the /v1/messages same-group stream retry scope their healthy-deployment lookup to the caller only when the caller's team holds a PTU share, so a share holder is retried on its shared deployment and every other caller keeps main's lookup. Scoping every caller was the alternative, but it changed retries for deployments a team owns through model_info.team_id: a failing call there went from one upstream call on main to three with num_retries: 2, a change outside what this PR ships

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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 UTC

Rig, 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, with LITELLM_ENABLE_PTU_COST_ATTRIBUTION=True and LITELLM_LICENSE exported, and calling the real Azure deployment behind azure/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 without LITELLM_ENABLE_PTU_COST_ATTRIBUTION in its environment and P4 with it set to False (the before leg booted both without it, and the base reads no such flag), and both with key_management_system: custom pointing 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/ tree

MK=(-H "Authorization: Bearer $LITELLM_MASTER_KEY"); CT=(-H 'Content-Type: application/json')
EFF=2026-10-11T00:00:00Z; TODAY=2026-10-14
call() {
  mt=$([ "$5" = 0 ] || echo ", \"max_tokens\": $5"); mo=$([ "$5" = 0 ] || echo ", \"max_output_tokens\": $5")
  case $4 in
    chat) r=/v1/chat/completions b="{\"model\": \"gpt-5.4-mini-ptu\", \"messages\": [{\"role\": \"user\", \"content\": \"$6\"}]$mt, \"cache\": {\"no-cache\": true}}";;
    messages) r=/v1/messages b="{\"model\": \"gpt-5.4-mini-ptu\", \"messages\": [{\"role\": \"user\", \"content\": \"$6\"}]$mt, \"cache\": {\"no-cache\": true}}";;
    responses) r=/v1/responses b="{\"model\": \"gpt-5.4-mini-ptu\", \"input\": \"$6\"$mo, \"cache\": {\"no-cache\": true}}";;
  esac
  curl -s -i -m 300 -X POST "$2$r" -H "Authorization: Bearer $3" "${CT[@]}" -d "$b" | python3 show.py "$1 (sent $(date -u +%TZ), $r)"
}
stream_call() { curl -s -i -N -m 300 -X POST "$2/v1/chat/completions" -H "Authorization: Bearer $3" "${CT[@]}" -d "{\"model\": \"gpt-5.4-mini-ptu\", \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"messages\": [{\"role\": \"user\", \"content\": \"$5\"}], \"max_tokens\": $4, \"cache\": {\"no-cache\": true}}" | python3 showstream.py "$1 (sent $(date -u +%TZ), /v1/chat/completions stream)"; }
LONG='Write a 3000 word short story about a lighthouse keeper. Do not stop early.'
model_body() {
  NAME=$1 SHARES=$2 TEAM=$3 FROM=$4 TO=$5 python3 - <<'EOF'
import json, os
info = {"base_model": "gpt-5.4-mini", "ptu_count": 5, "cost_per_ptu_per_hour": 10.0, "ptu_effective_from": os.environ["FROM"]}
if os.environ["TO"]: info["ptu_effective_to"] = os.environ["TO"]
if os.environ["SHARES"]: info["ptu_shares"] = json.loads(os.environ["SHARES"])
if os.environ["TEAM"]: info["team_id"] = os.environ["TEAM"]
print(json.dumps({"model_name": os.environ["NAME"], "litellm_params": {"model": "azure/gpt-5.4-mini", "api_base": os.environ["AZURE_QA_API_BASE"], "api_key": os.environ["AZURE_QA_API_KEY"], "api_version": "2025-04-01-preview"}, "model_info": info}))
EOF
}
activity() { curl -s "$P2/team/daily/activity?team_ids=$TEAM_A_ID,$TEAM_B_ID,$TEAM_C_ID&start_date=$1&end_date=$2&page_size=100" "${MK[@]}" | python3 flat_cost_by_team.py; }
one_team() { curl -s "$P2/team/daily/activity?team_ids=$1&start_date=$TODAY&end_date=$TODAY&page_size=100" "${MK[@]}" | python3 ptu_by_group.py; }

show.py prints the status, retry-after, ptu R/L from the x-ratelimit-model_per_team_ptu-remaining-tokens and -limit-tokens response headers, the x-litellm-model-group header, the x-litellm-model-id header as served by (ids print as <shared id>, <open id> and <split id>), the usage and the error message, and showstream.py prints the same for a stream with its chunk count. flat_cost_by_team.py prints total_flat_cost, total_ptu_hours and each day's flat_cost per team, and ptu_by_group.py prints total_tokens, total_ptu_hours and ptu_hours per 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.py rollup <day>... awaits run_ptu_flat_cost_rollup for each day and run_rollup.py backfill <today> awaits run_ptu_flat_cost_backfill, while run_sched.py lock|nolock <day> awaits run_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 through GET /team/daily/activity or the Admin UI

Each 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
  1. POST /model/new on P1 with ptu_shares and no team_id, then, since that is refused, the documented single-team registration, then GET /model/info on P2 after its database poll
curl -s -w '\nHTTP %{http_code}' -X POST $P1/model/new "${MK[@]}" "${CT[@]}" -d "$(model_body gpt-5.4-mini-ptu "{\"$TEAM_A_ID\": 3, \"$TEAM_B_ID\": 2}" "" $EFF "")"
curl -s -w '\nHTTP %{http_code}' -X POST $P1/model/new "${MK[@]}" "${CT[@]}" -d "$(model_body gpt-5.4-mini-ptu "" "$TEAM_A_ID" $EFF "")"
sleep 12; curl -s $P2/model/info "${MK[@]}"

Before

POST /model/new on P1 with ptu_shares and no team_id: HTTP 400, "team_id is required when PTU fields are set (one model maps to one team)"
fallback, the documented single-team way: POST /model/new on P1 with model_info.team_id = team A: HTTP 200
GET /model/info on P2: gpt-5.4-mini-ptu ptu_shares None team_id team A

After

POST /model/new on P1 with ptu_shares and no team_id: HTTP 200, {"model_id": "<returned>"}
POST /model/new on P1 with shares adding up to 4 of 5 PTU: HTTP 400 {"error":{"message":"ptu_shares must add up to ptu_count (4 of 5 allocated)","type":"auth_error","param":"None","code":"400"}} HTTP 400
GET /model/info on P2: gpt-5.4-mini-ptu ptu_shares {'team B': 2, 'team A': 3} team_id None

Case 2: who may call the deployment, on all three unified endpoints

Steps and output
  1. team A on /v1/chat/completions, /v1/responses and /v1/messages, then teams B and C on /v1/chat/completions, alternating P1 and P2, then the same three teams streaming
call c2-a-chat $P1 $TEAM_A_KEY chat 20 'Say hi'; call c2-a-responses $P2 $TEAM_A_KEY responses 20 'Say hi'
call c2-a-messages $P1 $TEAM_A_KEY messages 20 'Say hi'; call c2-b-chat $P2 $TEAM_B_KEY chat 20 'Say hi'; call c2-c-chat $P1 $TEAM_C_KEY chat 20 'Say hi'
stream_call c2-a-chat-stream $P2 $TEAM_A_KEY 20 'Say hi'; stream_call c2-b-chat-stream $P1 $TEAM_B_KEY 20 'Say hi'; stream_call c2-c-chat-stream $P2 $TEAM_C_KEY 20 'Say hi'

Before

c2-a-chat (sent 07:05:29Z, /v1/chat/completions) 07:05:31Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, usage in 8 out 5 total 13, finish_reason stop
c2-a-responses (sent 07:05:31Z, /v1/responses) 07:05:32Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, usage in 8 out 6 total 14
c2-a-messages (sent 07:05:32Z, /v1/messages) 07:05:34Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, usage in 8 out 5, stop_reason end_turn
c2-b-chat (sent 07:05:34Z, /v1/chat/completions) 07:05:34Z: HTTP 400, no ptu headers, "/chat/completions: Invalid model name passed in model=gpt-5.4-mini-ptu."
c2-c-chat (sent 07:05:34Z, /v1/chat/completions) 07:05:34Z: HTTP 400, no ptu headers, "/chat/completions: Invalid model name passed in model=gpt-5.4-mini-ptu."
c2-a-chat-stream (sent 10:19:28Z, /v1/chat/completions stream) 10:19:30Z: HTTP 200, text/event-stream, no ptu headers, group gpt-5.4-mini-ptu, 6 chunks then [DONE], usage in 8 out 5, finish_reason stop
c2-b-chat-stream (sent 10:19:30Z, /v1/chat/completions stream) 10:19:30Z: HTTP 400, application/json, no ptu headers, "/chat/completions: Invalid model name passed in model=gpt-5.4-mini-ptu."
c2-c-chat-stream (sent 10:19:30Z, /v1/chat/completions stream) 10:19:30Z: HTTP 400, application/json, no ptu headers, "/chat/completions: Invalid model name passed in model=gpt-5.4-mini-ptu."

Team B, which should hold 2 PTU, cannot call the deployment at all, streaming or not

After

c2-a-chat (sent 14:30:09Z, /v1/chat/completions) 14:30:14Z: HTTP 200, ptu 23579/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop
c2-a-responses (sent 14:30:14Z, /v1/responses) 14:30:15Z: HTTP 200, ptu 23541/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 6 total 14
c2-a-messages (sent 14:30:15Z, /v1/messages) 14:30:36Z: HTTP 200, ptu 23497/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5, stop_reason end_turn
c2-b-chat (sent 14:30:36Z, /v1/chat/completions) 14:30:59Z: HTTP 200, ptu 15679/15800, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop
c2-c-chat (sent 14:30:59Z, /v1/chat/completions) 14:30:59Z: HTTP 400, no ptu headers, "litellm.BadRequestError: Deployment gpt-5.4-mini-ptu is reserved for the teams holding a PTU share of it\n\nLiteLLM: model group 'gpt-5.4-mini-ptu' failed with the error above. No fallback was attempted."
c2-a-chat-stream (sent 14:30:59Z, /v1/chat/completions stream) 14:31:01Z: HTTP 200, text/event-stream, no ptu headers, group gpt-5.4-mini-ptu, 6 chunks then [DONE], usage in 8 out 5, finish_reason stop
c2-b-chat-stream (sent 14:31:01Z, /v1/chat/completions stream) 14:31:02Z: HTTP 200, text/event-stream, no ptu headers, group gpt-5.4-mini-ptu, 6 chunks then [DONE], usage in 8 out 5, finish_reason stop
c2-c-chat-stream (sent 14:31:03Z, /v1/chat/completions stream) 14:31:03Z: HTTP 400, application/json, no ptu headers, "litellm.BadRequestError: Deployment gpt-5.4-mini-ptu is reserved for the teams holding a PTU share of it\n\nLiteLLM: model group 'gpt-5.4-mini-ptu' failed with the error above. No fallback was attempted."

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
  1. in a fresh minute, team A asks for 4,000 output tokens (24,000 normalized, more than its 23,700), then sends three concurrent 1,800-token calls (about 10,800 normalized each, so only two fit), then team B and team A send small calls.
call c3-a-4000 $P2 $TEAM_A_KEY chat 4000 'Say hi'
for i in 1 2 3; do call c3-a-1800-$i $([ $i = 2 ] && echo $P2 || echo $P1) $TEAM_A_KEY chat 1800 "$LONG" > c3_$i.out & done; wait; cat c3_1.out c3_2.out c3_3.out
call c3-b-20 $P1 $TEAM_B_KEY chat 20 'Say hi'; call c3-a-20 $P2 $TEAM_A_KEY chat 20 'Say hi'

Before

c3-a-4000 (sent 08:09:24Z, /v1/chat/completions) 08:09:31Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, served by <team A's deployment>, usage in 8 out 5 total 13, finish_reason stop
c3-a-1800-1 (sent 08:09:31Z, /v1/chat/completions) 08:09:51Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, served by <team A's deployment>, usage in 24 out 1800 total 1824, finish_reason length
c3-a-1800-2 (sent 08:09:31Z, /v1/chat/completions) 08:09:51Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, served by <team A's deployment>, usage in 24 out 1800 total 1824, finish_reason length
c3-a-1800-3 (sent 08:09:31Z, /v1/chat/completions) 08:09:57Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, served by <team A's deployment>, usage in 24 out 1800 total 1824, finish_reason length
c3-b-20 (sent 08:09:57Z, /v1/chat/completions) 08:09:57Z: HTTP 400, no ptu headers, "/chat/completions: Invalid model name passed in model=gpt-5.4-mini-ptu."
c3-a-20 (sent 08:09:57Z, /v1/chat/completions) 08:09:58Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu, served by <team A's deployment>, usage in 8 out 5 total 13, finish_reason stop

No ceiling applies to team A, so all three long calls run in one minute, and team B has no access

After

c3-a-4000 (sent 14:32:05Z, /v1/chat/completions) 14:32:05Z: HTTP 400, no ptu headers, "This request needs 24001 normalized tokens, more than your team's PTU share of gpt-5.4-mini-ptu allows in a minute (23700), so it can never be admitted. Lower max_tokens or shorten the prompt."
c3-a-1800-1 (sent 14:32:05Z, /v1/chat/completions) 14:32:40Z: HTTP 200, ptu 2064/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 24 out 1800 total 1824, finish_reason length
c3-a-1800-2 (sent 14:32:05Z, /v1/chat/completions) 14:32:05Z: HTTP 429, retry-after 60, no ptu headers, "Rate limit exceeded for model_per_team_ptu: team A:gpt-5.4-mini-ptu. Limit type: tokens. Current limit: 23700, Remaining: 2064. Limit resets at: 2026-10-14 14:33:05 UTC"
c3-a-1800-3 (sent 14:32:05Z, /v1/chat/completions) 14:32:33Z: HTTP 200, ptu 12882/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 24 out 1800 total 1824, finish_reason length
c3-b-20 (sent 14:32:40Z, /v1/chat/completions) 14:32:50Z: HTTP 200, ptu 15679/15800, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop
c3-a-20 (sent 14:32:50Z, /v1/chat/completions) 14:32:57Z: HTTP 200, ptu 1931/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop

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
  1. run the rollup for 2026-10-11 to 2026-10-13 and read the three teams back
  2. after leg only, PATCH the deployment on P1 to move team B's 2 PTU to team C, run the next backfill and read the same days again
  3. wait 5 minutes, then rerun 2026-10-12 as the scheduled job holding the Redis lock and 2026-10-13 as the same job on a proxy with no Redis, and read the days again. The before leg does this on a fresh database with a single-team reservation moved from team A to team C, since the base refuses shares
$WT/.venv/bin/python run_rollup.py rollup 2026-10-11 2026-10-12 2026-10-13; activity 2026-10-11 2026-10-13
sleep 300; $WT/.venv/bin/python run_sched.py lock 2026-10-12; $WT/.venv/bin/python run_sched.py nolock 2026-10-13; activity 2026-10-11 2026-10-13

Before

rollup 2026-10-11 models_processed=1, rows_written=1, rows_failed=0, lapsed=())
rollup 2026-10-12 models_processed=1, rows_written=1, rows_failed=0, lapsed=())
rollup 2026-10-13 models_processed=1, rows_written=1, rows_failed=0, lapsed=())
total_flat_cost 3600.0 | total_ptu_hours <field absent>
2026-10-11 flat_cost 1200.0 {'team A': 1200.0}
2026-10-12 flat_cost 1200.0 {'team A': 1200.0}
2026-10-13 flat_cost 1200.0 {'team A': 1200.0}

The whole flat cost lands on team A, which holds the single-team registration

Before, step 3

POST /team/new on P1 ptu-sched-a -> team A and ptu-sched-c -> team C
POST /model/new on P1, gpt-5.4-mini-ptu-sched-113324, 5 PTU at $10 per PTU-hour owned by team A from 2026-10-11T00:00:00Z: HTTP 200
daily rollup for 2026-10-11 2026-10-12 2026-10-13 (in-process, this leg's code)
rollup 2026-10-11 RollupResult(day=datetime.date(2026, 10, 11), models_processed=5, rows_written=5, rows_failed=0, lapsed=())
rollup 2026-10-12 RollupResult(day=datetime.date(2026, 10, 12), models_processed=5, rows_written=5, rows_failed=0, lapsed=())
rollup 2026-10-13 RollupResult(day=datetime.date(2026, 10, 13), models_processed=5, rows_written=5, rows_failed=0, lapsed=())
GET /team/daily/activity on P2 for teams A and C, 2026-10-11 to 2026-10-13
total_flat_cost 3600.0
2026-10-11 flat_cost 1200.0 {'team A': 1200.0}
2026-10-12 flat_cost 1200.0 {'team A': 1200.0}
2026-10-13 flat_cost 1200.0 {'team A': 1200.0}
PATCH /model/<id>/update on P1 moving the reservation from team A to team C, the single-team way: HTTP 200
waiting 5 minutes, past the prune's clock-skew grace, so the first pricing is as old as a real rerun would find it
the 00:15 UTC scheduled rollup job reruns 2026-10-12 holding the Redis lock (in-process, this leg's code)
scheduled lock 2026-10-12 models_processed=5, rows_written=5, rows_failed=0, lapsed=())
the scheduled rollup job reruns 2026-10-13 on a proxy with no Redis, so without the lock (in-process, this leg's code)
scheduled nolock 2026-10-13 models_processed=5, rows_written=5, rows_failed=0, lapsed=())
GET /team/daily/activity on P2 for teams A and C, 2026-10-11 to 2026-10-13 after both reruns
total_flat_cost 4800.0
2026-10-11 flat_cost 1200.0 {'team A': 1200.0}
2026-10-12 flat_cost 1200.0 {'team C': 1200.0}
2026-10-13 flat_cost 2400.0 {'team A': 1200.0, 'team C': 1200.0}

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

daily rollup for 2026-10-11 2026-10-12 2026-10-13 (in-process, this leg's code)
rollup 2026-10-11 models_processed=1, rows_written=2, rows_failed=0, lapsed=())
rollup 2026-10-12 models_processed=1, rows_written=2, rows_failed=0, lapsed=())
rollup 2026-10-13 models_processed=1, rows_written=2, rows_failed=0, lapsed=())
GET /team/daily/activity on P2 for teams A, B, C, 2026-10-11 to 2026-10-13
total_flat_cost 3600.0 | total_ptu_hours 0.0
2026-10-11 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
2026-10-12 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
2026-10-13 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
PATCH /model/<id>/update on P1 moving team B's 2 PTU to team C: HTTP 200
next backfill catch-up pass (in-process, today=2026-10-14)
backfill BackfillResult(start=datetime.date(2026, 10, 11), end=datetime.date(2026, 10, 13), days_scanned=3, rows_written=0, rows_failed=0)
GET /team/daily/activity on P2 for teams A, B, C, 2026-10-11 to 2026-10-13 again
total_flat_cost 3600.0 | total_ptu_hours 0.0
2026-10-11 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
2026-10-12 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
2026-10-13 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
waiting 5 minutes, past the prune's clock-skew grace, so the first pricing is as old as a real rerun would find it
the 00:15 UTC scheduled rollup job reruns 2026-10-12 holding the Redis lock (in-process, this leg's code)
scheduled lock 2026-10-12 models_processed=1, rows_written=2, rows_failed=0, lapsed=())
the scheduled rollup job reruns 2026-10-13 on a proxy with no Redis, so without the lock (in-process, this leg's code)
scheduled nolock 2026-10-13 models_processed=1, rows_written=2, rows_failed=0, lapsed=())
GET /team/daily/activity on P2 for teams A, B, C, 2026-10-11 to 2026-10-13 after both reruns
total_flat_cost 3600.0 | total_ptu_hours 0.0
2026-10-11 flat_cost 1200.0 {'team A': 720.0, 'team B': 480.0}
2026-10-12 flat_cost 1200.0 {'team A': 720.0, 'team C': 480.0}
2026-10-13 flat_cost 1200.0 {'team A': 720.0, 'team C': 480.0}

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
  1. POST /team/delete on P1 for team C, a small call from team C, then POST /team/delete on P1 for team B

After (the base cannot register a share, so there is no before)

POST /team/delete on P1 for team C (holds 2 PTU on two deployments): {"detail":{"error":"Team <team C id> holds a PTU share on deployment <shared id>, <split id>. Move its share to another team in model_info.ptu_shares before deleting the team."}} HTTP 400
c11-c-chat (sent 14:49:28Z, /v1/chat/completions) 14:49:30Z: HTTP 200, ptu 15565/15800, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop
POST /team/delete on P1 for team B (holds no share now): HTTP 200 {"deleted_teams":["<team B id>"]} HTTP 200

Case 14: deleting the organization of a team holding a share, or that team through SCIM

Steps and output
  1. create organization ptu-org with team ptu-team-d in it and give team D all 5 PTU of gpt-5.4-mini-ptu-org, then delete the organization, then delete team A through SCIM, calling after each delete
ORG_ID=$(curl -s -X POST $P1/organization/new "${MK[@]}" "${CT[@]}" -d '{"organization_alias": "ptu-org"}' | jq -r .organization_id)
TEAM_D_ID=$(curl -s -X POST $P1/team/new "${MK[@]}" "${CT[@]}" -d "{\"team_alias\": \"ptu-team-d\", \"organization_id\": \"$ORG_ID\"}" | jq -r .team_id)
curl -s -X POST $P1/model/new "${MK[@]}" "${CT[@]}" -d "$(model_body gpt-5.4-mini-ptu-org "{\"$TEAM_D_ID\": 5}" "" $EFF "")"
curl -s -X DELETE $P1/organization/delete "${MK[@]}" "${CT[@]}" -d "{\"organization_ids\": [\"$ORG_ID\"]}"
curl -s -X DELETE "$P2/scim/v2/Groups/$TEAM_A_ID" "${MK[@]}"

Before

POST /organization/new on P1 ptu-org, POST /team/new on P1 ptu-team-d inside it, POST /key/generate on P2 -> ptu-team-d-key
POST /model/new on P1, gpt-5.4-mini-ptu-org with ptu_shares {team D: 5}: HTTP 400, so the documented single-team way with model_info.team_id = team D: HTTP 200
c14-d-before-delete (/v1/chat/completions, gpt-5.4-mini-ptu-org) 10:20:53Z: HTTP 200, no ptu headers, group gpt-5.4-mini-ptu-org, served by <org deployment id>, usage in 8 out 5 total 13, finish_reason stop
DELETE /organization/delete on P1 for ptu-org: [{"organization_id":"<org id>","organization_alias":"ptu-org", ...}] HTTP 200
c14-d-after-org-delete (/v1/chat/completions, gpt-5.4-mini-ptu-org) 10:20:53Z: HTTP 401, no ptu headers, "Authentication Error, Invalid proxy server token passed. ..."
DELETE /scim/v2/Groups/<team A id> on P2 (team A holds 3 PTU of gpt-5.4-mini-ptu):  HTTP 204
c14-a-after-scim-delete (sent 10:20:54Z, /v1/chat/completions) 10:20:54Z: HTTP 404, no ptu headers, "{'error': \"Team doesn't exist in db. Team=team A. Create team via `/team/new` call.\"}"

Both deletes go through, so team D's key stops working and team A, which held 3 PTU, is gone

After

POST /organization/new on P1 ptu-org, POST /team/new on P1 ptu-team-d inside it, POST /key/generate on P2 -> ptu-team-d-key
POST /model/new on P1, gpt-5.4-mini-ptu-org with ptu_shares {team D: 5}: HTTP 200
c14-d-before-delete (/v1/chat/completions, gpt-5.4-mini-ptu-org) 14:50:57Z: HTTP 200, ptu 39379/39500, group gpt-5.4-mini-ptu-org, served by <org deployment id>, usage in 8 out 5 total 13, finish_reason stop
DELETE /organization/delete on P1 for ptu-org: {"detail":{"error":"Team team D holds a PTU share on deployment <org deployment id>. Move its share to another team in model_info.ptu_shares before deleting the team."}} HTTP 400
c14-d-after-org-delete (/v1/chat/completions, gpt-5.4-mini-ptu-org) 14:50:57Z: HTTP 200, ptu 39341/39500, group gpt-5.4-mini-ptu-org, served by <org deployment id>, usage in 8 out 5 total 13, finish_reason stop
DELETE /scim/v2/Groups/<team A id> on P2 (team A holds 3 PTU of gpt-5.4-mini-ptu): {"error":{"message":"{'error': 'Team team A holds a PTU share on deployment <shared id>, <split id>. Move its share to another team in model_info.ptu_shares before deleting the team.'}","type":"inter ... HTTP 400
c14-a-after-scim-delete (sent 14:50:57Z, /v1/chat/completions) 14:51:20Z: HTTP 200, ptu 23541/23700, group gpt-5.4-mini-ptu, served by <shared id>, usage in 8 out 5 total 13, finish_reason stop

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
  1. open http://127.0.0.1:38511/ui/login and sign in as admin
  2. go to http://127.0.0.1:38511/ui/usage and pick Team Usage in the usage selector
  3. set the range to 9 Oct to 14 Oct
  4. type ptu-team-a in "Search teams by alias..." and pick it
  5. after leg only, hover the PTU Hours tile's info icon

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

pr43043-8a97ba47d4-r2_before_all.png
pr43043-8a97ba47d4-r2_before_team_a.png

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

pr43043-109f9bc979-r10_after_all.png
pr43043-109f9bc979-r10_after_team_a.png

Other cases

The steps and raw output for these are in the full before and after transcripts

Case Before After
4, late settlement no per-minute ledger next minute untouched
5, PTU-hours no ptu_hours field named team, per group
7, failed write day split refused both teams billed later
8, no max_tokens 6,274 out, no ceiling stops at 987 out
9, /azure route base refuses shares share not counted
10, open deployment base refuses shares non-holders use it
13, flag in secrets 4 reads per call 0 reads for team E
13, env False on P4 base has no flag secret manager wins

Earlier 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_id made 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 returns ptu_hours in each metrics block and total_ptu_hours in metadata, both 0.0 when no PTU deployment exists. This is additive, the same shape change main made for flat_cost, and the integration goldens carry it in 109f9bc

Regression risk. The sync Router.completion path is reachable only from the SDK, so the unit tests cover it and the rig does not. /queue/chat/completions is 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/info 400 right after a PATCH reproduces on base too, so it is pre-existing

Dependent Entry State
Router retries, chat /v1/chat/completions verified live
Router retries, messages /v1/messages verified live
Router retries, responses /v1/responses verified live
Priority scheduler priority in body verified live
/queue/chat/completions admin key verified live
Team PTU ceiling limiter headers verified live, QA
Key and team TPM limits limiter headers verified live
/model/new, /model/{id}/update management verified live
/model/info, /v2/model/info management verified live
Team, org and SCIM deletes management verified live
Daily activity, 4 routes spend verified live
Daily rollup job 00:15 UTC job in-process, QA
Team Usage page Admin UI verified live, QA
Sync Router.completion SDK unit tested
Integration suites mgmt, accounting, routing passed

The 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_shares without team_id, so its group answers 400

Rows Cells Base Head, twice Result At
Holder on chat, responses, messages 6 400, dropped 200 from shared PASS 109f9bc
Outsider and master key 6 400, dropped 400 reserved PASS 109f9bc
Holder in a mixed group 1 served by open own deployment PASS 109f9bc
Oversize, 1x and 2x 2 no ceiling 400 up front PASS 109f9bc
Settle, cached ratio, 500 refund 3 no ceiling counter matches PASS 109f9bc
Cache-hit twins 2 no ceiling settled, outsider 400 PASS 109f9bc
Retry, scheduler, messages retry 3 400, dropped holder served PASS 109f9bc
Flag off 2 served rule kept, bad split dropped PASS 109f9bc
Burst, worker killed 2 no ceiling only fits admitted PASS 109f9bc
Rollup split, share move 1 create 400 96/48, then 48/96 PASS 109f9bc
ptu_hours on 5 routes 5 no field matches or 0 PASS 109f9bc
Create guards, malformed 14 400 or 200 400 or 422 PASS 109f9bc
Flag-off store, PATCH 2 200 or 400 400, shares kept PASS 109f9bc
Team, org, SCIM delete 3 setup 400 400, row kept PASS 109f9bc
Bystander, after move, whole PTU 3 setup 400 200 PASS 109f9bc
64 KB base_model timing 1 400, dropped within 3x PASS 109f9bc
Controls, mgmt and accounting 8 not run pass PASS 109f9bc
Controls, providers 4 not run 3 pass, 1 flake Low 109f9bc

The 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 separately

Recent 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 adds ptu_hours and total_ptu_hours to the daily activity integration goldens, since every route now reports them

1251658 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_secret uses 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 unchanged

b70f6f7 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

  • A small share caps uncapped replies, at 987 output tokens on 3 PTU of gpt-5.4-mini
  • A max_tokens bigger than the team's whole share gets a 400 every time
  • Moving a share in the middle of a day bills that whole day by the new split
  • Fallback hops skip the share ceiling, as main's team TPM limits do
  • The /azure pass-through route skips the share ceiling, as on main
  • Only team rows report ptu_hours, and other usage rows show 0
  • A model with no Azure sizing row gets no ceiling and no PTU-hours
  • Daily team rows are keyed by model, so two groups on one model share a row
Medium caveats with workarounds and how main behaves
  • A small share cuts long uncapped replies: requests with no max_tokens get min(1,024, a quarter of the share in output tokens), 987 on 3 PTU of gpt-5.4-mini, and stop with finish_reason: length (design decision 5)
    • Main writes the same cap under any configured TPM limit below 4,096
    • A hand-set model_tpm_limit of the same 23,700 counts output once, stays above 4,096 and never gets the cap, so a team moving from that setup to ptu_shares loses those longer uncapped replies
    • Send max_tokens yourself to pick the cap; capped requests are untouched
  • A request whose max_tokens alone 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)
    • Lower max_tokens or give the team a bigger share
  • Moving a share in the middle of a day bills that whole day by the new split
    • The rollup reads the shares when it runs, the way it already reads the team and the price
  • Fallback hops are not checked against the share: a fallback from another group into a shared group skips the ceiling, and a fallback out of a shared group still charges the share
    • Main's per-model team TPM limits behave the same way, since the limiter runs once before routing
  • Calls through the /azure pass-through route skip the share ceiling, so a share holder can use more than its share there
    • Main's per-model TPM limits are skipped on that route the same way
  • Per-key, per-user, per-tag and per-deployment usage rows report ptu_hours: 0
    • Only team rows and breakdown.model_groups know their model group
  • Models missing an Azure sizing row get no ceiling or PTU-hours
    • Registration logs a warning naming the model
  • Daily team rows are keyed by model, not model group
    • The table's unique key predates this PR
    • A chat completions request by alias, deployment id or provider model lands under the group row too, while responses and messages requests keep the id or provider model they named
    • Two groups on one model merge into the first-written row
    • That row's PTU-hours are sized by the surviving group
    • A team reaching its reservation and an open route on the same model with one key reads the PTU-hours of whichever name was flushed first
    • A page spanning several or all teams merges every team into one row per name, so a share-less team's tokens on an open deployment under the shared name read as PTU-hours there; one team's page does not
    • One model group per underlying model keeps the figure exact

Low

30 low caveats, each left unfixed as net-negative to fix
  • Each team's row under breakdown.entities keeps ptu_hours at 0 on every page, so one team's PTU-hours come from a GET naming only that team
    • Filling it needs the per-model-group tokens under each team, which the entity breakdown does not keep
  • The share filter and the ceiling ignore ptu_effective_from and ptu_effective_to, so share holders keep the deployment and its ceiling outside those dates, while PTU-hours and the flat cost count only inside them
    • Azure keeps a provisioned deployment running after its reservation ends, billed by the hour, and main's team_id restriction ignores the dates the same way
  • PTU sizing matches the model name and not the provider, so a non-Azure deployment that declares ptu_shares gets Azure's ceiling and PTU-hours
    • Azure is also reached through openai/ with an Azure base URL, so a provider check would drop real reservations
  • /utils/token_counter on a shared group counts by the public model name, since it passes no request to the router, as on main
  • Streaming responses carry no PTU rate-limit headers, the same as the limiter's other rate-limit headers on main
  • The delete guards read the proxy's model list, so a share added on another proxy less than one model poll ago does not block a team delete yet
  • The SCIM group delete 400 uses the proxy's error shape, like the other SCIM errors there
  • The Admin UI has no ptu_shares editor yet
    • Set it through config.yaml or POST /model/new
  • A shared deployment still lists in GET /v1/models for share-less teams, and GET /health?model=<group> from such a team still probes it once
    • The refusal comes at request time as a 400; the health probe is the owner rule only, which the shares do not extend
  • A page spanning teams sizes a group mixing models, or a provider-model row, by its first reserved deployment
    • One team's page uses the deployment that team is served from, so the two pages can differ on such a row
  • PTU-hours are computed at read time from the shipped sizing table
    • A later release updating a model's row moves past days' figures
    • Stored tokens and the flat cost do not move
  • The Team Usage PTU Hours tile rounds to two decimals
    • GET /team/daily/activity carries the full value
  • ptu_shares has no cap on how many teams it names, and the team existence check looks them up in chunks under the database's IN list bound
  • A deployment one team already owns through team_id is split by deleting it and registering it again with ptu_shares and the same model_info.id, not by a PATCH, which refuses the mix with a 400 (design decision 16, documented)
  • With fail_closed_rate_limit_enforcement: true and Redis down, share-holding teams get a 503 on the shared deployment
  • ptu_shares in config.yaml is not checked against the team table, only POST /model/new and the PATCH are
    • A config share naming a team that does not exist boots and accrues that team's flat cost
  • The master key gets the 400 on a shared deployment (design decision 2)
    • Use a key in a holder team for smoke calls and the playground
  • A single-team reservation registered beside a shared registration of the same Azure deployment charges that team for both
    • Register each Azure reservation once
  • A share-less team whose group has fallbacks is served by the fallback group instead of getting the 400
  • A share-less team naming a name a shared wildcard matches gets the 400 even when an open * route also matches it
    • The router picks the most specific pattern and does not fall through to a broader one
  • A share-less team calling a shared deployment through the /azure pass-through gets a 500 instead of the 400, and nothing reaches Azure
    • Pre-existing: that route answers 500 for any name the router cannot serve, on main too
  • A refusal by deployment id names the provider model, and one by routing group calls the group a deployment
  • A provider-model request served by an open deployment in another group still counts against the team's share (design decision 17)
  • A ptu_shares map 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 exist
    • PATCH /model/{id}/update with ptu_count, cost_per_ptu_per_hour and ptu_effective_from completes it, or delete and re-register the deployment without the map
    • The database poll admits such a row without a log line, and a row registered with its terms and then stripped by a direct table write keeps the zero per-token prices POST /model/new wrote, so it bills nothing on either path until the PATCH
  • A PTU deployment registered through POST /model/new while 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 prices
    • Pre-existing for team_id reservations, now also the case for shared ones; turn the flag back on or re-register the deployment
  • A config.yaml entry declaring ptu_shares without ptu_count and cost_per_ptu_per_hour is 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 deployments
    • The same handling a malformed PTU entry already gets with the flag on; nothing in config.yaml stops the proxy from starting
  • POST /v1/messages without max_tokens is 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 200
    • Pre-existing and unchanged here; a 400 naming the field is tracked separately
  • osv-scan fails 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 check
  • The usage export carries no PTU-hours column
    • Main's export streams rows server-side with no summary object, so the column this PR had added was dropped in the second merge of main
    • The Team Usage page and GET /team/daily/activity carry the figure
  • The integration control test_concurrent_team_model_tpm_requests_reserve_tokens_before_reaching_the_provider went red once in the audit, with three concurrent requests all refused because each held one of the key and team limits
    • The reservation code is the same as main's, and its fix is tracked separately

Final 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

[!NOTE]
Medium Risk
Changes proxy routing, rate limiting, and team spend rollup for PTU reservations; behavior is mostly gated on cost attribution, but declared ptu_shares always affect who can call a deployment.

Overview
Adds model_info.ptu_shares so one Azure PTU deployment can split whole PTUs across teams (mutually exclusive with team_id, must sum to ptu_count), with validation on model create/update and blocks on team/org/SCIM delete while a share remains.

Routing & limits: Share holders are the only teams routed to shared deployments; the parallel limiter enforces a per-minute model_per_team_ptu ceiling in Azure normalized tokens (new sizing table in ptu_capacity.py), including pre-call reservation, post-call settlement, and a 400 when a request can never fit the share.

Cost & reporting: Daily PTU flat-cost rollup writes one transaction per deployment-day, splitting charges by share; team daily activity (and OpenAPI/UI metadata) gains ptu_hours computed at read time from token usage when attribution is enabled. LITELLM_ENABLE_PTU_COST_ATTRIBUTION can be read from the secret manager with a 60s cache.

Reviewed by Cursor Bugbot for commit cdce71e. Bugbot is set up for automated code reviews on this repo. Configure here.

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.
@devin-ai-integration

devin-ai-integration Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 2/5

[High impact] Splits Azure PTU deployments across teams with per-team ceilings and usage tracking.

Fix the PTU ceiling gaps and duplicate historical charges before merging, and bring the new tests into line with the unit-test guide.

Findings

  1. P1 Late refunds reopen capacity ▶
  2. P1 Reassigned shares duplicate old charges ▶
  3. P1 Fallback skips the PTU ceiling ▶
  4. P2 Tests skip the real query ▶
  5. P2 Tests read the real clock ▶

Summary

Adds ptu_shares to split an Azure reservation across teams, enforce per-team ceilings, divide flat cost, and show PTU-hours in team usage.

  • Teams can share one PTU deployment through whole-PTU allocations.
  • Each team’s PTU share sets its own Azure-weighted limit per minute.
  • Team usage reports PTU-hours alongside tokens and cost.

Reviews (27) · Last reviewed commit: "fix(proxy): accept whole-number PTU shar..." · Reviewed by Greptile

Comment thread litellm/router.py Resolved
Comment thread litellm/router_utils/ptu_shares.py Resolved
Comment thread litellm/llms/azure/ptu_capacity.py Resolved
Comment thread litellm/router.py Resolved
…r_team

# Conflicts:
#	tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_ptu_shares_per_team (cdce71e) with main (1f041a3)

Open in CodSpeed

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.81132% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...itellm/proxy/management_helpers/ptu_share_guard.py 92.30% 1 Missing ⚠️

📢 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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P1 Security Unescaped Team IDs in CSV litellm/proxy/management_endpoints/team_endpoints.py:6885 ▶

    A team can have a caller-supplied ID beginning with =, +, -, or @. The new CSV export escapes the team alias but writes the ID unchanged, so opening the export in a spreadsheet can evaluate that ID as a formula. Escape the Team ID field too.

    How this was verified: Team creation accepts caller-supplied IDs, and the CSV writer escapes the alias but not the exported ID.

            "Team ID": _csv_safe(row.team_id),
    
  • P2 Key Search Silently Omits Matches litellm/proxy/management_endpoints/team_endpoints.py:7093 ▶

    When more than USAGE_TOP_API_KEYS_LIMIT keys match a search, this query returns only the highest-spend matches. The same cap applies to user key search, but the UI does not indicate that either result is incomplete. Users therefore cannot find lower-spend matching keys, even though search is meant to reach beyond the initially loaded keys. Return truncation information or allow users to page through matches.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

…aw output tokens and escape the exported team id
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/router_utils/ptu_shares.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread litellm/router.py Resolved
Adds ptu_hours and total_ptu_hours to the daily activity integration goldens and fixtures, since every route now reports them
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri
mateo-berri dismissed their stale review October 15, 2026 17:00

Dismissing my own earlier approval so a second reviewer signs off on this PR before it merges

@mateo-berri

Copy link
Copy Markdown
Contributor

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at c106f93. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • high: 1725 changed source lines is over the 500 line cap (tests, docs, cookbook and markdown are not counted)

Judge: skipped, the rules alone decided.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 15, 2026
@mateo-berri
mateo-berri enabled auto-merge (squash) October 15, 2026 17:01
…r_team

# Conflicts:
#	litellm/proxy/management_endpoints/scim/scim_v2.py
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

Merged main at cdce71e, keeping both sides of one import conflict. The PR diff against main is unchanged, so QA and audit carry over

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit cdce71e. Configure here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit cdce71e. Configure here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@mateo-berri
mateo-berri merged commit e344dbd into main Oct 15, 2026
95 of 96 checks passed
@mateo-berri
mateo-berri deleted the litellm_ptu_shares_per_team branch October 15, 2026 18:44
devin-ai-integration Bot added a commit that referenced this pull request Oct 16, 2026
…43043

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…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>
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants