Skip to content

fix(proxy): share the billing logger across callback registries - #47510

Merged
joshua-berri merged 3 commits into
mainfrom
litellm_fix_duplicate_cost_callbacks
Oct 20, 2026
Merged

joshua-berri merged 3 commits into
mainfrom
litellm_fix_duplicate_cost_callbacks

Conversation

@joshua-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves

  • Two billing logger instances count one request twice

How it solves it

  • Register one shared billing logger in both callback registries
  • Existing object deduplication delivers the accounting event once

User Flow

Before, a non-streamed request adds twice its recorded cost to key spend

  1. Create a fresh key with POST http://localhost:4000/key/generate
  2. Send POST http://localhost:4000/v1/chat/completions using that key
  3. Compare /key/info with /spend/logs, key spend is doubled

After, the same request adds its recorded cost once

  1. Create a fresh key with POST http://localhost:4000/key/generate
  2. Send POST http://localhost:4000/v1/chat/completions using that key
  3. Compare /key/info with /spend/logs, key spend matches

Relevant issues

Follow-up to #47192. Covers the duplicate billing portion of #47047, whose separate Decisions changes remain outside this PR

Linear ticket

Resolves LIT-9911

Implementation

cost_tracking() created separate ProxyDBLogger instances for the general and async-success callback registries. Completed-success dispatch combined those registries and delivered both instances. The proxy now registers the same instance in both places, following the existing shared-instance registration convention

The generic completed-success selector is identical to the merge base. No new logger equivalence policy is introduced. Different logger headers, event subscriptions and redaction settings retain their existing behavior

Tests

All 938 affected unit tests passed for the implementation. After the fixed-timestamp test follow-up at 7ee91ebff9954104214a085aeb4e235da275944d, all 47 focused cases and canonical local lint/type gates pass again. Production code is unchanged by that follow-up. The extended lifecycle test runs real registration, request setup, dispatch and event serialization, asserting one accounting publication after one or two setup calls. On the unfixed baseline it fails with two publications in both cases

The existing local source-built proxy/Postgres/Redis accounting tests pass for background response billing and batch callback delivery. Changed executable-line coverage is 3/3. The touched cost_tracking() function has 7/7 lines and 2/2 branches covered

Independent paid-call verification passed at this tip against the merge base. The baseline double-bills four of five API flows. This tip bills once on all five flows and a real completed two-line batch. Fresh-key zero-spend controls and delayed accounting rechecks passed. The independent lifecycle regression fails twice on the baseline and passes on this tip

All 107 hosted checks pass. The completed Codecov report shows 100% patch coverage. Greptile reports 5/5, and Veria, Bugbot and LiteReview have no unresolved actionable findings at this tip

Pre-Submission checklist

  • Meaningful regression and compatibility tests added
  • Affected unit tests and local accounting integration tests pass
  • Scope is isolated to duplicate proxy billing
  • All applicable required CI/CD checks pass
  • Completed Codecov report inspected for the current tip
  • All four required current-tip reviews complete with concerns addressed

Type

Bug Fix
Test

Screenshots / Proof of Fix

Independently executed through Devin on 2026-10-20, using source builds at the SHAs below, separate Postgres databases, shared Redis on port 6390, and two workers per proxy. Source imports resolved inside each clean worktree. These were paid OpenAI calls with gpt-6-luna

Identical configuration on both sides, with secrets supplied through environment variables

model_list:
  - model_name: gpt-6-luna
    litellm_params: {model: openai/gpt-6-luna, api_key: os.environ/OPENAI_API_KEY}
general_settings: {master_key: os.environ/LITELLM_MASTER_KEY, database_url: os.environ/DATABASE_URL, proxy_batch_write_at: 5, use_redis_transaction_buffer: true}
litellm_settings: {drop_params: true, cache: false}
router_settings: {redis_host: os.environ/REDIS_HOST, redis_port: os.environ/REDIS_PORT}

From each checked-out source, start PYTHONPATH="$PWD:$PWD/enterprise" python -m litellm.proxy.proxy_cli --config config.yaml --port "$PORT" --num_workers 2. Use port 4111 for Before and 4112 for After, and set B to that localhost URL

Before each case, create a fresh key and confirm its initial spend is zero

KEY=$(curl -s "$B/key/generate" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'content-type: application/json' -d '{}' | jq -r .key)
curl -s "$B/key/info?key=$KEY" -H "Authorization: Bearer $LITELLM_MASTER_KEY"

After each request, read both endpoints below once accounting has flushed, then recheck at 30 and 60 seconds. Every case below retained the same result on recheck

