Skip to content

fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.6 - #47718

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

yuneng-berri merged 30 commits into
stable/1.104.xfrom
litellm_backport_lit145_stable_1_104_x

Conversation

@klu-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • stable/1.104.x lacks the LIT-145 spend-tracking fixes that landed on main
  • failed, timed-out, cancelled and spilled-over requests priced wrong or not at all on this line

How it solves it:

  • cherry-picks the 26 source PRs below in main order, one commit each, source author and provenance kept
  • adapts each pick to what the line has, drops only main-only pieces, listed per pick below
  • bumps the stable patch version to 1.104.6 and litellm-enterprise to 0.1.71.post1, since enterprise/ changed. The aiohttp 3.14.4 lock bump now comes from the base

Linear ticket

Resolves LIT-145

Picks

Empty or dropped picks:

Adaptations per pick

Every conflict was resolved the way main has it, keeping the line's own code where the source hunk only touched main-only context

Gates

  • picked tests: the 34 changed test files, 6272 passed on this branch against 6155 on the line's tip, same venv (uv sync --frozen --extra proxy --group dev --group proxy-dev --group ci); every pick-only red was fixed inside its pick
  • After the v1.104.5 merge, the picked unit tests on 240d415 give 6284 passed and 5 failed. All 5 fail the same way on stable/1.104.x: 4 in tests/router_unit_tests/test_router_helper_utils.py, and test_a_dispatched_failure_is_counted_off_the_event_loop, which only fails when run after them
  • grype: aiohttp 3.14.3 -> 3.14.4 bumped lock-only (main is at 3.14.5); claude-agent-sdk stays (dev-only ci group, pinned in pyproject), mlflow and diskcache have no fixed release (main carries the same diskcache)
  • Gauntlet-mini: SURVIVED, 5/5 lenses, 0 confirmed, degraded mode (no Agent tool, lenses run by hand on the worktree against git merge-base origin/stable/1.104.x HEAD = 5346a40, diff at /tmp/gm-diff-stable_1_104_x.patch), reviewed 97bcc92, bump 827cc15. Lenses: (a) every changed module imports and F821/basedpyright undefined-name clean, (b) picked tests above, (c) the only signature change with callers outside the picks is async_anthropic_sse_wrapper returning an async-iterable object, its three callers return it unchanged and 395 adapter/SSE tests pass, (d) aiohttp 3.14.4 / yarl 1.25.1: 131 custom_httpx tests pass, (e) no finding left unverified. No rejected findings
  • live before/after leg on the line below (Screenshots / Proof of Fix)

Screenshots / Proof of Fix

Live leg on this line, real OpenAI, no mocks: two proxies from the line venv, each with its own Postgres 14 database. Base is origin/stable/1.104.x (5346a40) on port 4100 with litellm_104_base, After is this PR's head (827cc15) on port 4200 with litellm_104_tip. Both started with python litellm/proxy/proxy_cli.py --config <cfg> --port <port> --use_v2_migration_resolver

Shared config (slow-mini has timeout: 1 so the essay request times out at the deployment, fast-mini is the same model without it):

model_list:
  - model_name: slow-mini
    litellm_params:
      model: openai/gpt-5.4-mini
      api_key: os.environ/OPENAI_API_KEY
      timeout: 1
  - model_name: fast-mini
    litellm_params:
      model: openai/gpt-5.4-mini
      api_key: os.environ/OPENAI_API_KEY
router_settings:
  num_retries: 0
general_settings:
  master_key: sk-lit145
  database_url: os.environ/LIT145_DB_URL

