Skip to content

fix(proxy): price the estimated input tokens on a timed-out or client-cancelled request's spend row - #47178

Closed
klu-berri wants to merge 19 commits into
mainfrom
litellm_lit145_timeout_input_cost
Closed

klu-berri wants to merge 19 commits into
mainfrom
litellm_lit145_timeout_input_cost

Conversation

@klu-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A request that times out at the provider is logged with spend 0
  • The provider accepted the prompt and bills for it, so spend undercounts
  • The row already carries estimated prompt_tokens, only the price was missing

How it solves it:

  • On a read timeout (litellm.Timeout caused by httpx.ReadTimeout), price the estimated prompt tokens at the model's input rate
  • Same for a client disconnect that cancelled the upstream call (cancel_on_disconnect: true, the 499 row), which today logs 0 tokens and $0
  • A connect timeout never reached the provider and stays at spend 0; other failures after dispatch keep spend 0 as before
  • The price honors the deployment's own input_cost_per_token from litellm_params (top level, or the router-stamped model_info under metadata / litellm_metadata) when set, like the success path; a model that cannot be priced keeps its row at spend 0 instead of dropping the row; the deployment's rate comes from deployment_pricing_model_info (the entry Router._create_deployment registers under the deployment's model_info.id, the same source the success path prices with), with the id read from the logging object's own litellm_params, never from the flattened model_call_details copy that a request body key can overwrite
  • completion_tokens stays 0, there is no response to count

Intentional 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

  1. The proxy admin sets timeout: 2 on gpt-4.1 and num_retries: 2 under router_settings
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "model": "gpt-4.1" and a short prompt, and the provider takes longer than 2 s
  3. They get HTTP 408 with litellm.Timeout: APITimeoutError - Request timed out after the retries
  4. https://litellm-domain/ui/?page=logs shows the request as a failure with prompt_tokens 17 and $0 spend

After: the same request shows the input cost the provider charged for the prompt

  1. The proxy admin sets timeout: 2 on gpt-4.1 and num_retries: 2 under router_settings
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "model": "gpt-4.1" and a short prompt, and the provider takes longer than 2 s
  3. They get HTTP 408 with litellm.Timeout: APITimeoutError - Request timed out after the retries
  4. https://litellm-domain/ui/?page=logs shows the request as a failure with prompt_tokens 17 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Real OpenAI, local proxy with Postgres. Config:

model_list:
  - model_name: gpt-4.1
    litellm_params:
      model: openai/gpt-4.1
      api_key: os.environ/OPENAI_API_KEY
      timeout: 1.5
router_settings:
  num_retries: 2
general_settings:
  master_key: sk-...

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):

curl -s -w '\nHTTP %{http_code} in %{time_total}s\n' http://127.0.0.1:4011/v1/chat/completions \
  -H 'Authorization: Bearer sk-...' -H 'Content-Type: application/json' \
  -d '{"model":"gpt-4.1","max_tokens":3000,"messages":[{"role":"user","content":"Write a 1500 word essay on the history of the Roman aqueducts."}]}'

