Repository navigation
fix(proxy): price the estimated input tokens on a timed-out or client-cancelled request's spend row - #47178
fix(proxy): price the estimated input tokens on a timed-out or client-cancelled request's spend row#47178klu-berri wants to merge 19 commits into
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Cursor Bugbot: Medium Risk at Pushes do not re-run this check. Comment |
|
bugbot run |
|
@litellm-stampbot |
|
bugbot run |
PR overviewThe PR updates proxy spend accounting to price estimated input tokens for requests that time out or are cancelled by the client. Two issues have been addressed, but one billing-integrity issue remains open. An authenticated caller can select a cheaper base model in the request and disconnect after dispatch, causing provider-billed input to be undercharged when the deployment has no explicit pricing override. Open issues (1)
Fixed/addressed: 2 · PR risk: 6/10 |
…m_params, not the flattened model_call_details
…failure-row deployment rate
…_info like the success path
|
@litellm-stampbot |
|
bugbot run |
…ike the success path
|
@litellm-stampbot |
|
bugbot run |
…ed_deployment_id helper
|
@litellm-stampbot |
|
bugbot run |
…nd the deployment's base_model like the success path
|
@litellm-stampbot |
|
bugbot run |
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 7c3d5a8. Configure here.
| dispatched=_first_handoff is not None, | ||
| provider_billed=provider_billed, | ||
| deployment_id=_logging_obj.get_router_model_id() if isinstance(_logging_obj, Logging) else None, | ||
| base_model=get_base_model_from_metadata(model_call_details=_model_call_details), |
There was a problem hiding this comment.
Base model read from flattened details
Medium Severity
deployment_id now comes from the logging object's own litellm_params via get_router_model_id, but base_model is still taken from flattened model_call_details through get_base_model_from_metadata. A request-body litellm_params key can overwrite that copy, so an Azure (or other base_model-priced) timeout row can be charged at the wrong rate or $0. If the overwrite is not a mapping, get_base_model_from_metadata raises in _failure_fields_to_lift on every failure, not only billed ones, and the spend lift can drop.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 7c3d5a8. Configure here.
| dispatched=_first_handoff is not None, | ||
| provider_billed=provider_billed, | ||
| deployment_id=_logging_obj.get_router_model_id() if isinstance(_logging_obj, Logging) else None, | ||
| base_model=get_base_model_from_metadata(model_call_details=_model_call_details), |
There was a problem hiding this comment.
Medium: Caller-selected base model controls failure charges
An authenticated caller can send "base_model": "gpt-4o-mini" on a gpt-4.1 chat request and disconnect after dispatch to record provider-billed input at the cheaper model's rate when the deployment has no explicit pricing override: main.completion() preserves this request field, _strip_client_pricing_overrides() does not remove it, and this helper prefers it over the routed model. Resolve the billing base model from the selected deployment's configuration rather than the request-populated logging parameters.


TLDR
Problem this solves:
spend0prompt_tokens, only the price was missingHow it solves it:
litellm.Timeoutcaused byhttpx.ReadTimeout), price the estimated prompt tokens at the model's input ratecancel_on_disconnect: true, the 499 row), which today logs 0 tokens and $0spend0; other failures after dispatch keepspend0 as beforeinput_cost_per_tokenfromlitellm_params(top level, or the router-stampedmodel_infoundermetadata/litellm_metadata) when set, like the success path; a model that cannot be priced keeps its row atspend0 instead of dropping the row; the deployment's rate comes fromdeployment_pricing_model_info(the entryRouter._create_deploymentregisters under the deployment'smodel_info.id, the same source the success path prices with), with the id read from the logging object's ownlitellm_params, never from the flattenedmodel_call_detailscopy that a request body key can overwritecompletion_tokensstays 0, there is no response to countIntentional product change: a timed-out request now records its input cost in the spend log and deducts it from key, team and user budgets, where it recorded $0 before. Output tokens are still not counted, so the row is a floor, not the provider's invoice amount
User Flow
Before: a team reconciling LiteLLM spend against the provider invoice sees $0 for requests that timed out, while the provider charged for them
timeout: 2ongpt-4.1andnum_retries: 2underrouter_settings"model": "gpt-4.1"and a short prompt, and the provider takes longer than 2 slitellm.Timeout: APITimeoutError - Request timed outafter the retriesprompt_tokens17 and $0 spendAfter: the same request shows the input cost the provider charged for the prompt
timeout: 2ongpt-4.1andnum_retries: 2underrouter_settings"model": "gpt-4.1"and a short prompt, and the provider takes longer than 2 slitellm.Timeout: APITimeoutError - Request timed outafter the retriesprompt_tokens17 and $0.000034 spend (17 tokens at the gpt-4.1 input rate)Linear ticket
Resolves LIT-145
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreScreenshots / Proof of Fix
Real OpenAI, local proxy with Postgres. Config:
Request, same on both sides (the long answer makes gpt-4.1 run past 1.5 s, so all three attempts time out and the provider bills each prompt):
Before (4bafebb)
Run the curl above against the proxy on origin/main
Read the failure row:
psql "$DATABASE_URL" -x -c "select request_id, model, spend, prompt_tokens, completion_tokens, metadata->>'status' as status, metadata->'attempted_retries' as attempted_retries, metadata->'error_information'->>'error_class' as error_class from \"LiteLLM_SpendLogs\" order by \"startTime\" desc limit 1;"After (ae22872; later commits only change where the deployment rate is read from and the lint gates, the rows below are unchanged)
Run the same curl against the proxy on this branch
Read the failure row with the same psql command.
spendis 24 tokens x $0.000002 (the gpt-4.1input_cost_per_tokenin the cost map) = 4.8e-05Client disconnect with
cancel_on_disconnect: trueSame model with
timeout: 60andgeneral_settings.cancel_on_disconnect: true; the caller hangs up after 1 s (curl --max-time 1 ..., exit 28, no HTTP response), so the proxy cancels the upstream call and writes the 499 failure row. Withoutcancel_on_disconnectthe proxy waits for the provider and logs a normal success row with full cost, so nothing changes there.Before (observed at b501c23, this code path is unchanged from main for the 499 row):
After (ae22872):
Deployment rate from the deployment's own
input_cost_per_tokenSame timeout config with
input_cost_per_token: 0.00001andoutput_cost_per_token: 0.00004on thegpt-4.1entry, same curl.Before (4bafebb), the row is $0:
After (ae22872),
spendis 24 x 0.00001 from the deployment, not the cost map's 0.000002:Type
🐛 Bug Fix
Caveats (if any)
Medium
usage_objectis still{}Low
spend0 as beforelitellm.Timeoutwhose cause chain has nohttpx.ReadTimeout(a provider SDK that does not go through httpx) is not pricedmodel_info.id, keeps its failure row atspend0 (the pricing error is logged at debug level, the row is not dropped)Link to Devin session: https://app.devin.ai/sessions/5070f71a202048649b9467fc681744c4
Open in Devin Desktop: https://app.devin.ai/desktop/session/5070f71a202048649b9467fc681744c4?variant=devin
Requested by: @kerrylu-berri
Note
Medium Risk
Changes how failure rows affect spend logs and budget deduction for timeouts and disconnects; behavior is intentional but can shift reported spend versus provider invoices and prior $0 rows.
Overview
Failure spend rows for requests that reached the provider but failed with a read timeout or client disconnect (499) now record input-token spend at the same rates as successful calls, instead of always $0 while still logging estimated
prompt_tokens.post_call_failure_hookclassifies those cases via exception chain (httpx.ReadTimeoutunderlitellm.Timeout, or status 499) and passesprovider_billedinto_failure_usage_to_lift/_failure_fields_to_lift, which compute cost throughlitellm.cost_per_tokenwith deployment overrides fromdeployment_pricing_model_infoand Azure-stylebase_modelmetadata. Connect timeouts, other post-dispatch errors, and unpriceable models still keep zero spend; client disconnect no longer skips estimation whenLITELLM_LOGGING_NO_UPSTREAM_LLM_CALLis set.Also renames
_deployment_model_infoto publicdeployment_model_infoand expands unit tests for the new pricing matrix.Reviewed by Cursor Bugbot for commit 7c3d5a8. Bugbot is set up for automated code reviews on this repo. Configure here.