Skip to content

fix(batches)!: backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.6 - #47726

Merged
yuneng-berri merged 29 commits into
stable/1.104.xfrom
litellm_backport_p0_batch_translation_cost_stable_1_104_x
Oct 21, 2026
Merged

yuneng-berri merged 29 commits into
stable/1.104.xfrom
litellm_backport_p0_batch_translation_cost_stable_1_104_x

Conversation

@mrinal-berri

@mrinal-berri mrinal-berri commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Opened under the author's account (Devin was asked to open it; the author's GitHub link was active), so this PR needs a reviewer's approval.

Problem this solves:

  • P0 billing, batch-cost and translation fixes from main are missing on 1.104
  • 1.104 locks dependencies with known fixable CVEs

How it solves it:

  • Cherry-picks 13 merged fixes onto stable/1.104.x, adapted where the line drifted
  • Mirrors main's cost map byte-for-byte and matches main's dependency versions

Intentional product change: Azure gpt-6-astra now rejects reasoning_effort: none, gpt-5.3-codex rejects minimal, and custom- or zero-priced deployments bill catalog priority/flex rates on service_tier requests, all as main does.

User Flow

Before: on 1.104.4 several requests fail outright or are billed wrong

  1. POST /v1/messages with "safeguards": [...] to an Anthropic model returns 400 "safeguards: Extra inputs are not permitted"
  2. POST /v1/chat/completions on gpt-6.1-sol with "reasoning_effort": "none" returns 400 from OpenAI
  3. A claude-haiku-5-5 call returns no cost, so spend logs read $0
  4. A Bedrock inference-profile deployment with only a custom input price logs $0 output spend

After: the same requests succeed and are billed at the right rates

  1. The same POST /v1/messages returns 200; the proxy adds the dangerous-tool-use-2026-09-03 beta
  2. The same gpt-6.1-sol call returns 200 with the unsupported effort dropped
  3. The claude-haiku-5-5 call reports a real cost (8.2e-06 for a short reply)
  4. The Bedrock profile deployment bills output at the profile's catalog rate

Linear ticket

p0-regression: LIT-9498

Resolves LIT-9498 (#47155, #47184), LIT-9499 (#47190), LIT-9950 (#47625), LIT-9898 (#47419), LIT-9133 (#44460), LIT-9394 (#45659), LIT-9393 (#45686), LIT-8284 (#43955, #46102), LIT-9082 (#43935), LIT-9660 (#47182)

Picks

Each pick fixes a bug present on 1.104: at least one of its own added tests fails on the line tip 5346a40c37 and passes here.

Dropped:

Dependencies and cost map

  • aiohttp 3.14.3 -> 3.14.5 and claude-agent-sdk 0.1.44 -> 0.2.165 (pyproject pin), matching main's lock; neither is from the last 3 days; nothing else moved
  • Not fixable: mlflow 3.15.0 and diskcache 5.6.3 (no fixed release)
  • model_prices_and_context_window.json and the backup are byte-identical to main at 6083cf97769aeedb2719c5b5c901ded3106cc79e
  • Tests that broke only from the mirror are retargeted in a test-only commit; the schema generator and committed schema accept main's new keys in a separate commit
  • litellm 1.104.5 -> 1.104.6 (on top of v1.104.5); litellm-enterprise 0.1.71 -> 0.1.71.post1 (enterprise/ changed, 0.1.71 is on PyPI)
  • Merged stable/1.104.x after fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.6 #47718 landed (bd382af), keeping both PRs' changes in the 6 conflicted files. The cost maps stay byte-identical to main, which already has the 47 search_free_requests values fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.6 #47718 added. The auto-merge also left four duplicates, a ResponseIncompleteEvent import, a test import, and the search_free_requests key in both the schema generator and its test, and those were removed. generate_model_prices_schema.py --check passes and uv lock --check resolves

Screenshots / Proof of Fix

Live replay against real OpenAI and Anthropic, one proxy per tree, same config (/tmp/p0_live/config.yaml: claude-sonnet = anthropic/claude-sonnet-4-6, claude-haiku-5-5, gpt-6.1-sol, drop_params: true).

Before (5346a40)

Safeguards beta (#43955)

  1. POST /v1/messages {"model":"claude-sonnet","max_tokens":16,"safeguards":[{"type":"dangerous_tool_use"}],...}
  2. 400: AnthropicException - safeguards: Extra inputs are not permitted

gpt-6.1-sol reasoning effort none (#43935)

  1. POST /v1/chat/completions {"model":"gpt-6.1-sol","reasoning_effort":"none",...}
  2. 400: OpenAIException - Unsupported value: 'reasoning_effort' does not support 'none' with this model

claude-haiku-5-5 cost (#45151)

  1. POST /v1/chat/completions {"model":"claude-haiku-5-5",...}
  2. 200, x-litellm-response-cost header absent (model not priced)

Truncated Responses (#44460)

  1. POST /v1/responses {"model":"claude-sonnet","input":"Count from 1 to 200...","max_output_tokens":16}
  2. 200, status: incomplete, incomplete_details.reason: max_output_tokens, max_output_tokens: null (request param not echoed)

Databricks json_schema refs (#45659), integration

  1. pytest tests/integration/sdk/test_databricks_json_schema_refs_sdk.py
  2. 4 failed

After (810db37)

Safeguards beta (#43955)

  1. Same request
  2. 200, msg_... with text content

gpt-6.1-sol reasoning effort none (#43935)

  1. Same request
  2. 200, "content": "Hi!"

claude-haiku-5-5 cost (#45151)

  1. Same request
  2. 200, x-litellm-response-cost: 8.2e-06

Truncated Responses (#44460)

  1. Same request
  2. 200, status: incomplete, incomplete_details.reason: max_output_tokens, max_output_tokens: 16

Databricks json_schema refs (#45659), integration

  1. Same command
  2. 4 passed

Responses reasoning.effort gate on openai/responses (#43935), live against real OpenAI

Two proxies with one config, stable/1.104.x at 5275320 on :4011 and this PR at 7b0e159 on :4012. codex is openai/gpt-5.3-codex, codex-drop is the same with drop_params: true, mini-drop is openai/gpt-5-mini with drop_params: true

for P in 4011 4012; do for C in 'codex|minimal' 'codex-drop|minimal' 'mini-drop|none' 'codex-drop|low'; do
  curl -s localhost:$P/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
    -d "{\"model\":\"${C%%|*}\",\"input\":\"Say ok\",\"reasoning\":{\"effort\":\"${C##*|}\"},\"max_output_tokens\":64}" -w '\nHTTP %{http_code}\n'
done; done
request before (5275320) after (7b0e159)
codex, effort minimal 400 from OpenAI, "Unsupported value: 'minimal' is not supported with the 'gpt-5.3-codex' model" 400 raised locally, UnsupportedParamsError: reasoning.effort=minimal is not supported for gpt-5.3-codex, nothing sent upstream
codex-drop, effort minimal 400 from OpenAI, same message, drop_params has no effect 200, effort dropped
mini-drop, effort none 400 from OpenAI, "Unsupported value: 'none' is not supported with the 'gpt-5-mini' model" 404 from OpenAI, "Your organization must be verified to use the model gpt-5-mini". The effort was dropped and the request reached OpenAI, which refused it for an unrelated account reason
codex-drop, effort low 200 200, a supported level is forwarded unchanged

Everything else

  1. Every pick's own added and changed unit tests pass; every touched test file runs 4208 passed, with only 2 failures that fail identically on the line tip (local google.cloud.speech_v2 missing; AF_UNIX path length)
  2. Batch-cost picks (fix(batches): handle empty models when logging batch cost #47155, fix(batches): preserve spend across malformed output and metadata failures #47184, fix(batch): preserve recoverable costs and prevent poll starvation #47190, fix(batches): retry confirmed pre-accounting failures #47625), fix(databricks): send a single plain text block as a string for non-Claude models #45686 and fix(bedrock): resolve profile pricing before applying custom rates #47419 are proven by their unit tests plus the line-tip comparison above; no live batch jobs, Databricks or Bedrock credentials were used
  3. Adversarial review: SURVIVED. The batch (5 lenses on b8e89a8, under the version bumps at 810db37) found 0 line-only regressions, and the behavior changes it surfaced are listed under Caveats. The later merge of stable/1.104.x (c4b5c45, the PR head) was reviewed separately: SURVIVED, no conflict markers, no backport hunk dropped or duplicated, 996 tests passed. Its 12 failures are google.genai missing locally and fail identically at 810db37
  4. Review follow-up (aa960d6): the bundled beta map now lists dangerous-tool-use-2026-09-03 for azure_ai and databricks, matching main. Before, safeguards requests to those providers went upstream without the beta whenever the proxy used the bundled map (LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True, a failed remote fetch, or egress-blocked CI). Probe on head: update_headers_with_filtered_beta(..., provider) keeps the beta for azure_ai and databricks; the beta-header, azure_ai and databricks unit tests pass. test_worker_sigkill_mid_burst_leaves_the_sibling_sending_the_beta is skipped on this line because it needs OwnedProxy.replacing_worker, which this line's integration harness doesn't have

Breaking changes and migration

This patch matches main's behavior, so upgrading from 1.104.4 changes these results:

  • openrouter/* cost rows removed from the bundled map (refactor(cost-map): remove openrouter rows, part 1 of 5 #45665). With LITELLM_LOCAL_MODEL_COST_MAP=True, completion_cost(model="openrouter/...") raises ModelNotMappedError (it returned a cost on 1.104.4). Migration: add input_cost_per_token / output_cost_per_token to those deployments' model_info or litellm_params, or use the remote cost map
  • Custom- or zero-priced deployments bill catalog rates on service_tier=priority/flex (fix(router): bill service tiers at catalog rates for custom-priced deployments #43890). E.g. a $0 deployment bills about $0.0003 on a priority request. Migration: set the tier prices explicitly on the deployment (input_cost_per_token_priority, output_cost_per_token_priority, and the _flex variants)
  • Unsupported reasoning efforts are rejected locally (fix(openai): drop unsupported reasoning effort for gpt-6.1-sol #43935). Azure gpt-6-astra with reasoning_effort: none and gpt-5.3-codex with minimal raise UnsupportedParamsError (400). Migration: set drop_params: true to drop the param instead, or send a supported effort

Testing evidence gaps

These changes are covered by unit tests only, with no integration or live evidence:

  • Responses API reasoning.effort drop/reject gate on azure/responses and azure_ai/responses, and the Azure chat gate. The openai/responses gate now has a live run above. The Azure key in the test environment is rejected with 401, so the Azure paths were not run live
  • Bedrock Converse json_mode length finish_reason
  • Databricks single-text-block collapse and $defs preservation: the wire tests check outbound request bodies against scripted upstream replies, not real Databricks captures

Type

🐛 Bug Fix

Caveats (if any)

Severe

High

  • With the bundled map (LITELLM_LOCAL_MODEL_COST_MAP=True), 477 openrouter/* rows are gone, as on main (refactor(cost-map): remove openrouter rows, part 1 of 5 #45665)

    • openrouter/openai/gpt-4o cost: 0.0035 on 1.104.4, ModelNotMappedError here and on main
    • Default deployments fetch main's map at startup and already see this today
  • Without Redis, fix(batches): retry confirmed pre-accounting failures #47625's per-batch markers can evict router budget counters (same bug on main)

    • 250 batches added 52 to the budget instead of 250; an evicted batch can be charged twice
    • Follow-up fix needed on main, then carried to every line

Medium

Low

devin-ai-integration Bot and others added 25 commits October 20, 2026 15:30
…o request params (#44460)

Backport of #44460 to stable/1.104.x.
Cherry-picked from f81a3f5 (main).
…5659)

Backport of #45659 to stable/1.104.x.
Cherry-picked from fa7ad80 (main).
Test-file conflict resolved by keeping the line's file plus this PR's own additions.
…laude models (#45686)

Backport of #45686 to stable/1.104.x.
Cherry-picked from 1aee1a2 (main).
Test-file import conflict resolved by keeping the line's imports plus this PR's own.
…equest carries safeguards (#43955)

Backport of #43955 to stable/1.104.x.
Cherry-picked from eb5295b (main).
Adapted to the line: the transformation lives under anthropic/experimental_pass_through, the integration tests live under tests/integration/providers, and the CLI-beta wire assertion change is dropped since that test is not on the line.
Backport of #45108 to stable/1.104.x.
Cherry-picked from 5cd1126 (main).
Prerequisite for #45151: adds the claude-haiku-5-5 entries that fix corrects. Cost-map conflicts resolved by appending the new entries.
… capability flags (#45151)

Backport of #45151 to stable/1.104.x.
Cherry-picked from 46d440a (main).
Conflicts resolved by keeping the line's fields and adding only the over-100k fields this PR introduces; cost-map entries replaced per model.
…ages request carries safeguards (#46102)

Backport of #46102 to stable/1.104.x.
Cherry-picked from 5b042c0 (main).
Ported to the line's Rust messages layer for the anthropic provider only: a non-null safeguards field adds dangerous-tool-use-2026-09-03. Azure AI keeps its current headers since its beta-map cell is null on this line, and the other Rust providers and integration tests in the source are not on this line.
Backport of #47155 to stable/1.104.x.
Cherry-picked from 4143e08 (main).
…lures (#47184)

Backport of #47184 to stable/1.104.x.
Cherry-picked from 3fb95c8 (main).
Ported by hand onto the line's poller, whose surrounding code predates several main-only batch features: the claim now writes the terminal status and NUL-stripped file_object, a failed spend-log write restores both, and the managed-files postgres_storable_json sanitizer (from #45703 on main) is added to the line since this fix needs it.
Backport of #43738 to stable/1.104.x.
Cherry-picked from a3552c4 (main).
Prerequisite for #43935: adds the gpt-6.1-sol cost-map row that fix gates on. Appended to the line's cost map.
Backport of #43744 to stable/1.104.x.
Cherry-picked from bda2763 (main).
Prerequisite for #43935: adds the azure and openrouter gpt-6.1-sol cost-map rows that fix gates on. Appended to the line's cost map.
Backport of #43935 to stable/1.104.x.
Cherry-picked from d7620c7 (main).
Adapted to the line: the bridge check lives in litellm/main.py rather than litellm/responses/bridge_check.py, the effort helpers keep the line's private names, and the azure gpt-6.1-sol rows get supports_none_reasoning_effort=false (from #46377 on main) since this fix and its tests key on it. Test files keep the line's content plus this PR's own hunks.
…ormation (#47182)

Backport of #47182 to stable/1.104.x.
Cherry-picked from 1212260 (main).
Adapted to the line's private helper names (_select_model_name_for_cost_calc, _response_cost_calculator); the new test is appended to the line's test file.
…47190)

Backport of #47190 to stable/1.104.x.
Cherry-picked from 0ede0e1 (main).
Ported by hand onto the line's poller (the ManagedObjectRow protocol is the line's local _ManagedObjectRow; _finalize_unbilled_terminal_job keeps the line's None return). Test conflicts take this PR's assertions; the line-item poller tests from main are not on this line.
Minimal port of helpers from #41523/#43890/#46647 needed by #47419; behavior changes of those PRs not included.
Adds lookup_model_info_for_registration, model_info_with_pricing_overrides, runtime_model_cost_registrations (fields each register_model call set, tracked in a side table cleared on cost-map reload instead of on AliasedCostEntry), the flat-price variant helpers, Router._cost_map_backend_model, and Router._inherit_builtin_service_tier_pricing with the tier-suffixed threshold keys from #43890.
…47419)

Backport of #47419 to stable/1.104.x.
Cherry-picked from 3124797 (main).
Ported onto the line's register_model and router startup path without #41523's aliased-entry rewrite: registered fields come from the side table added in the previous commit. Tests adapted to the line: private names (_replay_model_cost_registrations, _response_cost_calculator), the custom-pricing test helpers from main's test_cost_calculator.py, CONVERSE_ANSWER inlined, and the alias-propagation and bedrock gpt-6.1-sol/ARN cases removed since those depend on #41523 and #46128, which are not on this line.
Backport of #38172 to stable/1.104.x.
Cherry-picked from 8327cd6 (main).
Prerequisite for #47625: RouterBudgetLimiting reads the provider from the logging payload, so the batch poller's aretrieve_batch events reach router budgets at all. Test file placed at tests/unit/router_strategy/ on this line.
Backport of #47625 to stable/1.104.x.
Cherry-picked from 6564a49 (main).
Ported by hand onto the line's spend and budget code: the charge-once helpers move from model_max_budget_limiter into router_utils.batch_utils as on main; RouterBudgetLimiting keeps the line's websocket skip and uses the line's duration_in_seconds window for the batch marker TTL; the write_started mark covers budget reservations only, since the search free-tier allowance (#47494) is not on this line. Tests adapted to the line's _ProxyDBLogger name; the search-allowance test is dropped for the same reason.
…oken_count_model.litellm_provider in the schema
@devin-ai-integration

devin-ai-integration Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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

@CLAassistant

CLAassistant commented Oct 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
5 out of 9 committers have signed the CLA.

✅ pOpO1-9
✅ daqiangganjun
✅ mrinal-berri
✅ joshua-berri
✅ yuneng-berri
❌ devin-ai-integration[bot]
❌ krrish-berri-2
❌ berriai-litellm-provider-info-sync[bot]
❌ klu-berri
You have signed the CLA already but the status is still pending? Let us recheck it.

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@cursor

cursor Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

This PR is too large for Bugbot to review. It changes 69,130 lines and 4,059,433 characters. Split the change into smaller pull requests to get a review.

@litereview

litereview Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

⚠️ code-review

Review incomplete

Scope: full · Full PR review.

Review incomplete.

The decisive blocker is still the open no-Redis batch-marker eviction defect (dfeb8f2a899449bfbfd6ad34b541632f:1). I reran it on this head and got the same wrong counter values.

The real-testing-evidence gate stays not_run because several changed translation paths under litellm/llms/** have only unit-test coverage, as the PR's own "Testing evidence gaps" section admits:

  • the Responses reasoning.effort gate
  • the Azure chat effort gate
  • Bedrock Converse json_mode finish_reason
  • the Databricks text-block collapse and $defs handling, whose wire tests use scripted replies with no stated provenance

No new correctness findings.

Couldn’t complete

  • Real testing evidence is missing for changed translation paths under litellm/llms/**: the Responses reasoning.effort drop/reject gate (openai/responses, azure/responses, azure_ai/responses), the Azure chat reasoning_effort gate (azure/chat/gpt_5_transformation.py), the Bedrock Converse json_mode length finish_reason change (converse_transformation.py), and the Databricks single-text-block collapse and $defs preservation. The Databricks wire tests (tests/integration/providers/test_databricks_chat_wire.py) use scripted replies with synthetic keys and no capture provenance. To clear the gate, add integration tests with provenance-documented fixtures or inspectable live E2E runs for each of these paths.
  • Real testing evidence: In scope: the PR changes translation in litellm/llms/{openai,azure,azure_ai}/responses/transformation.py, litellm/llms/{openai,azure}/chat/gpt_5_transformation.py, litellm/llms/bedrock/chat/converse_transformation.py, litellm/llms/databricks/chat/transformation.py, and the anthropic and openai_like messages transformations.

Covered: the PR description has live before/after replays through a real proxy against OpenAI and Anthropic for the safeguards beta on /v1/messages, the gpt-6.1-sol chat reasoning_effort: none drop, and truncated bridged Responses.

Not covered: the PR itself says these are unit-only: the Responses reasoning.effort gate, the Azure chat gate, and Bedrock json_mode length. The Databricks wire tests use scripted upstream replies (_API_KEY = "synthetic-databricks-key") with no documented capture provenance.

I ran the unit tests locally and they passed: budget limiter, gpt5, azure gpt5, databricks, converse, responses transformations, batch utils, and test_check_batch_cost.py (116 passed after prisma generate). Unit tests alone do not satisfy this rule.

Checks and execution details
  • Not run · Real testing evidence (required): In scope: the PR changes translation in litellm/llms/{openai,azure,azure_ai}/responses/transformation.py, litellm/llms/{openai,azure}/chat/gpt_5_transformation.py, litellm/llms/bedrock/chat/converse_transformation.py, litellm/llms/databricks/chat/transformation.py, and the anthropic and openai_like messages transformations.

Covered: the PR description has live before/after replays through a real proxy against OpenAI and Anthropic for the safeguards beta on /v1/messages, the gpt-6.1-sol chat reasoning_effort: none drop, and truncated bridged Responses.

Not covered: the PR itself says these are unit-only: the Responses reasoning.effort gate, the Azure chat gate, and Bedrock json_mode length. The Databricks wire tests use scripted upstream replies (_API_KEY = "synthetic-databricks-key") with no documented capture provenance.

I ran the unit tests locally and they passed: budget limiter, gpt5, azure gpt5, databricks, converse, responses transformations, batch utils, and test_check_batch_cost.py (116 passed after prisma generate). Unit tests alone do not satisfy this rule.

  • Passed · Compatibility requirements (required): The PR makes real compatibility breaks. With LITELLM_LOCAL_MODEL_COST_MAP=True, openrouter/* rows are gone, so completion_cost raises ModelNotMappedError (on 1.104.4 it returned a cost). Zero- or custom-priced deployments now bill catalog rates on service_tier=priority/flex. azure/gpt-6-astra with reasoning_effort=none and gpt-5.3-codex with minimal now raise UnsupportedParamsError unless drop_params is set.

The title fix(batches)!: ... carries the breaking marker. The description's "Breaking changes and migration" section gives the impact and a migration step for each break. Prior finding :3 stays fixed.

  • Passed · Changed behavior and result consistency (required): Standards read: root AGENTS.md, tests/AGENTS.md, tests/integration/AGENTS.md, tests/unit/AGENTS.md.

Path traced: RouterBudgetLimiting.async_log_success_event → _increment_spend_for_key → _claim_batch_charge, on the no-Redis path, which writes to DualCache.in_memory_cache (capped at 200 entries). Reproducer on this head: after 250 distinct batches at $0.25 the counter reads 12.75 (expected 62.5). Re-polling 5 early batches raises it to 14.0.

Also inspected: the Responses and chat reasoning-effort gates (refuses_reasoning_effort_level / row_disables_reasoning_effort_level, dict-effort handling, drop vs raise), the responses_api_bridge_check reasoning_active change, the Databricks single-text-block collapse (non-Claude only), and the Bedrock json_mode finish_reason guard (now only rewrites tool_calls).

Reconciled: the open defect stays in prior finding :1. The evidence gaps are in limitations and the real-testing-evidence check.

  • Passed · Targeted unit tests (optional): pytest tests/unit/router_strategy/test_budget_limiter.py tests/unit/llms/openai/test_gpt5_transformation.py tests/unit/llms/azure/chat/test_azure_gpt5_transformation.py tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py tests/unit/llms/bedrock/chat/test_converse_transformation.py tests/unit/llms/openai/responses/... tests/unit/llms/azure/response/... tests/unit/llms/azure_ai/responses/... tests/unit/batches/test_batch_utils.py: 449 passed.

test_check_batch_cost.py first failed 6 cases because the Prisma client had not been generated (environmental). After prisma generate --schema litellm/proxy/schema.prisma it gave 116 passed.


View review · Reviewed 7b0e1596281b


verbose_router_logger.debug("Incremented spend for %s by %s", spend_key, response_cost)

async def _claim_batch_charge(self, spend_key: str, batch_id: str, ttl_seconds: int) -> bool:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · Without Redis, batch charge markers evict provider budget spend so budgets undercount

  1. A single-instance proxy has a provider_budget_config for openai and no Redis, so RouterBudgetLimiting uses only the router's DualCache in-memory cache. That cache holds at most 200 entries (DEFAULT_MAX_SIZE_IN_MEMORY).
  2. In one budget window, the proxy finishes and polls more than 200 distinct batches.
  3. For each batch, _claim_batch_charge writes a new provider_spend:openai:1d:batch:<id> marker into that same bounded cache. Eviction removes entries with the earliest expiry, and those include the provider_spend:* counter itself.
  4. After 250 batches at $0.25 each, the provider counter reads $12.75 instead of $62.50, so the budget lets traffic through after the limit. Once an early batch's marker is evicted, the next poll of that batch charges it again ($12.75 → $14.00 after re-polling 5 early batches).

The PR caveat acknowledges this; that does not waive it. Smallest fix: keep the markers out of the bounded spend cache (for example, a dedicated set with TTL), or require Redis before deduplicating per batch.

Evidence

Reproducer (repo test helpers _success_kwargs and _completed_budget_batch): RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={'openai': {'budget_limit': 1000, 'time_period': '1d'}}), then 250 aretrieve_batch success events with distinct batch ids.

Output: spend after 250 distinct batches: 12.75, spend after re-polling 5 early batches: 14.0. Expected 62.5 and unchanged.

litellm/caching/in_memory_cache.py:28 DEFAULT_MAX_SIZE_IN_MEMORY: Final = 200; evict_cache pops the earliest-expiry keys once the cache is full.

Latest summary by code-review · View this review · Reviewed c4b5c45196c5

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged, not fixing in this backport. _claim_batch_charge on main has the same code (same no-Redis in_memory_cache marker path), so this is a main bug rather than a backport regression; it is listed under Caveats. It will be fixed on main first and then carried to the stable lines.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Finding still applies

Thanks for the context. The reply says main has the same code and that the issue is listed under Caveats. Neither point refutes the defect, and the backport still brings it to this line.

  1. This PR adds _claim_batch_charge to litellm/router_strategy/budget_limiter.py on stable/1.104.x, so 1.104.4 does not have this code path. Without Redis, the method writes one batch:<id> marker per budget key into dual_cache.in_memory_cache. That cache is capped at 200 entries (DEFAULT_MAX_SIZE_IN_MEMORY).
  2. When the cache fills, it evicts the entries that expire first. Those include the provider_spend:openai:1d counter.
  3. I reran the reproducer on the current head. After 250 distinct batch polls at $0.25 each, the counter read 12.75 instead of 62.5. Re-polling 5 early batches whose markers were evicted charged them again and raised it to 14.0.

A plan to fix this on main first is reasonable, but the defect remains in this PR as merged.

Evidence

Code at head: litellm/router_strategy/budget_limiter.py:614-623 handles the no-Redis case with self.dual_cache.in_memory_cache.async_increment(key=marker_key, ...). litellm/caching/in_memory_cache.py:28 sets DEFAULT_MAX_SIZE_IN_MEMORY: Final = 200, and DualCache defaults to InMemoryCache().

Diff: the _claim_batch_charge method and the batch_id threading into _increment_spend_for_key are new lines in this PR (@​@​ -596,6 +611,17 @​@​).

Reproducer run with .venv/bin/python at head aa960d620a: RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={'openai': {'budget_limit': 1000, 'time_period': '1d'}}), then 250 aretrieve_batch success events using the test helpers _success_kwargs and _completed_budget_batch from tests/unit/router_strategy/test_budget_limiter.py. Output: 12.75, then 14.0 after re-polling batch_0..batch_4. Expected: 62.5, with no change after the re-polls.

The PR description's Caveats (High) acknowledges this: "Without Redis, #47625's per-batch markers can evict router budget counters (same bug on main)".

Reviewed aa960d620a75 · View follow-up

held_by: Final = MappingProxyType({pid: _open_upstream_connections(pid, wire.url) for pid in workers})
assert sum(held_by.values()) == 20, held_by
victim_pid, survivor_pid = sorted(workers, key=held_by.__getitem__)
with owned.replacing_worker(victim_pid) as kill:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · New chaos test calls an OwnedProxy method that does not exist

  1. CI's providers integration group collects tests/integration/providers/test_anthropic_safeguards_beta_chaos.py.
  2. test_worker_sigkill_mid_burst_leaves_the_sibling_sending_the_beta calls owned.replacing_worker(victim_pid).
  3. OwnedProxy in tests/integration/_support/process.py defines only gateway, process and log, and nothing in this checkout defines replacing_worker.
  4. The test fails with AttributeError on every run. The worker-kill scenario it claims to cover never executes, and the providers shard goes red.

Smallest fix: port the replacing_worker helper this test was written against, or drop the test from this backport.

Evidence

grep -rn replacing_worker finds only the call site at line 234.

Local run: AttributeError: 'OwnedProxy' object has no attribute 'replacing_worker', then Owned proxy required forced cleanup.

Latest summary by code-review · View this review · Reviewed c4b5c45196c5

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed. OwnedProxy.replacing_worker needs the worker-pid readiness header and process helpers that this stable line's integration harness does not have, so porting it would mean backporting a large part of the harness. The test is now skipped on this line with that reason (commit aa960d6); the other tests in the file still run.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Finding withdrawn

Thanks for the fix. The finding said this test would fail with AttributeError every time it ran and turn the providers shard red. On head aa960d6, the test has @​pytest.mark.skip with a clear reason, so pytest never runs the body that calls owned.replacing_worker. When I ran it locally, it reported as skipped instead of erroring. The other tests in the file still collect. Skipping the test matches the second fix the finding offered ("drop the test from this backport"). One gap remains: this line has no test for the worker-SIGKILL scenario. That is a known coverage gap, and it no longer breaks CI.

Evidence

tests/integration/providers/test_anthropic_safeguards_beta_chaos.py:203: @​pytest.mark.skip(reason="Needs OwnedProxy.replacing_worker, which this stable line's integration harness does not have")

grep -rn replacing_worker finds only the skip reason (line 203) and the call inside the skipped test body (line 235).

Local run from tests/: SKIPPED [1] integration/providers/test_anthropic_safeguards_beta_chaos.py:203: Needs OwnedProxy.replacing_worker ..., 1 skipped in 1.26s.

--collect-only collects 4 tests: aborted streams, slow streams, worker SIGKILL (skipped), and cold-worker beta map fetch.

GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.

Reviewed aa960d620a75 · View follow-up

…p worker-kill chaos test

The bundled beta map stripped dangerous-tool-use-2026-09-03 for providers
main supports it on, so safeguards requests went upstream without the beta
whenever the proxy used the bundled map. The worker-SIGKILL chaos test needs
OwnedProxy.replacing_worker, which this line's integration harness lacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mrinal-berri mrinal-berri changed the title fix(batches): backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.5 fix(batches)!: backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.5 Oct 21, 2026
@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

Replies to the review-summary findings (the inline ones are answered in their threads):

Bundled beta map strips dangerous-tool-use-2026-09-03. Fixed in aa960d6: the bundled anthropic_beta_headers_config.json now lists it for azure_ai and databricks, matching main. With LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True, update_headers_with_filtered_beta now keeps the beta for azure_ai and databricks. The beta-header, azure_ai and databricks unit tests pass.

Breaking-change marker. Title is now fix(batches)!:, and the description has a "Breaking changes and migration" section with one migration step each for the removed openrouter/* rows, catalog tier billing on zero-priced deployments, and the reasoning-effort 400s.

Real testing evidence. Ran the same SDK script from the line tip (5275320) and this head (aa960d6) against real Azure AI Foundry, Bedrock, Databricks and OpenAI:

Check Line tip PR head
Foundry azure/gpt-6-astra, reasoning_effort=none local UnsupportedParamsError local UnsupportedParamsError with drop_params hint
Bedrock Converse claude-haiku-4-5, json_object, max_tokens=5 finish_reason=length finish_reason=length
Databricks claude-sonnet-4-6, strict json_schema with $defs/$ref 200, valid object 200, valid object
OpenAI Responses gpt-5.3-codex, reasoning.effort=minimal 400 from OpenAI local UnsupportedParamsError, no upstream call

No regression on any live path. Not covered live: the /v1/messages safeguards beta for Foundry and Databricks; the remaining unit-only paths are listed under "Testing evidence gaps".

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@yuneng-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@yuneng-berri yuneng-berri changed the title fix(batches)!: backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.5 fix(batches)!: backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.6 Oct 21, 2026
…ion_cost_stable_1_104_x

# Conflicts:
#	litellm/model_prices_and_context_window_backup.json
#	litellm/proxy/hooks/proxy_track_cost_callback.py
#	litellm/responses/litellm_completion_transformation/streaming_iterator.py
#	model_prices_and_context_window.json
#	tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py
#	tests/unit/test_utils.py
@yuneng-berri
yuneng-berri merged commit b2e44bf into stable/1.104.x Oct 21, 2026
12 of 13 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_backport_p0_batch_translation_cost_stable_1_104_x branch October 21, 2026 06:32

This branch was successfully deployed

No deployments
e2e-changed — bd382afc Deployed Oct 21, 2026 by yuneng-berri via oauth #6019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants