Repository navigation
fix(logging): log spend once for large non-streaming requests on the chat to Responses bridge - #44508
Conversation
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
|
bugbot run |
| messages=messages, | ||
| stream=False, | ||
| call_type="acompletion", | ||
| start_time=time.time(), |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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
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>
85a307e to
1205176
Compare
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
… innermost wrapper in the claim docstrings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…onses result is the logged one Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@hektorjg thank you for contributing! |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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.
| await asyncio.sleep(0) | ||
| return await real_truncate(messages) | ||
|
|
||
| monkeypatch.setattr(litellm_logging, "truncate_base64_in_messages_async", yielding_truncate) |
There was a problem hiding this comment.
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!
| """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.""" |
There was a problem hiding this comment.
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!
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
chore(release): backport #44508 to stable/1.102.x and cut 1.102.4
…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)
…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 [#​44243](BerriAI/litellm#44243) and [#​44508](BerriAI/litellm#44508) to stable/1.105.x for v1.105.1 by [@​kerry-berri](https://github.com/kerry-berri) in [#​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
…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)

TLDR
Problem this solves:
openai/responses/*models are logged twiceHow it solves it:
@clientwrapper claims the async success log on the sharedLoggingobject, synchronously, before any task is created (claim_async_success_loginlitellm_logging.py, called from_schedule_async_success_logginginutils.py). It always exits first because the outer wrapper is awaiting it. The outer wrapper then getsFalseand schedules nothing, so one request queues exactly one success handler and it carries the provider-shaped result. There is noawaitbetween the check and the decision, so no lock is neededrequest_idis the inner Responses result's encoded id, so the provider-shaped result is the one loggedLoggingobject, driven through the logging worker with a yielding base64 offload, log once and log the inner provider-shaped result. It fails without the claimUser Flow
Before: a developer sends one large chat request and is billed twice in LiteLLM's own accounting
openai/responses/gpt-5.6-lunamodel with ~300k characters of message text, no streamingAfter: the same request is logged once
Relevant issues
Fixes #44500
Affected release
Regression since v1.102.0
Pre-Submission checklist
misc,rust-wheelandproxy-infra-rootjobs fail on main too, from theSpendLogRecord.provider_request_idand tracing fixture errors)Screenshots / Proof of Fix
SDK-level, real calls to
openai/responses/gpt-5.6-lunavialitellm.acompletion(non-streaming), with aCustomLoggercountingasync_log_success_eventperlitellm_call_id. Prompts are random words plus "Reply OK".Before (6532dcb)
ResponsesAPIResponse)ModelResponse,ResponsesAPIResponse) for the samelitellm_call_idAfter (6532dcb + this change)
ResponsesAPIResponse)ResponsesAPIResponse)ResponsesAPIResponse)The logged result is the inner, provider-shaped
ResponsesAPIResponsein every case: the inner wrapper exits first, so it is the one that claims the logProxy-level:
tests/integration/spend/test_responses_bridge_spend_once.pysends one 300,000-char non-streaming chat request to anopenai/responses/deployment through a real proxy with Postgres. Withlitellm_logging.pyreverted to 6532dcb it fails with twoLiteLLM_SpendLogsrows for onelitellm_call_id; with this change it writes one row whoserequest_iddecodes to the upstream Responses id, and the key is charged onceType
🐛 Bug Fix
✅ Test
Caveats (if any)
Medium
@clientwrapper exit path changes. Callers that invokeasync_success_handlerdirectly (cache hits, streaming, background interaction completion) are not affected by the claimNote
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
@clientwrappers (e.g. chat completions over the OpenAI Responses bridge), where two wrapper exits shared oneLoggingobject and both could enqueue async success handlers beforehas_logged_async_successwas 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 asasync_success_handlerand background interaction completion are unchanged.Adds an integration test asserting one
LiteLLM_SpendLogsrow 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.