Before (4bafebb)

  1. Run the curl above against the proxy on origin/main

    {"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out. - timeout value=1.5, time taken=1.52 seconds\n\nDeployment Info: request_timeout: None\ntimeout: 1.5\n\nLiteLLM: model group 'gpt-4.1' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"408"}}
    HTTP 408 in 9.647792s
    
  2. 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;"

    request_id        | ffaae762-4664-4bd2-ad47-d8ea58e6364b
    model             | openai/gpt-4.1
    spend             | 0
    prompt_tokens     | 24
    completion_tokens | 0
    status            | failure
    attempted_retries | 2
    error_class       | Timeout
    

After (ae22872; later commits only change where the deployment rate is read from and the lint gates, the rows below are unchanged)

  1. Run the same curl against the proxy on this branch

    {"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out. - timeout value=1.5, time taken=1.52 seconds\n\nDeployment Info: request_timeout: None\ntimeout: 1.5\n\nLiteLLM: model group 'gpt-4.1' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"408"}}
    HTTP 408 in 9.688996s
    
  2. Read the failure row with the same psql command. spend is 24 tokens x $0.000002 (the gpt-4.1 input_cost_per_token in the cost map) = 4.8e-05

    request_id        | 5c314270-c243-456e-b6de-1a870bff4c93
    model             | openai/gpt-4.1
    spend             | 4.8e-05
    prompt_tokens     | 24
    completion_tokens | 0
    status            | failure
    attempted_retries | 2
    error_class       | Timeout
    

Client disconnect with cancel_on_disconnect: true

Same model with timeout: 60 and general_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. Without cancel_on_disconnect the 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):

request_id        | 34481ab6-25c4-4158-93f9-b8530ac5a001
model             | openai/gpt-4.1
spend             | 0
prompt_tokens     | 0
completion_tokens | 0
status            | failure
error_class       | HTTPException
error_code        | 499

After (ae22872):

request_id        | 0f61e8b5-7e15-4c48-b5f2-e7777089b125
model             | openai/gpt-4.1
spend             | 4.8e-05
prompt_tokens     | 24
completion_tokens | 0
status            | failure
error_class       | HTTPException
error_code        | 499

Deployment rate from the deployment's own input_cost_per_token

Same timeout config with input_cost_per_token: 0.00001 and output_cost_per_token: 0.00004 on the gpt-4.1 entry, same curl.

Before (4bafebb), the row is $0:

request_id        | 72b13814-9aba-4999-9a2a-82a049126794
model             | openai/gpt-4.1
spend             | 0
prompt_tokens     | 24
completion_tokens | 0
status            | failure
attempted_retries | 2
error_class       | Timeout

After (ae22872), spend is 24 x 0.00001 from the deployment, not the cost map's 0.000002:

request_id        | 5f154190-3112-4c67-b41b-e6199d1f44a4
model             | openai/gpt-4.1
spend             | 0.00024
prompt_tokens     | 24
completion_tokens | 0
status            | failure
attempted_retries | 2
error_class       | Timeout

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Retries: this PR still writes one row priced for the final attempt's prompt (24 tokens here, while 3 provider calls were billed). Follow-up feat(proxy): write one spend row per billed timed-out retry attempt #47416 writes one spend row per billed timed-out attempt so the rows reconcile with the provider invoice
  • Nothing marks the row as an estimate yet, usage_object is still {}

Low

  • Only a read timeout and a cancelled client disconnect are priced; connect timeouts and other post-dispatch failures (provider 5xx, 429) keep spend 0 as before
  • A litellm.Timeout whose cause chain has no httpx.ReadTimeout (a provider SDK that does not go through httpx) is not priced
  • A model the cost map does not know, on a deployment that registered no pricing of its own under its model_info.id, keeps its failure row at spend 0 (the pricing error is logged at debug level, the row is not dropped)
  • Output tokens are unknowable without a response, so the row is a floor

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_hook classifies those cases via exception chain (httpx.ReadTimeout under litellm.Timeout, or status 499) and passes provider_billed into _failure_usage_to_lift / _failure_fields_to_lift, which compute cost through litellm.cost_per_token with deployment overrides from deployment_pricing_model_info and Azure-style base_model metadata. Connect timeouts, other post-dispatch errors, and unpriceable models still keep zero spend; client disconnect no longer skips estimation when LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL is set.

Also renames _deployment_model_info to public deployment_model_info and 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.

@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

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_lit145_timeout_input_cost (7c3d5a8) with main (1525e4b)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (b670031) during the generation of this report, so 1525e4b was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@devin-ai-integration devin-ai-integration Bot changed the title fix(proxy): price the estimated input tokens on a timed-out request's spend row fix(proxy): price the estimated input tokens on a timed-out or client-cancelled request's spend row Oct 17, 2026
@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at 7c3d5a8. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at 7c3d5a8. 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. Bugbot run requested, finished in 5 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/utils.py Resolved
Comment thread litellm/proxy/utils.py Resolved
@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 19, 2026
@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/utils.py Resolved
Comment thread litellm/proxy/utils.py Resolved
@veria-ai

veria-ai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The 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

Comment thread litellm/proxy/utils.py Resolved
Comment thread litellm/proxy/utils.py Resolved

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/utils.py Resolved

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/utils.py Resolved
@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/utils.py Resolved
Comment thread litellm/proxy/utils.py Resolved
…nd the deployment's base_model like the success path
@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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 7c3d5a8. Configure here.

Comment thread litellm/proxy/utils.py
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),

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.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7c3d5a8. Configure here.

Comment thread litellm/proxy/utils.py
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),

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.

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.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Closing, this was split and merged as #47435, #47436, #47437, #47456, #47490 and #47416, so nothing here is left to merge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants