Skip to content

fix(proxy): attribute retry attempt spend rows to their deployment and keep them out of daily request counts - #47658

Merged
klu-berri merged 11 commits into
mainfrom
litellm_attempt_rows_deployment_and_counts
Oct 20, 2026
Merged

klu-berri merged 11 commits into
mainfrom
litellm_attempt_rows_deployment_and_counts

Conversation

@klu-berri

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

Copy link
Copy Markdown
Contributor

A timed-out request that the router retried writes one spend row per billed attempt since #47416. Those attempt rows copied the final row's model, provider and api_base even when the attempt ran on a different deployment, and every attempt row also counted as one more request in the daily spend tables, so one caller request with two earlier attempts showed up as three failed requests. Each attempt row now names the deployment it actually ran on, and the daily tables keep its spend and tokens while counting only the caller's one request

Details

TLDR

Problem this solves:

  • Attempt rows carried the final row's model, provider and api_base
  • One failed request with N earlier attempts counted N+1 daily requests

How it solves it:

  • Attempt rows look up their deployment by model_info.id through the proxy router
  • They carry that deployment's model, provider, configured api_base and model group
  • Attempt rows carry a billed_retry_attempt metadata flag, which the proxy strips from caller metadata on the way in
  • Daily spend keeps their spend, tokens and model usage, counts zero requests and zero request errors for them

User Flow

Before: an operator reading spend logs after a retried timeout sees a row that names the wrong deployment, and the daily request count triples

  1. They send POST http://localhost:4000/v1/chat/completions with "model": "essay", where essay times out and falls back to essay-fallback (OpenAI gpt-4.1)
  2. They get HTTP 408 after the retries and the fallback are exhausted
  3. http://localhost:4000/ui/?page=logs shows three failure rows for the request id, and the -attempt-1 row that ran on the OpenAI deployment reads anthropic/claude-sonnet-4-6, provider anthropic, api_base https://api.anthropic.com/v1/messages
  4. http://localhost:4000/ui/?page=usage counts 3 requests and 3 failed requests for the one call they made

After: the same request writes rows that name the deployment each attempt ran on, and the usage page counts one request

  1. They send the same POST http://localhost:4000/v1/chat/completions with "model": "essay"
  2. They get the same HTTP 408
  3. http://localhost:4000/ui/?page=logs shows the same three rows, and the -attempt-1 row now reads openai/gpt-4.1, provider openai, api_base https://api.openai.com/v1, model group essay-fallback
  4. http://localhost:4000/ui/?page=usage counts 1 request and 1 failed request, with the spend of all three rows

Affected release

regression since #47416

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

Live proxy started from the checkout (python -m litellm.proxy.proxy_cli --config config.yaml --detailed_debug --port 4000) against a real Postgres 14 database_url, real Anthropic and OpenAI calls, no mocks. The 1500 word essay prompt against a 1.5 s timeout makes every attempt time out after the provider has accepted the prompt, so each attempt is billed. Two deployments, so the earlier attempts and the fallback run on different providers:

model_list:
  - model_name: essay
    litellm_params:
      model: anthropic/claude-sonnet-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
      timeout: 1.5
    model_info:
      id: dep-anthropic-sonnet-4-6
  - model_name: essay-fallback
    litellm_params:
      model: openai/gpt-4.1
      api_key: os.environ/OPENAI_API_KEY
      api_base: https://api.openai.com/v1
      timeout: 1.5
    model_info:
      id: dep-openai-gpt-4-1

router_settings:
  num_retries: 1
  fallbacks:
    - essay: ["essay-fallback"]
  allowed_fails: 100

general_settings:
  master_key: sk-live-master-1234
  database_url: os.environ/DATABASE_URL

The psql columns are request_id | model | custom_llm_provider | api_base | model_id | model_group | spend | prompt_tokens | status | attempted_retries | internal_call_origin for LiteLLM_SpendLogs and date | model | custom_llm_provider | api_requests | successful_requests | failed_requests | spend | prompt_tokens for LiteLLM_DailyUserSpend. The tables were truncated before each run and the daily rows were read after the 10 s batch write. Before was captured on main at e6065b9, before the attempt-row pricing change that current main carries, so its -attempt-0 row bills at gpt-4.1's rate (4.8e-05) while the After row bills at its own model's rate (7.2e-05); that difference comes from main, not this PR

Before (e6065b9, main)

  1. T0=2026-10-20T23:29:43Z, then the request

    $ curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-live-master-1234" -H "Content-Type: application/json" -d '{"model":"essay","messages":[{"role":"user","content":"Write a 1500 word essay on the history of the Roman aqueducts."}]}'
    HTTP 408 in 11.017419s
    
  2. The spend rows written for it

    $ psql "$DATABASE_URL" -Atc "select request_id, model, custom_llm_provider, api_base, model_id, model_group, spend, prompt_tokens, status, metadata->>'attempted_retries' as attempted_retries, metadata->>'billed_retry_attempt' as billed_retry_attempt from "LiteLLM_SpendLogs" where "startTime" >= '2026-10-20T23:29:43Z' order by request_id"
    f872e931-6b33-4c3d-a4e0-2a6b338f8a86|anthropic/claude-sonnet-4-6|anthropic|https://api.anthropic.com/v1/messages|dep-anthropic-sonnet-4-6|essay|4.8e-05|24|failure|1|
    f872e931-6b33-4c3d-a4e0-2a6b338f8a86-attempt-0|anthropic/claude-sonnet-4-6|anthropic|https://api.anthropic.com/v1/messages|dep-anthropic-sonnet-4-6|essay|4.8e-05|24|failure|1|
    f872e931-6b33-4c3d-a4e0-2a6b338f8a86-attempt-1|anthropic/claude-sonnet-4-6|anthropic|https://api.anthropic.com/v1/messages|dep-openai-gpt-4-1|essay|4.8e-05|24|failure|0|
    
  3. The daily spend row(s) after the batch write

    $ psql "$DATABASE_URL" -Atc "select date, model, custom_llm_provider, api_requests, successful_requests, failed_requests, spend, prompt_tokens from "LiteLLM_DailyUserSpend" order by model"
    2026-10-20|anthropic/claude-sonnet-4-6|anthropic|3|0|3|0.000144|72
    

The -attempt-1 row ran on dep-openai-gpt-4-1 but reads anthropic/claude-sonnet-4-6, anthropic, https://api.anthropic.com/v1/messages, and the daily row counts 3 requests and 3 failed requests for one HTTP call

After (2ae784d)

  1. T0=2026-10-20T23:30:47Z, then the request

    $ curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-live-master-1234" -H "Content-Type: application/json" -d '{"model":"essay","messages":[{"role":"user","content":"Write a 1500 word essay on the history of the Roman aqueducts."}]}'
    HTTP 408 in 12.000248s
    
  2. The spend rows written for it

    $ psql "$DATABASE_URL" -Atc "select request_id, model, custom_llm_provider, api_base, model_id, model_group, spend, prompt_tokens, status, metadata->>'attempted_retries' as attempted_retries, metadata->>'billed_retry_attempt' as billed_retry_attempt from "LiteLLM_SpendLogs" where "startTime" >= '2026-10-20T23:30:47Z' order by request_id"
    d25ff03d-4a5d-4007-8fe0-99dea720c087|anthropic/claude-sonnet-4-6|anthropic|https://api.anthropic.com/v1/messages|dep-anthropic-sonnet-4-6|essay|4.8e-05|24|failure|1|false
    d25ff03d-4a5d-4007-8fe0-99dea720c087-attempt-0|anthropic/claude-sonnet-4-6|anthropic||dep-anthropic-sonnet-4-6|essay|7.2e-05|24|failure|1|true
    d25ff03d-4a5d-4007-8fe0-99dea720c087-attempt-1|openai/gpt-4.1|openai|https://api.openai.com/v1|dep-openai-gpt-4-1|essay-fallback|4.8e-05|24|failure|0|true
    
  3. The daily spend row(s) after the batch write

    $ psql "$DATABASE_URL" -Atc "select date, model, custom_llm_provider, api_requests, successful_requests, failed_requests, spend, prompt_tokens from "LiteLLM_DailyUserSpend" order by model"
    2026-10-20|anthropic/claude-sonnet-4-6|anthropic|1|0|1|0.00012|48
    2026-10-20|openai/gpt-4.1|openai|0|0|0|4.8e-05|24
    

The -attempt-1 row now reads openai/gpt-4.1, openai, https://api.openai.com/v1, model group essay-fallback, both attempt rows carry the billed_retry_attempt flag, and the daily rows count 1 request and 1 failed request while keeping the spend and tokens of all three rows

Tests