Before (5346a40)

  1. Timed-out request, returns 408 after the 1s deployment timeout
  2. Normal request, returns 200
  3. Spend rows 10s later: the 408 row counted 38 prompt tokens but was charged 0, the ok row was priced
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:4100/v1/chat/completions -H 'Authorization: Bearer sk-lit145' -H 'Content-Type: application/json' -d '{"model":"slow-mini","user":"lit145-base-timeout","messages":[{"role":"user","content":"Write a 3000 word essay on the history of the printing press, with sections on Gutenberg, the spread through Europe, and its effect on literacy."}]}'
{"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out. - timeout value=1.0, time taken=1.15 seconds\n\nDeployment Info: request_timeout: None\ntimeout: 1.0\n\nLiteLLM: model group 'slow-mini' failed with the error above. No fallback was attempted.","
HTTP 408
$ curl -s http://localhost:4100/v1/chat/completions -H 'Authorization: Bearer sk-lit145' -H 'Content-Type: application/json' -d '{"model":"fast-mini","user":"lit145-base-ok","messages":[{"role":"user","content":"Say hi in three words."}]}'
{"content": "Hi there!", "usage": {"completion_tokens": 6, "prompt_tokens": 12, "total_tokens": 18, "completion_tokens_details": {"accepted_prediction_tokens": 0, "audio_tokens": 0, "reasoning_tokens": 0, "rejected_prediction_tokens": 0}, "prompt_tokens_details": {"audio_tokens": 0, "cached_tokens": 0}}}
HTTP 200

$ psql -d litellm_104_base -c "select end_user, status, prompt_tokens, completion_tokens, spend from \"LiteLLM_SpendLogs\" where end_user like 'lit145-%' order by \"startTime\""
      end_user       | status  | prompt_tokens | completion_tokens |  spend  
---------------------+---------+---------------+-------------------+---------
 lit145-base-timeout | failure |            38 |                 0 |       0
 lit145-base-ok      | success |            12 |                 6 | 3.6e-05
(2 rows)

After (827cc15)

  1. Same timed-out request, returns 408
  2. Same normal request, returns 200
  3. Spend rows 10s later: the 408 row is now priced at the input rate, 38 tokens -> 2.85e-05 (38 x $0.75/M, fix(proxy): price the estimated input tokens on a read-timed-out request's spend row #47435), the ok row prices the same way on both sides (12 prompt x $0.75/M + completion x $4.50/M: 6 tokens -> 3.6e-05 before, 8 tokens -> 4.5e-05 after)
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:4200/v1/chat/completions -H 'Authorization: Bearer sk-lit145' -H 'Content-Type: application/json' -d '{"model":"slow-mini","user":"lit145-tip-timeout","messages":[{"role":"user","content":"Write a 3000 word essay on the history of the printing press, with sections on Gutenberg, the spread through Europe, and its effect on literacy."}]}'
{"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out. - timeout value=1.0, time taken=1.2 seconds\n\nDeployment Info: request_timeout: None\ntimeout: 1.0\n\nLiteLLM: model group 'slow-mini' failed with the error above. No fallback was attempted.","t
HTTP 408
$ curl -s http://localhost:4200/v1/chat/completions -H 'Authorization: Bearer sk-lit145' -H 'Content-Type: application/json' -d '{"model":"fast-mini","user":"lit145-tip-ok","messages":[{"role":"user","content":"Say hi in three words."}]}'
{"content": "Hi there, friend.", "usage": {"completion_tokens": 8, "prompt_tokens": 12, "total_tokens": 20, "completion_tokens_details": {"accepted_prediction_tokens": 0, "audio_tokens": 0, "reasoning_tokens": 0, "rejected_prediction_tokens": 0}, "prompt_tokens_details": {"audio_tokens": 0, "cached_tokens": 0}}}
HTTP 200

$ psql -d litellm_104_tip -c "select end_user, status, prompt_tokens, completion_tokens, spend from \"LiteLLM_SpendLogs\" where end_user like 'lit145-%' order by \"startTime\""
      end_user      | status  | prompt_tokens | completion_tokens |  spend   
--------------------+---------+---------------+-------------------+----------
 lit145-tip-timeout | failure |            38 |                 0 | 2.85e-05
 lit145-tip-ok      | success |            12 |                 8 |  4.5e-05
(2 rows)

Source PR proof steps replayed on this branch

Every source PR's "Screenshots / Proof of Fix" section was replayed against a proxy started from this branch (python litellm/proxy/proxy_cli.py --config <cfg> --port 4200 --use_v2_migration_resolver, PostgreSQL 14, real OpenAI, Anthropic, Gemini and Vertex AI calls, scripted upstreams only where the source PR used one). "same" means the numbers match the source PR's After section

PR Leg replayed on this branch Result
#47183 /v1/systemone and /v1/decisions on a scripted decisions upstream, logged messages captured by a CustomLogger same: both logged payloads carry the full request including the question text
#47373 generic_cost_per_token for the ticket's usage (816032 prompt, 9033 text, 14999 audio, 792000 video, 4559 completion) on vertex_ai/gemini-3.1-pro-preview same: prompt 3.264128, completion 0.082062 (the source's cost-case module is main-only, so the SDK number was checked instead)
#47394 claude-sonnet-4-6 with a tool_config cache point, chat x2 then /v1/messages; openai/gpt-4.1 with the same point same: cache_creation 12141 then cache_read 12141, /v1/messages reads 12141, OpenAI returns 200
#47406 timeout_by_service_tier on a scripted upstream that answers flex after 8 s same: flex 200 after 8.4 s on chat and /v1/responses, default tier 200 in 0.05 s, x-litellm-timeout: 2 gives 408 at 2.1 s
#47435 gpt-4.1 with timeout: 1.5, num_retries: 2, long prompt same: 408, failure rows priced 26 x 2e-6 = 5.2e-05 (one row per attempt, attempted_retries 0, 1, 2)
#47436 cancel_on_disconnect, curl --max-time 1 on gpt-4.1 differs from the source After but identical to main 0e24bbb run side by side: the gpt-4.1 hang-up row has 26 prompt tokens and spend 0 on both, a gpt-5.5 hang-up bills 26 x 5e-6 on both
#47437 deployment input_cost_per_token: 0.00001 on the timed-out request same: 26 x 1e-5 = 0.00026
#47456 source proof is unit tests only its 3 tests pass on this branch
#47460 vertex_ai/text-embedding-005 and vertex_ai/gemini-embedding-001, 43-char input same: 35 billable chars x 2.5e-8 = 8.75e-07 and 9 tokens x 1.5e-7 = 1.35e-06
#47466 Vertex batch, regional asia-northeast1 vs global, two 7-token requests each, PROXY_BATCH_POLLING_INTERVAL=60 same: regional batch row 6.105e-05 = (14 x 7.5e-7 + 10 x 4.5e-6) x 1.1 uplift, global batch row 4.65e-05 = 14 x 7.5e-7 + 8 x 4.5e-6 flat
#47490, #47416 no proof section in the source PRs covered by the per-attempt rows of #47435 and #47648
#47494 apply_search_free_tier, three grounded vertex_ai/gemini-3.8-flash calls spend same (each row is original minus 0.014 per query), but cost_breakdown.discount_amount is 0.0 on some rows (4 of 8 across the run) while main writes it on every row, see Caveats
#47564 SDK litellm.decisions(input=b"\xff\xfe not utf-8") with a failure callback same: logged content "__4gbm90IHV0Zi04", caller sees BadRequestError 400
#47567 scripted Azure upstream answering x-ms-is-spilled-over: true for a PTU deployment with base_model: azure/gpt-4.1 same: 0.0006 billed, logged rates 2e-6 and 8e-6 under azure/gpt-4.1 (this line requires team_id on PTU deployments, the source config did not set it)
#47570 litellm_proxy/ hop forwarding cache_control_injection_points same: chat and /v1/messages through the hop read 12141 cached tokens, the forwarded bodies carry the point
#47571 60 gpt-4o-mini requests with 4 service postgresql restart in between, SPEND_LOG_QUEUE_POLL_INTERVAL=0.5 same: 60 of 60 spend rows land
#47611 curl --max-time 4 on streamed chat, /v1/responses and /v1/messages on gpt-5.5 same: three partial rows (acompletion 17/104 0.003205, aresponses 17/117 0.003595, anthropic_messages 17/451 0.013615) and the three "Billing partial" log lines
#47614 10 /v1/responses turns on OpenAI then 10 on Anthropic, proxy_batch_write_at: 5 same: 0 spend-log monitor wake-ups for the OpenAI turns, 10 for the Anthropic turns, all 20 rows land
#47617 cost-based routing between a deployment priced through model_info.base_model and a custom-priced one same: x-litellm-model-id: base-model-priced four times, router log item_cost: 2e-06 vs 0.0001
#47639 body base_model on a gpt-4o success and a streamed hang-up, lone surrogate in multipart metadata same: rows at gpt-4o rates (13 x 2.5e-6 + 3 x 1e-5 = 6.25e-05), surrogate rejected with 400 "Invalid form payload", café-😀 tag lands
#47646 Gemini API then Vertex AI grounded call on a fresh month same counters (litellm:search_free_tier:gemini:gemini-3:2026-10 = 1, ...vertex_ai:gemini-3:2026-10 = 3) and spend; same discount_amount caveat as #47494
#47647 1.35M-char prompt on a Gemini deployment with input_cost_per_token_above_200k_tokens: 5e-7, timeout: 0.5 same: failure rows 261663 x 5e-7 = 0.1308315, control success at the tiered rate
#47648 timeout-mini (gpt-5.4-mini) falling back to fallback-big (gpt-5.4), num_retries: 1 each same rows as the source After: dep-fb-big 7e-05, dep-mini 7e-05 (final row, last gpt-5.4 attempt), dep-mini 2.1e-05
#47652 upstream answering 499, and a hang-up while gpt-5.5 generates same: upstream 499 row keeps 13 prompt tokens at spend 0, the hang-up row bills 13 x 5e-6 = 6.5e-05 (the during_call guardrail leg needs the source author's local guardrail file and was not replayed)
#47655 spilled-over PTU request without base_model on a scripted Azure upstream that reports served model gpt-5.4-nano-2026-03-17 same: 13 x 2e-7 + 5 x 1.25e-6 = 8.85e-06 logged under gpt-5.4-nano-2026-03-17, regular PTU row stays 0

Integration and e2e suites on this line

tests/integration/run.py groups behind a local copy of .circleci/scripts/run_integration.sh (real proxy, PostgreSQL 14, Redis, scripted upstream), each failing id compared against the same run on a clean origin/stable/1.104.x checkout: cost 483 passed, sdk 5 passed, database 4 passed, mcp 236 passed with 1 failure that also fails on the baseline, accounting 101 passed with 17 failures all also failing on the baseline, management 69 passed with 13 failures all also failing on the baseline, providers 262 passed with 62 failures identical to the baseline (the group's test_strands_decider_agentcore_wire.py imports the main-only integration._support.tls and was skipped on both), extensions 47 passed with 129 failures and errors identical to the baseline plus one chaos test that passed on rerun. No integration failure is specific to this branch

tests/e2e against a proxy on this branch with real OpenAI, Anthropic and Gemini: router 32 passed (2 failures and 1 error need an Azure endpoint the rig did not have and a db-added model), llm_translation 255 passed (21 failures need Azure, Bedrock, Cohere or the realtime websocket rig), management 108 passed (18 errors need Keycloak), batches 70 passed (17 failures need an Azure endpoint, a GCS or S3 bucket and an AWS role the rig did not configure), access_control 19 passed, other 8 passed (10 errors need Keycloak, 2 session-token failures need the UI session rig), quota_management stopped on test_spend_counter_reseed_e2e.py waiting on a Redis read with no socket timeout

Type

🆕 New Feature
🐛 Bug Fix

Caveats (if any)

Low

Link to Devin session: https://app.devin.ai/sessions/ef4875ad3f844c6c8b8997e1500eaf91
Open in Devin Desktop: https://app.devin.ai/desktop/session/ef4875ad3f844c6c8b8997e1500eaf91?variant=devin
Requested by: @kerrylu-berri


Note

High Risk
Changes how the proxy computes and writes spend for failures, retries, disconnects, batches, and grounding allowances—directly affecting billing, budgets, and spend logs across critical paths.

Overview
This backport tightens proxy spend tracking and cost math so failed, cancelled, and partially streamed requests line up better with what providers actually bill.

Failure and disconnect billing: Read timeouts and proxy 499 disconnects can now get estimated prompt usage priced at deployment rates (including long-context tiers), with separate spend rows for earlier timed-out retry attempts. Logging avoids double-billing when async success already ran, and Azure PTU spillover uses pay-as-you-go rates instead of zeroed PTU entries.

Streaming and Responses: Client disconnects on Responses (and related Anthropic SSE paths) can bill partial output via incomplete events. Spend-log flushing is limited to chat-completions–bridged Responses turns that need DB history for previous_response_id.

Cost calculation fixes: Vertex batch jobs apply regional endpoint uplift via resolved vertex_location. Gemini/Vertex grounding gets optional search_free_requests in the cost map plus opt-in apply_search_free_tier (Redis-shared counters). Input costing respects modality fallbacks, per-character Vertex embeddings, and service-tier timeouts on passthrough routes.

Other: Anthropic tool_config cache breakpoints on tools; decisions/systemone request logging before validation; router lowest-cost routing honors base_model; clients cannot override base_model for spend; multipart metadata rejects lone UTF-16 surrogates.

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

klu-berri and others added 28 commits October 20, 2026 23:54
…one and /v1/decisions (#47183)

* fix(decisions): log every request field the caller sent on /v1/systemone and /v1/decisions

* fix(decisions): serialize the logged request with model_dump_json so no mutable dict is built

* refactor(decisions): drop the state-only messages pick in function_setup, prepare_call logs the request

* fix(decisions): return the single logged message so no mutable list type is annotated

* fix(decisions): log the caller's raw request fields before validation so a rejected request is still recorded

* fix(decisions): serialize the raw request fields with pydantic_core so question objects and mapping proxies log as JSON

* fix(decisions): log the caller request at the SDK entry so requests rejected before prepare_call are recorded too

* test(decisions): assert the exact BadRequestError for the rejected-questions case

---------

Backport of #47183 to stable/1.104.x
Cherry-picked from 53821f6 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat(router): let a deployment set a timeout per service_tier

Adds timeout_by_service_tier and stream_timeout_by_service_tier to a deployment's
litellm_params. A request whose service_tier matches a key uses that value in place
of the deployment's timeout or stream_timeout. A timeout the client sends still wins
and requests without a matching tier are unchanged

Co-authored-by: adc77 <amandogra2016@gmail.com>

* style(router): sort the request_timeout_resolver import

* fix(router): read the service tier maps without the untyped params get

* fix(router): look the service tier timeout up through a typed get

---------

Backport of #47406 to stable/1.104.x
Cherry-picked from 62ce515 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: adc77 <amandogra2016@gmail.com>
…d input rate when no modality rate exists (#47373)

* fix(cost): bill Gemini audio/image/video prompt tokens at the resolved input rate when no modality rate exists

Co-authored-by: shivam <shivam@berri.ai>

* style(cost): ruff format the modality cost calls

---------

Backport of #47373 to stable/1.104.x
Cherry-picked from 09e9193 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: shivam <shivam@berri.ai>
…1/messages (#47394)

* fix(anthropic): apply tool_config cache-control points on chat and /v1/messages

A cache_control_injection_points entry with location tool_config was spread into
the Anthropic request body on /v1/chat/completions, which Anthropic rejected with
400 Extra inputs are not permitted, and the native /v1/messages path dropped the
point silently. Both paths now put the point's control on the last tool Anthropic
caches and never forward the key.

Co-authored-by: Tan Nguyen <tan@pressingly.net>

* refactor(anthropic): validate tool_config inputs instead of casting them

Keeps the lint gates flat: the helper takes untyped tools and points and
narrows them with the existing object validators, the chat transform builds
the body with the marked tools instead of writing into optional_params, and
the handler reads a typed view of kwargs.

* fix(openai): keep tool_config cache points out of extra_body, add integration test

The cache hook hands a tool_config point on for the provider step, and for
providers that call through the OpenAI SDK every non-OpenAI param rides in
extra_body, so OpenAI answered 400 Unrecognized request argument supplied.
The new integration file drives a live proxy against scripted Anthropic,
Bedrock Converse and OpenAI upstreams for /v1/chat/completions and
/v1/messages.

* test(integration): cover tool_config cache points on bridged /v1/messages

Three new cases on /v1/messages for models without a native Anthropic
messages path: OpenAI through the Responses bridge and Gemini through the
chat bridge never see cache_control_injection_points in the body, and
Bedrock Nova through the chat bridge gets the cachePoint on toolConfig

---------

Backport of #47394 to stable/1.104.x
Cherry-picked from 93b79d2 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Tan Nguyen <tan@pressingly.net>
…est's spend row (#47435)

Backport of #47435 to stable/1.104.x
Cherry-picked from 7b76b2b (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…a proxy-only failure (#47456)

Backport of #47456 to stable/1.104.x
Cherry-picked from 3fa1587 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…leCharacterCount (#47460)

Vertex text embedding predict responses report metadata.billableCharacterCount, the
unit Google bills text-embedding-005 and text-multilingual-embedding-002 on. Carry it
into usage.prompt_tokens_details.character_count and, when the model carries
input_cost_per_character, bill that count instead of the token count so the prompt is
charged under one unit. Per-token embeddings (gemini-embedding-001) are unchanged.

Backport of #47460 to stable/1.104.x
Cherry-picked from d29200f (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…#47466)

* fix(batches): apply the Vertex regional endpoint uplift to batch cost

batch_cost_calculator takes vertex_location and multiplies by the model's
regional_endpoint_uplift_multiplier through get_vertex_regional_endpoint_uplift,
and every batch cost path (aretrieve_batch pricing, completed-batch logging,
native Vertex batch rows, the proxy batch cost poll and its per-line items)
resolves the deployment's location and passes it down

Co-authored-by: Mrun25 <165297479+Mrun25@users.noreply.github.com>

* test(logging): point the resolver tests at resolve_vertex_location_for_cost

---------

Backport of #47466 to stable/1.104.x
Cherry-picked from c6c303a (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Mrun25 <165297479+Mrun25@users.noreply.github.com>
…99) request's spend row (#47436)

* fix(proxy): price the estimated input tokens on a client-cancelled (499) request's spend row

* fix(proxy): read the provider handoff before the proxy-only error handler stamps it so a pre-handoff 499 is not priced

* fix(proxy): drop the pre-logging handoff read now that pre_call no longer stamps proxy-only failures

---------

Backport of #47436 to stable/1.104.x
Cherry-picked from 0e7c490 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ike the success path (#47437)

Backport of #47437 to stable/1.104.x
Cherry-picked from fb555b0 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…U spillover (#47567)

get_standard_logging_object_payload decided custom_pricing from
litellm_params alone, so on an Azure PTU spillover response
model_map_information kept the deployment's zeroed PTU entry while
response_cost already used the standard model rate. Reuse the billing
side LitellmLogging._custom_pricing_for so both read the same decision

Backport of #47567 to stable/1.104.x
Cherry-picked from 4222523 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s to the downstream proxy (#47570)

PR #47394 withheld cache_control_injection_points from the OpenAI SDK extra_body for
every provider on that path, which also covers litellm_proxy. The downstream LiteLLM
proxy applies the point itself, so litellm_proxy keeps forwarding it while OpenAI and the
other OpenAI-compatible providers still never receive it

Backport of #47570 to stable/1.104.x
Cherry-picked from 04e9ed4 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…validation and gets a 400 (#47564)

Backport of #47564 to stable/1.104.x
Cherry-picked from ce63f48 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…he failed request (#47490)

* feat(proxy): lift every earlier billed timed-out retry attempt onto the failed request

_billed_earlier_attempts reads the router's previous_models records, keeps the Timeout ones other than the final attempt (matched on deployment_id plus attempted_retries, since the count restarts after a fallback hop and the fallback handler re-logs the exhausting attempt) and prices each at the deployment that served it. post_call_failure_hook lifts the tuple as billed_failed_attempts; nothing writes it yet. previous_models joins the router-reserved metadata fields so a client-planted record never reaches it

* fix(proxy): price earlier timed-out attempts from the prompt estimate only

The final row may lift a mid-stream recovered usage (prompt plus delivered chunks) or a failed_attempts_usage sum; earlier attempts never produced output, so they are priced from _estimated_prompt_usage, and when failed_attempts_usage already bills them into the final row none is lifted again

---------

Backport of #47490 to stable/1.104.x
Cherry-picked from 7a4a255 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… prisma engine mid-write (#47571)

Backport of #47571 to stable/1.104.x
Cherry-picked from ccd0d4e (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…47416)

_failure_spend_rows yields the final row plus one re-keyed row per lifted billed_failed_attempts entry (<request_id>-attempt-<position>, the attempt's usage, cost, retry count and deployment id), each written through DBSpendUpdateWriter.update_database so it also deducts from key, team and user spend

Backport of #47416 to stable/1.104.x
Cherry-picked from ad8ca53 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…pend (#47494)

* feat(proxy): opt-in free-tier allowance for Google Search grounding spend

* fix(proxy): declare the search free tier counter's service target

* test(cost_map): allow search_free_requests in the cost map schema

* fix(proxy): skip cache hits and never free more than the billed cost in the search free tier

---------

Backport of #47494 to stable/1.104.x
Cherry-picked from e63aec0 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…idge reads back (#47614)

Every /v1/responses spend log asked its worker to flush the queue right away so a
chained previous_response_id could find the row. Only the chat-completions bridge
reads that row. Native Responses providers hold the conversation upstream, so their
rows now wait for the batch write like chat rows do

Backport of #47614 to stable/1.104.x
Cherry-picked from 423362b (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…nects (#47611)

* fix(proxy): bill partial Responses API streams when the client disconnects

Streamed /v1/responses requests and the default-route OpenAI and Azure /v1/messages requests behind them logged a 499 with zero spend when the client went away mid-stream, while /v1/chat/completions already billed the chunks it had sent. The Responses API iterator now keeps the response.created payload and can hand the disconnect cleanup a response.incomplete event with counted usage and the served service_tier, and the messages-route byte stream and router wrappers delegate to it.

* fix(proxy): satisfy lint gates for partial Responses API disconnect billing

Make the disconnect helper public so the proxy, router and messages adapter can import it without reportPrivateUsage, type the SSE byte stream as an AsyncGenerator so aclose is known, read litellm_call_id off the logging object, and keep the new tests on Final locals with the recorder injected through dynamic_async_success_callbacks instead of litellm.callbacks.

* fix(router): bill the primary stream's tokens after a mid-stream hop and chat-bridge Responses streams on disconnect

The router's fallback wrapper now folds the primary Responses stream's relayed tokens into the fallback's disconnect event the way _combine_responses_fallback_usage does for a natural end of stream, and LiteLLMCompletionStreamingIterator (chat-only providers served through /v1/responses) builds its disconnect event from the chat completion chunks it collected. stamp_responses_usage_cost is now public so the bridge module can price that event.

* Potential fix for pull request finding 'CodeQL / Log Injection'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

---------

Backport of #47611 to stable/1.104.x
Cherry-picked from f0ae445 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
…e surrogates in multipart metadata (#47639)

* fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata

* fix(proxy): type the parsed multipart metadata so basedpyright does not grow reportArgumentType

---------

Backport of #47639 to stable/1.104.x
Cherry-picked from 2a26895 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…xt tier like the success path (#47647)

Backport of #47647 to stable/1.104.x
Cherry-picked from 70ece35 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…der (#47646)

* fix(proxy): scope the search free-tier counter to the request's provider

* fix(proxy): read the provider with get so partial spend payloads still get the free tier

* test(proxy): give the grounded spend payload fixture its provider

---------

Backport of #47646 to stable/1.104.x
Cherry-picked from 640f2d8 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…, and never after the call already completed (#47652)

* fix(proxy): price a 499 spend row only for the proxy's own disconnect, and never after the call already completed

* fix(proxy): gate the zero-cost 499 row on the success log being enqueued, not merely claimed

---------

Backport of #47652 to stable/1.104.x
Cherry-picked from ffb7133 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…47617)

* fix(router): price cost-based routing through model_info.base_model

* fix(router): keep cost-based routing pricing helpers fully typed

* fix(router): drop typing.cast from cost-based routing pricing helpers

* fix(router): read the cost map through a typed accessor in cost-based routing

* fix(router): avoid a Final rebind inside the cost-based routing loop

* refactor(router): share deployment_pricing_models across spend, listing and cost-based routing

* refactor(router): keep the /v1/models listing key inline, share pricing models for spend and routing

* refactor(router): inline the deployment pricing-model wrapper in cost-based routing

* refactor(router): read deployment pricing models through one shared helper

deployment_pricing_models(deployment) now owns the model_info.base_model / litellm_params.base_model /
litellm_params.model unpacking, used by cost-based routing and the /v1/models listing. pricing_models(base_model, model)
stays for the failure-row spend estimate, which already holds the two names

* refactor(router): share the str-keyed mapping validator with cost-based routing

* ci: re-run after flaky test_aiohttp_transport read timeout in llms-providers

---------

Backport of #47617 to stable/1.104.x
Cherry-picked from 0c6731e (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…yment's model rate (#47648)

* fix(proxy): bill every earlier timed-out retry attempt at its own deployment's model rate

* fix(router): read the retry record's base_model through the typed metadata helper

* fix(router): keep the four-record retry breadcrumb cap

* fix(router): carry a deployment's litellm_params base_model on its retry record

* chore(router): place the cast-ok reason on the cast line and list the base_model helper as covered through log_retry

---------

Backport of #47648 to stable/1.104.x
Cherry-picked from 27efc38 (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…rved model's rates (#47655)

* fix(logging): report pay-as-you-go rates for spilled over PTU requests without base_model

* fix(logging): keep the provider response model so spilled over PTU payloads price the served model

* fix(logging): keep a provider_response_model the response already carries

* fix(logging): read the carried provider_response_model through a typed adapter

---------

Backport of #47655 to stable/1.104.x
Cherry-picked from 6b1f4ed (main)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@klu-berri
klu-berri requested a review from a team October 21, 2026 01:16
@devin-ai-integration

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.
1 out of 3 committers have signed the CLA.

✅ yuneng-berri
❌ devin-ai-integration[bot]
❌ klu-berri
You have signed the CLA already but the status is still pending? Let us recheck it.

@yuneng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@yuneng-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 21, 2026

Copy link
Copy Markdown

Review not started

LiteReview only reviews open pull requests.

@yuneng-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Devin is archived and cannot be woken up. Please unarchive Devin if you want to continue using it.

View session

@yuneng-berri yuneng-berri changed the title fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.5 fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.6 Oct 21, 2026
@yuneng-berri
yuneng-berri merged commit 01823bd into stable/1.104.x Oct 21, 2026
19 of 21 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_backport_lit145_stable_1_104_x branch October 21, 2026 06:04

@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 1 potential issue.

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 240d415. Configure here.

Comment thread litellm/proxy/utils.py
_base_model: Final = _get_base_model_from_metadata(model_call_details=_model_call_details)
_deployment_id: Final = _logging_obj.get_router_model_id() if isinstance(_logging_obj, Logging) else None
_success_already_logged: Final = isinstance(_logging_obj, Logging) and _logging_obj.async_success_log_enqueued
_billed: Final = provider_billed and not _success_already_logged

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.

Disconnect success billing skips 499 guard

Medium Severity

The 499 spend guard only looks at async_success_log_enqueued, which is set when @client schedules success logging. Partial stream billing goes through dispatch_success_handlers and never sets that flag, and this line dropped main's claim_async_success_log. A streamed hang-up that also surfaces as HTTPException 499 can therefore write a priced failure row after the partial success row has already billed the same request.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 240d415. Configure here.

@litereview

litereview Bot commented Oct 21, 2026

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The PR description still says the line bumps to 1.104.5, but the head commit (240d4157f8) bumps litellm to 1.104.6 and litellm-enterprise to 0.1.71.post1. 1.104.5 is already on PyPI, so the head version is the correct one. Only the description is stale.

Checks and execution details
  • Passed · Real testing evidence (required): The rule applies to three translation changes under litellm/llms/**. Each is covered by inspectable manual E2E evidence from a live proxy on this line (head 827cc15bfc). The later commits up to 240d4157f8 only merge in stable v1.104.5 Bedrock Mantle count-tokens work and bump versions. I confirmed this with the GitHub compare API: none of those commits touch the paths below.

  • Anthropic tool_config cache point (anthropic/chat/transformation.py, messages/handler.py, common_utils.tools_marked_for_a_tool_config_point): live claude-sonnet-4-6 with a tool_config point. Chat twice showed cache_creation 12141, then cache_read 12141. /v1/messages read 12141. openai/gpt-4.1 with the same point returned 200. The litellm_proxy hop (fix(litellm_proxy): forward tool_config cache_control_injection_points to the downstream proxy #47570) also read 12141.

  • Vertex embedding billableCharacterCount (vertex_embeddings/transformation.py): live vertex_ai/text-embedding-005 gave 35 billable chars × 2.5e-8 = 8.75e-07. gemini-embedding-001 stayed token-priced.

  • Anthropic Responses-adapter SSE stream with partial_response_on_disconnect (responses_adapters/streaming_iterator.py): curl --max-time 4 on /v1/messages against gpt-5.5 wrote a partial row (17/451 tokens, 0.013615).

The Vertex batch vertex_location threading is cost-side. It is backed by a live regional-vs-global batch replay with the 1.1 uplift.

I ran the affected unit tests locally at this head with .venv/bin/python -m pytest -n 8: 2002 passed across the Anthropic chat and messages handler, Vertex embeddings, responses, batch utils, search free tier, deployment pricing, lowest cost, pricing-field strip, track-cost callback, router timeout, cost-calc utils and http parsing.

  • Passed · Compatibility requirements (required): No supported behavior breaks.

  • timeout_by_service_tier / stream_timeout_by_service_tier: new optional fields. Absent means the old precedence.

  • Request-body base_model: now stripped in _strip_client_pricing_overrides unless the key or team sets allow_client_pricing_override. The proxy already stripped metadata.model_info, which carries the same base_model, under that same gate. Before this PR, a body-level base_model bypassed that existing restriction. After, both paths behave the same and the opt-in is unchanged. Requests still succeed.

  • previous_models: joins the router-reserved metadata strip. The router writes this field; a client-supplied value has no defined meaning.

  • Multipart metadata with a lone surrogate: now returns 400. Such a payload cannot be encoded to UTF-8 for the provider or the DB, and the JSON body path already returns 400 for it.

  • async_anthropic_sse_wrapper: now returns an async-iterable object. Its callers return it unchanged.

  • Version bump: 1.104.6 / enterprise 0.1.71.post1 is a patch bump.

  • Passed · Changed behavior and result consistency (required): I read the standards in root AGENTS.md/CONTRIBUTING.md, tests/AGENTS.md and tests/unit/AGENTS.md, then traced these paths:

  • Body base_model strip: from add_litellm_data_to_request (after the metadata string parse, at line ~2218) to _get_base_model_from_metadata in utils.py, which reads litellm_params.base_model first. Stripping the body field removes the client override. The opt-in test asserts the field survives when the key allows it.

  • tools_marked_for_a_tool_config_point: checked absent vs present control (defaults to ephemeral), a client-marked tool (left alone), tool-search tools (skipped) and no cacheable tools (no mark).

  • _parse_form_metadata: valid JSON returns unchanged. A surrogate raises ProxyException 400. Non-string metadata stays as sent.

  • Vertex embedding usage: absent billableCharacterCount gives prompt_tokens_details=None.

The PR's caveats are acknowledged but do not mark any spend value wrong:

Nothing here amounts to a supported defect.


View review · Reviewed 240d4157f84e

yuneng-berri added a commit that referenced this pull request 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

This branch was successfully deployed

No deployments
e2e-changed — 240d4157 Deployed Oct 21, 2026 by yuneng-berri via oauth #6017
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.

3 participants