Repository navigation
fix(proxy): backport the LIT-145 spend tracking fixes to stable/1.104.x for v1.104.6 - #47718
Conversation
…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>
…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>
…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>
…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>
…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>
…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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
…_104_x # Conflicts: # uv.lock
|
bugbot run |
|
@litereview code-review |
Review not startedLiteReview only reviews open pull requests. |
|
@litereview code-review |
|
Devin is archived and cannot be woken up. Please unarchive Devin if you want to continue using it. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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.
| _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 |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 240d415. Configure here.
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. The PR description still says the line bumps to Checks and execution details
The Vertex batch I ran the affected unit tests locally at this head with
The PR's caveats are acknowledged but do not mark any spend value wrong:
Nothing here amounts to a supported defect. View review · Reviewed |
…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
Problem this solves:
How it solves it:
enterprise/changed. The aiohttp 3.14.4 lock bump now comes from the baseLinear ticket
Resolves LIT-145
Picks
stable/1.104.xat v1.104.5 (5275320), resolving the only conflict,uv.lockexclude-newer, to the base value (b465d97)Empty or dropped picks:
_tool_carries_ephemeral_markfrom fix(router): key prompt caching affinity on tools and the /v1/messages system prompt #46411, which only exists on mainAdaptations 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
SystemOneRequestFields(state,questions), added onlypydantic_core.to_jsonable_pythonandChatCompletionUserMessagelogging, not main-onlyaudio,videos,_SYSTEMONE_FIELDStimeout_by_service_tierandstream_timeout_by_service_tierthrough the line's timeout precedence; the picked timeout test file was created at a line-compatible path_get_service_tier_cost_key; droppedtests/integration/cost_calculation/cases/vertex_ai.py(the line has nocases/module)experimental_pass_through/messages/handler.py; kept the line's_CLAUDE_CODE_OBJECT_MAPPING_ADAPTERandvalidated_object_list; droppedtests/integration/providers/test_tool_config_cache_point_wire.py(integration._support.openai_wireis main-only)httpxto the line's import block; test landed intests/test_litellm/proxy/test_proxy_utils.pyLITELLM_LOGGING_NO_UPSTREAM_LLM_CALLconstantBaseModelas the Vertex embedding config base (noLiteLLMBaseModelon the line); smaller direct transformation testvertex_locationthrough the line's existing batch-cost functions; did not add main-onlylitellm/batches/batch_line_items.py; the picked test needed thebatch_cost_calculatorimport on the lineLITELLM_HTTP_STATUS_CLIENT_DISCONNECTEDaround the line's_failure_usage_to_lift_get_base_model_from_metadata(main:get_base_model_from_metadata)custom_pricing_forrename applied; picked test adapted fromresponse_cost_calculatorto the line's_response_cost_calculatoraudioandvideoskwargstest_attempts_already_summed_into_the_final_row_are_not_lifted_again(depends onLogging.carry_failed_attempt_usagefrom fix(responses): log and bill every round of non-stream MCP auto-execute #43667, main-only); the retry lift itself is complete_failure_snapshot_with_guardrails_recorded_after_itorlitellm.disable_end_user_cost_trackingon the line, solate_guardrails_snapshot=Noneandend_user_id=user_api_key_dict.end_user_id; test uses the line's_ProxyDBLoggersearch_free_requests;_str_keyed_fieldsdefined inline (nolitellm.llms.azure.ptu_capacityon the line); dropped the@with_service_targetdecorator insearch_free_tier.py(OTel span naming from fix(otel): nest cache spans under their operation and name service spans by purpose #44150, main-only);search_free_requestsadded toci_cd/generate_model_prices_schema.pyand the schema regenerated; tests use the line's_ProxyDBLoggerprovider_stores_the_conversationtolitellm/responses/main.py(the line never had the MCP first-roundbridged_first_turnblock); test file got only the_responses_routerhelperpartial_response_on_disconnectadded to the line's Responses, completion-bridge and router stream wrappers without main-only pending-logging andfollow_source_attributionhelpers; the Anthropic responses adapter (line pathexperimental_pass_through/, no safeguards) now returnsAnthropicResponsesSSEByteStreamover a_sse_framesgenerator that keeps the line's JSON SSE encoding;common_request_processing.pylogslitellm_call_iddirectly (nosanitize_for_logon the line); one picked test dropped its_await_pending_logging()teardown call_read_request_body; added only_parse_form_metadataand the multipart metadata hunk;test_pricing_field_strip.pytook the picked>=assertion_estimated_input_costwith main's_deployment_priced_input_cost/_priced_input_costversion;CostPerTokenimport dropped as nothing on the line uses it any more_async_success_enqueued,async_success_log_enqueuedandmark_async_success_log_enqueuedwithout main-onlyclaim_async_success_log; picked tests set the line's_defer_async_logging/_enqueue_deferred_logginglitellm/router_utils/deployment_pricing.pyis new on the line; only thedeployment_pricing_modelsimport was added to the line's router import blockRouter.log_retryimports the line's_get_base_model_from_litellm_call_metadata; coverage list and helper test got only the picked entriesspilled_over_ptu_for/custom_pricing_forsplit with the line's_hidden_paramsliteral and_get_base_model_from_metadata; picked test uses the line's_select_model_name_for_cost_calcand_response_cost_calculator_stamp_responses_usage_costcall (fixed inside the fix(proxy): bill partial Responses API streams when the client disconnects #47611 pick); importer scan over every changed module found no line file importing a dropped nameGates
uv sync --frozen --extra proxy --group dev --group proxy-dev --group ci); every pick-only red was fixed inside its pickstable/1.104.x: 4 intests/router_unit_tests/test_router_helper_utils.py, andtest_a_dispatched_failure_is_counted_off_the_event_loop, which only fails when run after themcigroup, pinned in pyproject), mlflow and diskcache have no fixed release (main carries the same diskcache)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 isasync_anthropic_sse_wrapperreturning 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 findingsScreenshots / 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 withlitellm_104_base, After is this PR's head (827cc15) on port 4200 withlitellm_104_tip. Both started withpython litellm/proxy/proxy_cli.py --config <cfg> --port <port> --use_v2_migration_resolverShared config (
slow-minihastimeout: 1so the essay request times out at the deployment,fast-miniis the same model without it):Before (5346a40)
After (827cc15)
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/v1/systemoneand/v1/decisionson a scripted decisions upstream, loggedmessagescaptured by a CustomLoggergeneric_cost_per_tokenfor the ticket's usage (816032 prompt, 9033 text, 14999 audio, 792000 video, 4559 completion) onvertex_ai/gemini-3.1-pro-previewclaude-sonnet-4-6with atool_configcache point, chat x2 then/v1/messages;openai/gpt-4.1with the same point/v1/messagesreads 12141, OpenAI returns 200timeout_by_service_tieron a scripted upstream that answers flex after 8 s/v1/responses, default tier 200 in 0.05 s,x-litellm-timeout: 2gives 408 at 2.1 sgpt-4.1withtimeout: 1.5,num_retries: 2, long promptcancel_on_disconnect,curl --max-time 1ongpt-4.1input_cost_per_token: 0.00001on the timed-out requestvertex_ai/text-embedding-005andvertex_ai/gemini-embedding-001, 43-char inputasia-northeast1vsglobal, two 7-token requests each,PROXY_BATCH_POLLING_INTERVAL=60apply_search_free_tier, three groundedvertex_ai/gemini-3.8-flashcallscost_breakdown.discount_amountis 0.0 on some rows (4 of 8 across the run) while main writes it on every row, see Caveatslitellm.decisions(input=b"\xff\xfe not utf-8")with a failure callback"__4gbm90IHV0Zi04", caller seesBadRequestError400x-ms-is-spilled-over: truefor a PTU deployment withbase_model: azure/gpt-4.1azure/gpt-4.1(this line requiresteam_idon PTU deployments, the source config did not set it)litellm_proxy/hop forwardingcache_control_injection_points/v1/messagesthrough the hop read 12141 cached tokens, the forwarded bodies carry the pointgpt-4o-minirequests with 4service postgresql restartin between,SPEND_LOG_QUEUE_POLL_INTERVAL=0.5curl --max-time 4on streamed chat,/v1/responsesand/v1/messagesongpt-5.5/v1/responsesturns on OpenAI then 10 on Anthropic,proxy_batch_write_at: 5model_info.base_modeland a custom-priced onex-litellm-model-id: base-model-pricedfour times, router logitem_cost: 2e-06vs0.0001base_modelon agpt-4osuccess and a streamed hang-up, lone surrogate in multipart metadatacafé-😀tag landslitellm:search_free_tier:gemini:gemini-3:2026-10 = 1,...vertex_ai:gemini-3:2026-10 = 3) and spend; samediscount_amountcaveat as #47494input_cost_per_token_above_200k_tokens: 5e-7,timeout: 0.5timeout-mini(gpt-5.4-mini) falling back tofallback-big(gpt-5.4),num_retries: 1eachbase_modelon a scripted Azure upstream that reports served modelgpt-5.4-nano-2026-03-17gpt-5.4-nano-2026-03-17, regular PTU row stays 0Integration and e2e suites on this line
tests/integration/run.pygroups 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 cleanorigin/stable/1.104.xcheckout: 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'stest_strands_decider_agentcore_wire.pyimports the main-onlyintegration._support.tlsand 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 branchtests/e2eagainst 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 ontest_spend_counter_reseed_e2e.pywaiting on a Redis read with no socket timeoutType
🆕 New Feature
🐛 Bug Fix
Caveats (if any)
spendis discounted on every row, but on this linemetadata.cost_breakdown.discount_amountis 0.0 andmetadata.cost_breakdown.total_coststays at the undiscounted amount on 4 of the 8 grounded rows in the replay, while main writes both on 7 of 7. The missing prerequisite is fix(logging): keep the async request's logging payload when the sync success thread runs late #47019 (keep the async request's logging payload when the sync success thread runs late), which 1.104.x does not have and which does not cherry-pick cleanly (24 conflict hunks inlitellm_logging.py). Budgets and the Redis counter are unaffectedgpt-4.1withcancel_on_disconnect) bills 0 on this branch and on main 0e24bbb alike while the same hang-up ongpt-5.5bills the prompt on both, so it is not a difference introduced by this backportLow
tests/test_litellm/proxy/test_proxy_utils.pytests are red on the line's tip before and after the picks (twoTestPrismaClientTokenAuthBehindThePoolcases need a generated prisma client,test_a_dispatched_failure_is_counted_off_the_event_loop), the line's ownLink 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 optionalsearch_free_requestsin the cost map plus opt-inapply_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_configcache breakpoints on tools; decisions/systemone request logging before validation; router lowest-cost routing honorsbase_model; clients cannot overridebase_modelfor 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.