curl -s "$B/key/info?key=$KEY" -H "Authorization: Bearer $LITELLM_MASTER_KEY"
curl -s "$B/spend/logs?api_key=$KEY" -H "Authorization: Bearer $LITELLM_MASTER_KEY"

Amounts vary where the model generated different token counts. Compare key spend with that request's recorded cost, rather than comparing amounts across different responses

Before (ba61ecd)

Chat non-stream

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/chat/completions" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 8.8e-06, and key spend is 1.76e-05

Chat streaming control

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/chat/completions" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 3.3e-06, and key spend is 3.3e-06

Responses

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/responses" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","input":"Reply with the single word: billing"}'
  3. Read spend using the commands above, one successful row totals 9.8e-06, and key spend is 1.96e-05

OpenAI pass-through

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/openai_passthrough/v1/responses" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","input":"Reply with the single word: billing"}'
  3. Read spend using the commands above, one successful row totals 3.8e-06, and key spend is 7.6e-06

Messages

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/messages" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","max_tokens":64,"messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 3.8e-06, and key spend is 7.6e-06

Completed batch control

  1. Add general_settings.proxy_batch_polling_interval: 15, restart with PROXY_BATCH_POLLING_ENABLED=true, and create a fresh zero-spend key
  2. Upload two chat JSONL lines with model gpt-6-luna and prompts Reply with the single word: billing and Reply with the single word: batch using curl -s "$B/v1/files" -H "Authorization: Bearer $KEY" -F purpose=batch -F target_model_names=gpt-6-luna -F file=@batch_in.jsonl
  3. Submit curl -s "$B/v1/batches" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"input_file_id":"<returned file id>","endpoint":"/v1/chat/completions","completion_window":"24h","model":"gpt-6-luna"}', then poll GET $B/v1/batches/<returned batch id> with the same key until completed
  4. Both lines succeeded. The billable batch row totals 6.05e-06 and key spend is 6.05e-06. File and batch creation rows have zero cost

After (7ee91eb)

Chat non-stream

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/chat/completions" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 3.3e-06, and key spend is 3.3e-06

Chat streaming control

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/chat/completions" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 9.8e-06, and key spend is 9.8e-06

Responses

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/responses" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","input":"Reply with the single word: billing"}'
  3. Read spend using the commands above, one successful row totals 3.8e-06, and key spend is 3.8e-06

OpenAI pass-through

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/openai_passthrough/v1/responses" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","input":"Reply with the single word: billing"}'
  3. Read spend using the commands above, one successful row totals 3.8e-06, and key spend is 3.8e-06

Messages

  1. Create a fresh zero-spend key using the command above
  2. Run curl -s "$B/v1/messages" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"gpt-6-luna","max_tokens":64,"messages":[{"role":"user","content":"Reply with the single word: billing"}]}'
  3. Read spend using the commands above, one successful row totals 9.3e-06, and key spend is 9.3e-06

Completed batch control

  1. Add general_settings.proxy_batch_polling_interval: 15, restart with PROXY_BATCH_POLLING_ENABLED=true, and create a fresh zero-spend key
  2. Upload two chat JSONL lines with model gpt-6-luna and prompts Reply with the single word: billing and Reply with the single word: batch using curl -s "$B/v1/files" -H "Authorization: Bearer $KEY" -F purpose=batch -F target_model_names=gpt-6-luna -F file=@batch_in.jsonl
  3. Submit curl -s "$B/v1/batches" -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"input_file_id":"<returned file id>","endpoint":"/v1/chat/completions","completion_window":"24h","model":"gpt-6-luna"}', then poll GET $B/v1/batches/<returned batch id> with the same key until completed
  4. Both lines succeeded. The billable batch row totals 9.3e-06 and key spend is 9.3e-06. File and batch creation rows have zero cost

Caveats

Low

  • Separately constructed dynamic/global logger equivalence retains baseline behavior

Final Attestation

  • Current-tip verification and all required reviews are complete

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review please review the current commit for duplicate accounting, preserved callback selection, and the included live verification evidence

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current commit for duplicate accounting, distinct logger preservation, and compatibility with existing callback registration behavior

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run please review the current commit for duplicate accounting, preserved callback selection, and meaningful regression coverage across logger configurations

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

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with the clock-read finding fixed and no new actionable issues found

Summary

cost_tracking() shares one ProxyDBLogger across both callback registries so one request produces one accounting event

  • A completed proxy request records its spend once.

Reviews (3) · Last reviewed commit: "test(proxy): use fixed timestamps for bi..." · Reviewed by Greptile

@litereview

