Skip to content

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

Merged
klu-berri merged 2 commits into
mainfrom
litellm_disconnect_billing_499
Oct 20, 2026
Merged

klu-berri merged 2 commits into
mainfrom
litellm_disconnect_billing_499

Conversation

@klu-berri

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

Copy link
Copy Markdown
Contributor

Two spend-row bugs in the 499 pricing that #47436 shipped. A provider that itself answers HTTP 499 was being billed as if the caller had hung up on the proxy mid-generation, and a caller who hung up while a during_call guardrail was still running got the prompt billed a second time on top of the completed call's real cost. Both rows now stay at zero, the real client-disconnect row keeps its estimated input cost

Details

TLDR

Problem this solves:

  • Any exception with status_code 499 was priced as a client disconnect, upstream 499s included
  • A disconnect while a during_call guardrail was pending billed the prompt twice
  • The second row doubled the real spend of a call that already finished and logged

How it solves it:

  • Only the proxy's own disconnect HTTPException counts as a billed disconnect
  • A failure row prices nothing once the call's success log task was actually enqueued, not merely claimed. A success log parked in the deferred slot (a post_call guardrail is registered) never runs once the 499 interrupts, so that failure row keeps its price and the request is still billed once
  • Both rows still carry the estimated prompt tokens at zero cost

User Flow

Before: a team's cost dashboard shows spend the provider never charged for

  1. They send POST http://localhost:4000/v1/chat/completions to a model whose upstream answers HTTP 499, and get back a 499 error with OpenAIException - client closed request
  2. http://localhost:4000/ui/?page=logs shows that failed request at non-zero spend, priced at the input rate
  3. They send the same POST with "guardrails": ["slow-during-call"] and hang up after 3 seconds while the guardrail is still running
  4. The logs page shows two rows for that one request, the real completed call at its real cost and a second failure row billed for the prompt again

After: the same requests show only what the provider actually charged

  1. They send POST http://localhost:4000/v1/chat/completions to the model whose upstream answers HTTP 499, and get the same 499 error back
  2. http://localhost:4000/ui/?page=logs shows that failed request at $0 with the prompt tokens still counted
  3. They send the same POST with "guardrails": ["slow-during-call"] and hang up after 3 seconds
  4. The logs page shows the completed call at its real cost and the failure row for the hang-up at $0

Affected release

regression since #47436

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

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live proxy from the checkout (python litellm/proxy/proxy_cli.py --config config.yaml --detailed_debug --port 4000), real Postgres database_url, cancel_on_disconnect: true, real OpenAI gpt-5.5 calls that cost real money. The upstream 499 case cannot be steered through a real provider, so that one deployment points at a minimal fake upstream on 127.0.0.1:8499 that answers every POST with HTTP 499 and {"error": {"message": "client closed request", "code": 499}}. The during_call guardrail is a CustomGuardrail whose async_moderation_hook sleeps 8 seconds and returns. The hang-up case is curl -m 3, which exits 28 on both sides

config.yaml

model_list:
  - model_name: gpt-5.5
    litellm_params:
      model: openai/gpt-5.5
      api_key: os.environ/OPENAI_API_KEY
  - model_name: gpt-5.5-upstream-499
    litellm_params:
      model: openai/gpt-5.5
      api_key: fake
      api_base: http://127.0.0.1:8499/v1
guardrails:
  - guardrail_name: slow-during-call
    litellm_params:
      guardrail: slow_guardrail.SlowGuardrail
      mode: during_call
      default_on: false
general_settings:
  master_key: sk-lit499-master
  cancel_on_disconnect: true
  database_url: os.environ/DATABASE_URL

Before (5c341e7)