tests/unit/proxy/hooks/test_proxy_track_cost_callback.py::test_attempt_rows_are_attributed_to_the_deployment_that_billed_them and ::test_attempt_rows_add_spend_but_not_requests_to_daily_spend build the spend-log payloads and daily transactions the hook produces for the same two-deployment timeout. Both fail with the fix stashed. Mutations checked: making the deployment lookup return nothing flips the first test ('anthropic/claude-sonnet-4-6' != 'openai/gpt-4.1'), and dropping the billed_retry_attempt flag flips the second ([1, 1, 1] == [1, 0, 0]). The second test also checks the attempt rows still reach LiteLLM_DailyModelUsage (Bugbot's finding on the first revision, which used internal_call_origin and lost them there)

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • An attempt row's api_base is the deployment's configured one, empty when none is configured (the -attempt-0 row above), since the URL a failed attempt was sent to is not recorded

Low

  • A deployment removed from the router between the request and the spend write keeps the final row's model, provider and api_base on its attempt row, as before

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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


Note

Medium Risk
Touches proxy spend logging, daily usage rollups, and failure retry accounting; incorrect handling could mis-attribute cost or skew usage metrics, but scope is limited to billed retry attempt rows.

Overview
Fixes a regression where per-attempt spend rows written on failed requests (retries/fallbacks since #47416) inherited the final attempt’s model, provider, and api_base, and each row inflated daily request counters.

Earlier billed attempts now resolve the router deployment by deployment_id and copy that deployment’s model, provider, configured api_base, and model group into the spend log and standard logging payload. Rows are stamped with billed_retry_attempt metadata (new constant and logging field).

Daily spend aggregation still records spend, tokens, and model usage for those rows but sets api_requests / success / failure counts to zero, same idea as internal sub-calls. Request-error rollup treats them as non–caller-request as well.

Adds deployment_params_provider for consistent provider attribution and unit tests for deployment attribution and daily request counting.

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

…t and keep them out of daily request counts

Each <request_id>-attempt-<n> row now carries the model, provider, api_base and model group of the deployment that billed it (looked up by model_info.id through the proxy router, injected as deployment_lookup) instead of copying the final row's, and is stamped internal_call_origin=billed_retry_attempt so the daily spend tables keep its spend and tokens while counting zero api_requests and failed_requests for it
@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

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

Copy link
Copy Markdown
Contributor

litellm-stampbot

Taking a look at this PR now. I'll update this comment with the review result

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@codspeed

codspeed Bot commented Oct 20, 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

✅ 34 untouched benchmarks


Comparing litellm_attempt_rows_deployment_and_counts (2ae784d) with main (7c39dbf)

Open in CodSpeed

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

…ternal_call_origin so model usage keeps their spend

Bugbot: an internal_call_origin stamp made build_model_usage_transaction drop the attempt rows from LiteLLM_DailyModelUsage. The rows now carry their own SpendLogsMetadata flag, which only the daily request counters read
@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.

@klu-berri

Copy link
Copy Markdown
Contributor Author

@BugBot run

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.15385% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/db/db_spend_update_writer.py 66.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

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

@klu-berri
klu-berri enabled auto-merge (squash) October 20, 2026 22:08
@veria-ai

veria-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

…d strip the flag from caller metadata

Bugbot: _record_request_error counted every attempt row as a caller failure in LiteLLM_DailyRequestErrors. Veria: a caller could send metadata.billed_retry_attempt to zero its own request counts, so the key joins the untrusted metadata fields the proxy strips on the way in
@klu-berri
klu-berri disabled auto-merge October 20, 2026 22:25
@klu-berri
klu-berri enabled auto-merge (squash) October 20, 2026 22:25
@klu-berri
klu-berri disabled auto-merge October 20, 2026 22:28
@klu-berri

Copy link
Copy Markdown
Contributor Author

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 560f673. Configure here.

@klu-berri
klu-berri enabled auto-merge (squash) October 20, 2026 23:02
@klu-berri
klu-berri merged commit 5dce13d into main Oct 20, 2026
88 of 89 checks passed
@klu-berri
klu-berri deleted the litellm_attempt_rows_deployment_and_counts branch October 20, 2026 23:33
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
…d keep them out of daily request counts (#47658)

* fix(proxy): attribute retry attempt spend rows to their own deployment and keep them out of daily request counts

Each <request_id>-attempt-<n> row now carries the model, provider, api_base and model group of the deployment that billed it (looked up by model_info.id through the proxy router, injected as deployment_lookup) instead of copying the final row's, and is stamped internal_call_origin=billed_retry_attempt so the daily spend tables keep its spend and tokens while counting zero api_requests and failed_requests for it

* fix(proxy): declare DeploymentLookup as a TypeAlias and leave the test file's untouched lines as they were

* fix(proxy): mark attempt rows with billed_retry_attempt instead of internal_call_origin so model usage keeps their spend

Bugbot: an internal_call_origin stamp made build_model_usage_transaction drop the attempt rows from LiteLLM_DailyModelUsage. The rows now carry their own SpendLogsMetadata flag, which only the daily request counters read

* fix(proxy): read the billed_retry_attempt flag through a typed helper so the basedpyright gate holds

* fix(proxy): keep the typed litellm_params local in _deployment_provider so the basedpyright gate holds

* fix(proxy): annotate the validated litellm_params as LiteLLM_Params in _deployment_provider

* fix(proxy): keep billed retry attempts out of daily request errors and strip the flag from caller metadata

Bugbot: _record_request_error counted every attempt row as a caller failure in LiteLLM_DailyRequestErrors. Veria: a caller could send metadata.billed_retry_attempt to zero its own request counts, so the key joins the untrusted metadata fields the proxy strips on the way in

* fix(proxy): stamp billed_retry_attempt explicitly in the spend log metadata so the basedpyright gate holds

---------

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 5dce13d)
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.

4 participants