litereview Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/proxy/proxy_server.py and unit tests under tests/unit/ only. Nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/** changed.
  • Passed · Compatibility requirements (required): No supported behavior breaks. Before the change, cost_tracking() registered two ProxyDBLogger objects with equal keys, one in litellm.callbacks and one in litellm._async_success_callback. After it, both registries hold one object. Registry sizes stay the same: 2 callbacks and 1 async-success entry, both before and after. The type, constructor arguments and failure-hook consumers stay the same. _bill_rejected_frame still iterates litellm.callbacks for ProxyDBLogger. The only observable change fixes double spend publication, so the PR title needs no ! marker.
  • Passed · Changed behavior and result consistency (required): Traced path: cost_tracking() registers the logger. Startup fan-out in proxy/utils.py:1598 and function_setup in utils.py:1137 copies the litellm.callbacks instance into success_callback. _get_completed_success_callbacks then merges the sync and async registries with get_combined_callback_list (dict.fromkeys, identity/hash dedupe) before async_log_success_event calls spend_event_producer.publish. With two distinct instances, both survived dedupe, so the request was billed twice. With one shared instance, it survives once. Repeat setup (setup_count=2) keeps the first instance because key-based _add_custom_logger_to_list dedupe skips the new one. Failure hooks still read litellm.callbacks and are unchanged. Ran pytest tests/unit/proxy/proxy_server/test_lifecycle.py tests/unit/litellm_core_utils/test_litellm_logging.py -k 'cost_tracking or completed_success or preserves_generic or split_registries or private': 41 passed. Defect-sensitive oracle: I reverted only the async registration to ProxyDBLogger(spend_event_producer). Both test_cost_tracking_adds_db_and_shadow_eval_callbacks_when_prisma_set[1] and [2] then failed on producer.publish.assert_awaited_once() with two publications. Standards: the test uses Final and typed parameters, consistent with the repo's typing conventions. No smells noted.

View review · Reviewed 7ee91ebff995

@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_fix_duplicate_cost_callbacks (7ee91eb) with main (8a2782e)

Open in CodSpeed

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

@joshua-berri joshua-berri changed the title fix(logging): deduplicate equivalent completed success callbacks fix(proxy): share the billing logger across callback registries Oct 20, 2026
@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai please review a00e72d, which shares the billing logger at registration and restores baseline generic callback selection, addressing both findings

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review please review a00e72d, which shares the billing logger at registration, preserves distinct configurations, and adds accounting regression coverage

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run please review a00e72d for duplicate billing, repeated setup behavior, and preservation of distinct logger configurations after removing generic filtering

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

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai please review 7ee91eb, which replaces both new test clock reads with fixed timestamps and preserves the approved production fix

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review please refresh your review for 7ee91eb, a fixed-timestamp test follow-up with unchanged production code and passing local gates

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run please refresh your review for 7ee91eb, a fixed-timestamp test follow-up with unchanged production code and passing local gates

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

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

LGTM. Thanks!

@joshua-berri
joshua-berri merged commit 02199b6 into main Oct 20, 2026
112 checks passed
@joshua-berri
joshua-berri deleted the litellm_fix_duplicate_cost_callbacks branch October 20, 2026 15:21
yuneng-berri pushed a commit that referenced this pull request Oct 20, 2026
…sted model and name a missing answers field (#47508)

* test: bill each completed request once and price unpriced returned decision models at the requested model

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>

* fix(logging,decisions): bill each request once and price returned decision models only when they carry rates

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>

* fix(decisions): leave the double-billing fix to #47510 and keep the decisions pricing and missing-answers fixes

* fix(decisions): name malformed answer entries and pick the Arize cache-hit span by attribute

* test(decisions): cover a returned-model row with metadata but no rates

* fix(decisions): keep upstream reply text out of the parse error so it stays a 500

* fix(decisions): answer every malformed upstream reply with a 500, whatever text it carries

A reply that fails the decisions response schema now raises
DecisionsResponseValidationError, which the decisions call maps straight to
InternalServerError instead of passing it through exception_type. Its text
matching read an answer key like rate_limit, or a value like "Request timed
out", as a 429 or a 408, so the router cooled down a deployment for a reply
that fails the same way on every retry.

The message also drops the empty location for a reply that is not an
object, the Arize family test loses the cache_hit entries main already
added, and the Bedrock Mantle count-tokens wire test calls
_metadata_deployment, since main renamed the _deployment helper under it.

---------

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
@norkelbyte norkelbyte mentioned this pull request Oct 28, 2026
4 of 6 tasks
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.

2 participants