Repository navigation
fix(batches)!: backport P0 batch-cost, pricing and translation fixes to stable/1.104.x for v1.104.6 - #47726
Conversation
…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.
…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.
…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 #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.
…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 #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
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
…ion_cost_stable_1_104_x
|
@litereview code-review |
|
bugbot run |
|
@greptileai review |
|
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. |
|
|
|
||
| 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: |
There was a problem hiding this comment.
Medium · Without Redis, batch charge markers evict provider budget spend so budgets undercount
- A single-instance proxy has a
provider_budget_configforopenaiand no Redis, soRouterBudgetLimitinguses only the router'sDualCachein-memory cache. That cache holds at most 200 entries (DEFAULT_MAX_SIZE_IN_MEMORY). - In one budget window, the proxy finishes and polls more than 200 distinct batches.
- For each batch,
_claim_batch_chargewrites a newprovider_spend:openai:1d:batch:<id>marker into that same bounded cache. Eviction removes entries with the earliest expiry, and those include theprovider_spend:*counter itself. - 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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
- This PR adds
_claim_batch_chargetolitellm/router_strategy/budget_limiter.pyonstable/1.104.x, so 1.104.4 does not have this code path. Without Redis, the method writes onebatch:<id>marker per budget key intodual_cache.in_memory_cache. That cache is capped at 200 entries (DEFAULT_MAX_SIZE_IN_MEMORY). - When the cache fills, it evicts the entries that expire first. Those include the
provider_spend:openai:1dcounter. - 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: |
There was a problem hiding this comment.
Medium · New chaos test calls an OwnedProxy method that does not exist
- CI's
providersintegration group collectstests/integration/providers/test_anthropic_safeguards_beta_chaos.py. test_worker_sigkill_mid_burst_leaves_the_sibling_sending_the_betacallsowned.replacing_worker(victim_pid).OwnedProxyintests/integration/_support/process.pydefines onlygateway,processandlog, and nothing in this checkout definesreplacing_worker.- The test fails with
AttributeErroron 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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>
|
@litereview code-review |
|
Replies to the review-summary findings (the inline ones are answered in their threads): Bundled beta map strips Breaking-change marker. Title is now 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:
No regression on any live path. Not covered live: the |
|
@litereview code-review |
|
@litereview code-review |
…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
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:
How it solves it:
Intentional product change: Azure gpt-6-astra now rejects
reasoning_effort: none, gpt-5.3-codex rejectsminimal, and custom- or zero-priced deployments bill catalog priority/flex rates onservice_tierrequests, all as main does.User Flow
Before: on 1.104.4 several requests fail outright or are billed wrong
"safeguards": [...]to an Anthropic model returns 400 "safeguards: Extra inputs are not permitted""reasoning_effort": "none"returns 400 from OpenAIAfter: the same requests succeed and are billed at the right rates
dangerous-tool-use-2026-09-03betaLinear 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
5346a40c37and passes here.incompleteand echo request params#/$defsrefs in json_schemapostgres_storable_jsonfrom fix(responses): bill a background response once, on the first read or poll that sees it finished #45703)model_map_informationreports the entry billing usedDropped:
Dependencies and cost map
model_prices_and_context_window.jsonand the backup are byte-identical to main at6083cf97769aeedb2719c5b5c901ded3106cc79estable/1.104.xafter 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 47search_free_requestsvalues 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, aResponseIncompleteEventimport, a test import, and thesearch_free_requestskey in both the schema generator and its test, and those were removed.generate_model_prices_schema.py --checkpasses anduv lock --checkresolvesScreenshots / 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)
POST /v1/messages {"model":"claude-sonnet","max_tokens":16,"safeguards":[{"type":"dangerous_tool_use"}],...}AnthropicException - safeguards: Extra inputs are not permittedgpt-6.1-sol reasoning effort none (#43935)
POST /v1/chat/completions {"model":"gpt-6.1-sol","reasoning_effort":"none",...}OpenAIException - Unsupported value: 'reasoning_effort' does not support 'none' with this modelclaude-haiku-5-5 cost (#45151)
POST /v1/chat/completions {"model":"claude-haiku-5-5",...}x-litellm-response-costheader absent (model not priced)Truncated Responses (#44460)
POST /v1/responses {"model":"claude-sonnet","input":"Count from 1 to 200...","max_output_tokens":16}status: incomplete,incomplete_details.reason: max_output_tokens,max_output_tokens: null(request param not echoed)Databricks json_schema refs (#45659), integration
pytest tests/integration/sdk/test_databricks_json_schema_refs_sdk.pyAfter (810db37)
Safeguards beta (#43955)
msg_...with text contentgpt-6.1-sol reasoning effort none (#43935)
"content": "Hi!"claude-haiku-5-5 cost (#45151)
x-litellm-response-cost: 8.2e-06Truncated Responses (#44460)
status: incomplete,incomplete_details.reason: max_output_tokens,max_output_tokens: 16Databricks json_schema refs (#45659), integration
Responses
reasoning.effortgate onopenai/responses(#43935), live against real OpenAITwo proxies with one config,
stable/1.104.xat 5275320 on :4011 and this PR at 7b0e159 on :4012.codexisopenai/gpt-5.3-codex,codex-dropis the same withdrop_params: true,mini-dropisopenai/gpt-5-miniwithdrop_params: truecodex, effortminimalUnsupportedParamsError: reasoning.effort=minimal is not supported for gpt-5.3-codex, nothing sent upstreamcodex-drop, effortminimaldrop_paramshas no effectmini-drop, effortnonegpt-5-mini". The effort was dropped and the request reached OpenAI, which refused it for an unrelated account reasoncodex-drop, effortlowEverything else
google.cloud.speech_v2missing; AF_UNIX path length)google.genaimissing locally and fail identically at 810db37dangerous-tool-use-2026-09-03forazure_aianddatabricks, 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 forazure_aianddatabricks; the beta-header, azure_ai and databricks unit tests pass.test_worker_sigkill_mid_burst_leaves_the_sibling_sending_the_betais skipped on this line because it needsOwnedProxy.replacing_worker, which this line's integration harness doesn't haveBreaking 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). WithLITELLM_LOCAL_MODEL_COST_MAP=True,completion_cost(model="openrouter/...")raisesModelNotMappedError(it returned a cost on 1.104.4). Migration: addinput_cost_per_token/output_cost_per_tokento those deployments'model_infoorlitellm_params, or use the remote cost mapservice_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_flexvariants)gpt-6-astrawithreasoning_effort: noneandgpt-5.3-codexwithminimalraiseUnsupportedParamsError(400). Migration: setdrop_params: trueto drop the param instead, or send a supported effortTesting evidence gaps
These changes are covered by unit tests only, with no integration or live evidence:
reasoning.effortdrop/reject gate onazure/responsesandazure_ai/responses, and the Azure chat gate. Theopenai/responsesgate now has a live run above. The Azure key in the test environment is rejected with 401, so the Azure paths were not run livelengthfinish_reason$defspreservation: the wire tests check outbound request bodies against scripted upstream replies, not real Databricks capturesType
🐛 Bug Fix
Caveats (if any)
Severe
service_tierrequests on custom- or zero-priced deployments now bill catalog tier rates (from fix(router): bill service tiers at catalog rates for custom-priced deployments #43890, matches main)reasoning_effort: none; gpt-5.3-codex rejectsminimal(fix(openai): drop unsupported reasoning effort for gpt-6.1-sol #43935, matches main)High
With the bundled map (
LITELLM_LOCAL_MODEL_COST_MAP=True), 477openrouter/*rows are gone, as on main (refactor(cost-map): remove openrouter rows, part 1 of 5 #45665)openrouter/openai/gpt-4ocost: 0.0035 on 1.104.4,ModelNotMappedErrorhere and on mainWithout Redis, fix(batches): retry confirmed pre-accounting failures #47625's per-batch markers can evict router budget counters (same bug on main)
Medium
Bundled-map changes from the mirror: 11 github_copilot rows removed, azure/gpt-4o-mini family repriced, 19 azure region codex/pro rows move from
chattoresponsesmode7 providers in main's map are not on this line, so the provider-registration test exempts them (they cannot be routed here)
Provider budgets now count embeddings and other API surfaces (fix(router): count provider budget spend on every API surface #38172)
Azure EU gpt-6-astra price corrected to match the other gpt-6-astra rows (cost map mirror)
register_modelcustom rates now also apply to region-prefixed Bedrock profiles (fix(bedrock): resolve profile pricing before applying custom rates #47419)Cross-region profile ARNs still bill the base row; needs fix(bedrock): bill the regional row for inference-profile ARNs that embed a cross-region prefix #46128, not on this line
Low
router.completionnot counted toward provider budgets; Router with a provider budget built outside an event loop raises