Upstream answers HTTP 499

  1. curl -s -m 30 http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-lit499-master" -H "Content-Type: application/json" -d '{"model":"gpt-5.5-upstream-499","messages":[{"role":"user","content":"main3 f5 one short sentence about tea"}]}'
  2. {"error":{"message":"litellm.APIError: APIError: OpenAIException - client closed request\n\nLiteLLM: model group 'gpt-5.5-upstream-499' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"499"}}
  3. psql "$DATABASE_URL" -c "select model, status, prompt_tokens, completion_tokens, spend, request_id from \"LiteLLM_SpendLogs\" where \"startTime\" >= '2026-10-20T21:27:20Z' order by \"startTime\";" (rows shared with the next case, first row is this request)
     model      | status  | prompt_tokens | completion_tokens |  spend   |               request_id
----------------+---------+---------------+-------------------+----------+----------------------------------------
 openai/gpt-5.5 | failure |            16 |                 0 |    8e-05 | 989768b0-2ec8-4fad-948b-a3c4f5537647
 openai/gpt-5.5 | failure |            16 |                 0 |    8e-05 | 0b01e3e7-fe4b-4d77-89d2-3d1d52783806
 openai/gpt-5.5 | success |            15 |                28 | 0.000915 | chatcmpl-EbBeb0reZzFMnpZoFOjMHhQIHW2SD
  1. The upstream 499 is billed 8e-05, the input rate times 16 estimated prompt tokens

Hang up while a during_call guardrail is pending

  1. curl -s -m 3 http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-lit499-master" -H "Content-Type: application/json" -d '{"model":"gpt-5.5","guardrails":["slow-during-call"],"messages":[{"role":"user","content":"main3 f6 one short sentence about tea"}]}'; echo "curl exit=$?"
  2. curl exit=28
  3. Rows two and three of the psql output above belong to this one request: the completed call at 0.000915 (15 prompt, 28 completion) plus a failure row that bills the prompt again at 8e-05

After (db0310a)

Upstream answers HTTP 499

  1. curl -s -m 30 http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-lit499-master" -H "Content-Type: application/json" -d '{"model":"gpt-5.5-upstream-499","messages":[{"role":"user","content":"tip2 f5 one short sentence about tea"}]}'
  2. {"error":{"message":"litellm.APIError: APIError: OpenAIException - client closed request\n\nLiteLLM: model group 'gpt-5.5-upstream-499' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"499"}}
  3. psql "$DATABASE_URL" -c "select model, status, prompt_tokens, completion_tokens, spend, request_id from \"LiteLLM_SpendLogs\" where \"startTime\" >= '2026-10-20T21:51:37Z' order by \"startTime\";" (rows shared with the next case, first row is this request)
     model      | status  | prompt_tokens | completion_tokens |  spend   |               request_id
----------------+---------+---------------+-------------------+----------+----------------------------------------
 openai/gpt-5.5 | failure |            16 |                 0 |        0 | 4d0b4c4e-8c51-41bb-988a-ebf0690d8c4f
 openai/gpt-5.5 | failure |             0 |                 0 |        0 | 7d123f64-51c1-42fc-9621-210c0b5e25d1
 openai/gpt-5.5 | success |            15 |                34 | 0.001095 | chatcmpl-EbC26KVM0uhAVRGbOch9DHqfjCaqu
  1. The upstream 499 keeps its 16 estimated prompt tokens and is billed 0

Hang up while a during_call guardrail is pending

  1. curl -s -m 3 http://127.0.0.1:4000/v1/chat/completions -H "Authorization: Bearer sk-lit499-master" -H "Content-Type: application/json" -d '{"model":"gpt-5.5","guardrails":["slow-during-call"],"messages":[{"role":"user","content":"tip2 f6 one short sentence about tea"}]}'; echo "curl exit=$?"
  2. curl exit=28
  3. Rows two and three of the psql output above belong to this one request: the completed call at 0.001095 (15 prompt, 34 completion) and the hang-up failure row at 0

Control on both sides, a hang-up with no guardrail while gpt-5.5 is generating (curl -m 3, "write 400 words about tea"), still lands one failure row priced at the input rate (8e-05 on both sides, 16 estimated prompt tokens), so the #47436 behavior for a real mid-generation disconnect is unchanged

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A hang-up while the TCP connect to the provider is still pending is still billed at the input rate (reproduced live with a blackhole api_base, 8e-05 at this tip). Nothing on the failure path records whether the request bytes ever left the proxy, so telling that apart from a mid-generation hang-up needs new instrumentation and is left for a follow-up

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/f4606f7d1d4d4537a43e14b62cc0b537
Open in Devin Desktop: https://app.devin.ai/desktop/session/f4606f7d1d4d4537a43e14b62cc0b537?variant=devin
Requested by: @kerrylu-berri


Note

Medium Risk
Changes proxy failure spend attribution and disconnect detection; wrong logic would under- or over-charge customers on edge paths (499, guardrails).

Overview
Fixes incorrect spend on HTTP 499 and double-billing when a client disconnects after the LLM call already finished.

499 classification: _client_disconnected now only treats the proxy’s own FastAPI HTTPException (status 499) as a billed client hang-up. Upstream/provider failures that surface as litellm.APIError with code 499 are no longer priced like a mid-generation disconnect.

No second charge after success: Logging tracks whether the async success log was actually enqueued (mark_async_success_log_enqueued in the @client path), not just claimed. Failure-path spend lifting skips estimated input billing when that flag is set, so a 499 raised while a during_call guardrail is still pending does not add another prompt charge on top of the completed call. If success logging was only claimed and deferred for post_call guardrails but never flushed before disconnect, failure billing still applies so the request is charged once.

Unit tests cover upstream 499 at $0, post-completion disconnect at $0, and deferred-never-flushed disconnect still priced.

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

…, and never after the call already completed
@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.

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at 97d6583. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at 97d6583. Changes failure-path spend attribution for disconnects and 499 errors; incorrect classification would under- or over-charge teams, but scope is narrow and covered by new unit tests. Bugbot run requested, finished in 6 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

@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

✅ 32 untouched benchmarks


Comparing litellm_disconnect_billing_499 (db0310a) with main (6bc1b2b)1

Open in CodSpeed

Footnotes

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

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

@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
@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 20, 2026
@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@klu-berri

Copy link
Copy Markdown
Contributor Author

@BugBot run

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

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

@klu-berri
klu-berri merged commit ffb7133 into main Oct 20, 2026
97 of 98 checks passed
@klu-berri
klu-berri deleted the litellm_disconnect_billing_499 branch October 20, 2026 22:11
devin-ai-integration Bot added a commit that referenced this pull request Oct 21, 2026
…, and never after the call already completed (#47652)

Backport of #47652 to stable/1.103.x

Cherry-picked from ffb7133 (main)
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
…, and never after the call already completed (BerriAI#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

---------

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

Backport of BerriAI#47652 to stable/1.106.x
Cherry-picked from ffb7133 (main)
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
…, 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

---------

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit ffb7133)
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
…, and never after the call already completed (BerriAI#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

---------

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

Backport of BerriAI#47652 to stable/1.105.x.
Cherry-picked from ffb7133 (main).
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.

4 participants