Skip to content

fix(logging): log spend once for large non-streaming requests on the chat to Responses bridge - #44508

Merged
kerry-berri merged 11 commits into
BerriAI:mainfrom
hektorjg:fix/async-success-dedup-race
Oct 6, 2026
Merged

kerry-berri merged 11 commits into
BerriAI:mainfrom
hektorjg:fix/async-success-dedup-race

Conversation

@hektorjg

@hektorjg hektorjg commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Large non-streaming chat requests to openai/responses/* models are logged twice
  • Key, team and daily spend are incremented twice for one request

How it solves it:

  • The innermost @client wrapper claims the async success log on the shared Logging object, synchronously, before any task is created (claim_async_success_log in litellm_logging.py, called from _schedule_async_success_logging in utils.py). It always exits first because the outer wrapper is awaiting it. The outer wrapper then gets False and schedules nothing, so one request queues exactly one success handler and it carries the provider-shaped result. There is no await between the check and the decision, so no lock is needed
  • The handler itself and the streaming paths are unchanged
  • Integration test: one spend row and one key charge for a single 300,000-char bridged chat request, and the row's request_id is the inner Responses result's encoded id, so the provider-shaped result is the one logged
  • Regression test: two wrapper exits with one Logging object, driven through the logging worker with a yielding base64 offload, log once and log the inner provider-shaped result. It fails without the claim
  • A background interaction's completion still logs while the create's in_progress handler is parked on awaited work

User Flow

Before: a developer sends one large chat request and is billed twice in LiteLLM's own accounting

  1. They send POST https://litellm-domain/v1/chat/completions to a openai/responses/gpt-5.6-luna model with ~300k characters of message text, no streaming
  2. The response comes back normally, and the provider bills one call
  3. https://litellm-domain/ui/?page=logs shows two rows for the request, and the key and team budgets drop by twice the real cost

After: the same request is logged once

  1. They send the same POST https://litellm-domain/v1/chat/completions
  2. The response comes back normally
  3. The logs page shows one row, and the key and team budgets drop by the real cost

Relevant issues

Fixes #44500

Affected release

Regression since v1.102.0

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks (the misc, rust-wheel and proxy-infra-root jobs fail on main too, from the SpendLogRecord.provider_request_id and tracing fixture errors)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Greptile confidence score 5/5 on 41d88c9

Screenshots / Proof of Fix

SDK-level, real calls to openai/responses/gpt-5.6-luna via litellm.acompletion (non-streaming), with a CustomLogger counting async_log_success_event per litellm_call_id. Prompts are random words plus "Reply OK".

Before (6532dcb)

  1. 200,000 chars: 1 event (ResponsesAPIResponse)
  2. 300,000 chars: 2 events (ModelResponse, ResponsesAPIResponse) for the same litellm_call_id

After (6532dcb + this change)

  1. 200,000 chars: 1 event (ResponsesAPIResponse)
  2. 300,000 chars: 1 event (ResponsesAPIResponse)
  3. 300,000 chars, second run: 1 event (ResponsesAPIResponse)

The logged result is the inner, provider-shaped ResponsesAPIResponse in every case: the inner wrapper exits first, so it is the one that claims the log

Proxy-level: tests/integration/spend/test_responses_bridge_spend_once.py sends one 300,000-char non-streaming chat request to an openai/responses/ deployment through a real proxy with Postgres. With litellm_logging.py reverted to 6532dcb it fails with two LiteLLM_SpendLogs rows for one litellm_call_id; with this change it writes one row whose request_id decodes to the upstream Responses id, and the key is charged once

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • If the one queued handler is cancelled or raises before its callbacks run, the other wrapper does not retry
    • That matches any ordinary single-wrapper request today; a retry would need the same shared object to log twice on purpose
  • Only the @client wrapper exit path changes. Callers that invoke async_success_handler directly (cache hits, streaming, background interaction completion) are not affected by the claim

Note

Medium Risk
Changes when async success logging is scheduled for nested wrapper exits, which directly affects spend accounting; scope is narrow and does not alter streaming or direct success-handler callers.

Overview
Fixes double spend logging for large non-streaming chat requests routed through nested @client wrappers (e.g. chat completions over the OpenAI Responses bridge), where two wrapper exits shared one Logging object and both could enqueue async success handlers before has_logged_async_success was set—often after yielding during base64 message offload.

Adds a synchronous first-wins claim on the logging object (claim_async_success_log / _async_success_scheduled) at the start of _schedule_async_success_logging, so only the innermost (provider-shaped) exit schedules one handler; outer wrappers return without enqueueing. Direct paths such as async_success_handler and background interaction completion are unchanged.

Adds an integration test asserting one LiteLLM_SpendLogs row and one key charge for a ~300k-char bridged request, plus unit regressions for nested wrapper scheduling and interaction completion while an in-progress handler is still parked.

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

@hektorjg
hektorjg requested a review from a team October 4, 2026 16:29
@CLAassistant

CLAassistant commented Oct 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Medium risk] Fixes duplicate logging for nested request wrappers.

The logging fix appears safe, but the unit-test guide violations must be addressed before merging.

Findings

  1. P2 Project-owned function patched ▶
  2. P2 Test context in docstrings ▶
  3. P2 Unit tests read the clock ▶

Summary

The PR claims async success logging before nested wrappers enqueue handlers, so a bridged non-streaming request schedules one spend log. It also adds unit and proxy integration coverage for that behavior.

Reviews (11) · Last reviewed commit: "test(integration): send one bridged requ..."

@codecov

codecov Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing hektorjg:fix/async-success-dedup-race (41d88c9) with main (a3e74a5)

Open in CodSpeed

@hektorjg hektorjg changed the title fix(logging): claim the async success dedup flag before the first await fix(logging): stop double-logging spend for large non-streaming requests on the chat→Responses bridge Oct 4, 2026
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

messages=messages,
stream=False,
call_type="acompletion",
start_time=time.time(),

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.

P2 Unit tests read the clock Both new unit tests call time.time() and datetime.now(), which violates the unit-test guide's no-clock requirement. Use fixed timestamps in both tests; this repository requirement must be satisfied before merging

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

Fixed in 1205176: both tests now use a fixed 2026-01-01 UTC timestamp instead of time.time() and datetime.now(), and the first docstring describes the lock

hektorjg and others added 5 commits October 6, 2026 19:21
Nested @client wrappers on the chat -> Responses bridge schedule two async
success tasks on one logging object. The dedup flag was checked at the top
of _async_success_handler_body but only set after several awaits; the
worker-thread base64 offload for messages >= 256 KiB yields there, so the
second task passed the same check and the request was logged twice
(two SpendLogs rows, key/team/daily spend counted twice).

Fixes BerriAI#44500

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…tead of claiming early

Claiming the dedup flag before the first await (previous commit) let a first
handler that is cancelled before its callbacks run (e.g. by the logging
worker's per-coroutine timeout) suppress the second one, losing the request's
success accounting. Serialise non-streaming handlers on the same Logging
object with an asyncio.Lock kept in a module-level WeakKeyDictionary: the
second handler waits, then skips if the first logged, or logs itself if the
first raised or was cancelled first. Streaming chunk logging is not locked.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…dged chat completions

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…rting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri
mateo-berri force-pushed the fix/async-success-dedup-race branch from 85a307e to 1205176 Compare October 6, 2026 19:28
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@veria-ai

veria-ai Bot commented Oct 6, 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.

@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

… innermost wrapper in the claim docstrings

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

…onses result is the logged one

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@kerry-berri kerry-berri changed the title fix(logging): stop double-logging spend for large non-streaming requests on the chat→Responses bridge fix(logging): log spend once for large non-streaming requests on the chat to Responses bridge Oct 6, 2026
@kerry-berri

Copy link
Copy Markdown
Contributor

@hektorjg thank you for contributing!

@kerry-berri
kerry-berri enabled auto-merge (squash) October 6, 2026 21:22
@kerry-berri
kerry-berri merged commit 157d96d into BerriAI:main Oct 6, 2026
99 of 100 checks passed

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

@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread tests/unit/test_utils.py
await asyncio.sleep(0)
return await real_truncate(messages)

monkeypatch.setattr(litellm_logging, "truncate_base64_in_messages_async", yielding_truncate)

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.

P2 Project-owned function patched Both unit tests patch our truncation function to control timing. The unit-test guide forbids doubles of project code; satisfy this requirement before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment thread tests/unit/test_utils.py
Comment on lines +6718 to +6722
"""Chat over the Responses bridge exits two @client wrappers with one logging object. Issue
#44500: both exits enqueued a success handler, and on a large prompt the first one yielded to
the worker-thread base64 offload before it marked ``has_logged_async_success``, so the second
passed the check too and the request was logged and billed twice. The schedule step claims the
log for the object synchronously, so only the inner provider-shaped result is ever logged."""

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.

P2 Test context in docstrings This test and the background-interaction test put context in explanatory docstrings. The test guide requires context in assertion messages; satisfy this requirement before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

yuneng-berri added a commit that referenced this pull request Oct 8, 2026
chore(release): backport #44508 to stable/1.102.x and cut 1.102.4
klu-berri added a commit that referenced this pull request Oct 13, 2026
…table_1_105_x

fix(proxy): backport #44243 and #44508 to stable/1.105.x for v1.105.1
hao3039032 pushed a commit to hao3039032/litellm that referenced this pull request Oct 14, 2026
…chat to Responses bridge (BerriAI#44508)

Backport of BerriAI#44508 to stable/1.105.x.

Cherry-picked from 157d96d (origin/main).

(cherry picked from commit 157d96d)
rogerrum pushed a commit to rogerrum/k8s-gitops that referenced this pull request Oct 22, 2026
…105.1 ) (#3656)

This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [ghcr.io/berriai/litellm](https://images.chainguard.dev/directory/image/wolfi-base/overview) ([source](https://github.com/BerriAI/litellm)) | patch | `v1.105.0` → `v1.105.1` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the [Dependency Dashboard](issues/3566) for more information.

---

### Release Notes

<details>
<summary>BerriAI/litellm (ghcr.io/berriai/litellm)</summary>

### [`v1.105.1`](https://github.com/BerriAI/litellm/releases/tag/v1.105.1)

[Compare Source](BerriAI/litellm@v1.105.0...v1.105.1)

#### Verify Docker Image Signature

All LiteLLM Docker images are signed with [cosign](https://docs.sigstore.dev/cosign/overview/). Every release is signed with the same key introduced in [commit `0112e53`](BerriAI/litellm@0112e53).

**Verify using the pinned commit hash (recommended):**

A commit hash is cryptographically immutable, so this is the strongest way to ensure you are using the original signing key:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/0112e53046018d726492c814b3644b7d376029d0/cosign.pub \
  ghcr.io/berriai/litellm:v1.105.1
```

**Verify using the release tag (convenience):**

Tags are protected in this repository and resolve to the same key. This option is easier to read but relies on tag protection rules:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/v1.105.1/cosign.pub \
  ghcr.io/berriai/litellm:v1.105.1
```

Expected output:

```
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

***

#### What's Changed

- fix(proxy): backport [#&#8203;44243](BerriAI/litellm#44243) and [#&#8203;44508](BerriAI/litellm#44508) to stable/1.105.x for v1.105.1 by [@&#8203;kerry-berri](https://github.com/kerry-berri) in [#&#8203;46313](BerriAI/litellm#46313)

**Full Changelog**: <BerriAI/litellm@v1.105.0...v1.105.1>

</details>

---

### Configuration

📅 **Schedule**: (in timezone America/Chicago)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xNTEuMiIsInVwZGF0ZWRJblZlciI6IjQ0LjE1MS4yIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJyZW5vdmF0ZS9jb250YWluZXIiLCJ0eXBlL3BhdGNoIl19-->

Reviewed-on: https://git.rsr.net/roger/k8s-gitops/pulls/3656
pamanseau pushed a commit to KubeTEE-AI/litellm that referenced this pull request Oct 25, 2026
…chat to Responses bridge (BerriAI#44508)

* fix(logging): claim the async success dedup flag before the first await

Nested @client wrappers on the chat -> Responses bridge schedule two async
success tasks on one logging object. The dedup flag was checked at the top
of _async_success_handler_body but only set after several awaits; the
worker-thread base64 offload for messages >= 256 KiB yields there, so the
second task passed the same check and the request was logged twice
(two SpendLogs rows, key/team/daily spend counted twice).

Fixes BerriAI#44500

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(logging): serialise async success handlers per logging object instead of claiming early

Claiming the dedup flag before the first await (previous commit) let a first
handler that is cancelled before its callbacks run (e.g. by the logging
worker's per-coroutine timeout) suppress the second one, losing the request's
success accounting. Serialise non-streaming handlers on the same Logging
object with an asyncio.Lock kept in a module-level WeakKeyDictionary: the
second handler waits, then skips if the first logged, or logs itself if the
first raised or was cancelled first. Streaming chunk logging is not locked.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(integration): pin one spend row and one key charge for large bridged chat completions

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): wait for the large request's spend row before asserting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): use fixed timestamps in async success dedup tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* style(logging): trim the async success dedup lock comment

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(logging): reset background interaction dedupe under the success dedup lock

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): use a fixed start time in the interactions logging helper

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: claim the async success log at schedule time instead of locking the handler

Nested @client wrappers (chat over the Responses bridge, Anthropic Messages over the chat adapter) exit with one shared Logging object and each queued their own async success handler. The handler checked has_logged_async_success before its awaited work and set it after, so both could pass the check and the request was logged and billed twice.

_schedule_async_success_logging now claims the log on the Logging object synchronously through claim_async_success_log, and a later wrapper returns without enqueuing. There is no await between the check and the decision, so no lock is needed. The per-object asyncio.Lock, the WeakKeyDictionary that held it and the locked block in async_log_background_interaction_completion are gone.

Tests: the regression test moves to tests/unit/test_utils.py and drives two _dispatch_success_logging exits with one Logging object through the logging worker, asserting one log with the inner result. It fails without the claim. The cancelled-handler test is dropped since a second wrapper no longer retries. The background interaction completion test stays.
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): pin the background completion event order and name the innermost wrapper in the claim docstrings

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): send one bridged request and assert the inner Responses result is the logged one

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: kerry <kerry@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 157d96d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants