Repository navigation
chore(release): backport #44508 to stable/1.102.x and cut 1.102.4 - #45215
Conversation
…chat to Responses bridge (#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 #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)
|
| super().__init__() | ||
| self.logged_results: list[object] = [] | ||
|
|
||
| async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None: |
There was a problem hiding this comment.
The new callback and helper parameters are untyped in both test files, and calls lacks Final. CLAUDE.md requires strongly typed parameters and Final variables. Add the missing annotations before merging
Context Used: CLAUDE.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!
| first: Final = asyncio.create_task(logging_obj.async_success_handler(result=in_progress)) | ||
| await in_progress_parked.wait() | ||
| completion: Final = asyncio.create_task(logging_obj.async_log_background_interaction_completion(result=completed)) |
There was a problem hiding this comment.
Settlement test skips the claim
The initial handler runs directly, so claim_async_success_log never sets the new flag. This test would still pass if settlement were wrongly dropped whenever that flag was set. Claim the initial log before parking its handler to cover that state
Knowledge Base Used: Logging callbacks and telemetry
TLDR
Problem this solves:
openai/responses/*models log twice on 1.102.xHow it solves it:
User 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
Backports #44508 (fixes #44500) from main onto stable/1.102.x and bumps the line to 1.102.4. The bug is present on 1.102.x: the success handler checks its "already logged" flag, then awaits the large-message offload, and only sets the flag afterwards, so both nested wrappers log the same request
What is included
Adaptation notes
#44508 is adapted, not verbatim. 1.102.x predates
_schedule_async_success_logging(added on main later by 22b377f, which is on 1.103.x and up), so the claim is called inline in the line's_dispatch_success_logginginstead. It guards only the immediate (non-deferred) branch. The deferred branch, used when a post-call guardrail holds logging until after the guardrail runs, is left exactly as 1.102.x ships it: that path already logs once, and moving it to the inner result belongs to 22b377f, which this PR does not backportclaim_async_success_logand_async_success_scheduledare copied verbatim intoLogging, placed beforehas_run_logging(main renamed itmark_logging_complete)The two unit tests moved from
tests/unit/totests/test_litellm/, which is where this line keeps them; only the PR's own test hunks were taken. The integration testtests/integration/spend/test_responses_bridge_spend_once.pyis dropped because thetests/integration/_supportharness it imports does not exist on 1.102.x. The live proxy run below covers the same assertions (one spend row, key charged once, the row is the inner Responses result)test_background_interaction_completion_logs_while_in_progress_handler_is_parkedis upstream's own test and is kept as is. On this line it passes with or without the fix, since background completion calls the success handler directly and never goes through the claim, so it guards against a future regression rather than proving this changeKnown noise on this line
These fail on the untouched stable/1.102.x tip too and are unrelated (model capability lookups):
tests/test_litellm/test_utils.py::TestProxyFunctionCalling::test_proxy_function_calling_support_consistency(groq/gemma-7b-it, groq/llama-3.3-70b-versatile)tests/test_litellm/test_utils.py::test_supports_function_calling_github_anthropic_aliastests/test_litellm/test_utils.py::test_supports_tool_choice_simple_testsWith the pick, the two mapped files go from 4 failed / 671 passed to 4 failed / 673 passed. The new
test_nested_wrapper_exits_schedule_one_async_success_logfails (assert 2 == 1) with the claim removed from_dispatch_success_loggingPre-Submission checklist
uv run pytest tests/test_litellm/<your_test_file>.py -vScreenshots / Proof of Fix
Adversarial review (gauntlet-mini, 5 lenses, 13 min) returned SURVIVED with 0 confirmed regressions. Its own runs reproduced the double log without the fix (2 events, 3 of 3 runs) and one inner
ResponsesAPIResponseevent with it, and found the same log counts with and without the fix for small requests, streaming, plain chat, retries, fallbacks, sync calls and cache hits. The new nested-wrapper test kills 5 of 5 mutants of the claimShared setup: the worktree's own proxy (
python litellm/proxy/proxy_cli.py --config config.yaml) backed by a fresh Postgres, real OpenAI calls, and this config:small.jsonis a ~2,000-char prompt andlarge.jsona ~300,000-char prompt (random words plus "Reply OK"), both{"model": "luna-bridge", "messages": [{"role": "user", "content": "..."}]}with no streamingBefore (d174b05)
Small prompt
curl -s http://localhost:4061/key/generate -H 'Authorization: Bearer sk-bp44508-master' -d '{"key_alias":"bp44508-base"}'returns a new keycurl -s http://localhost:4061/v1/chat/completions -H "Authorization: Bearer $KEY" -d @small.jsonreturnsOK, 334 prompt tokens,x-litellm-response-cost: 8.96e-05LiteLLM_SpendLogsrow for it at8.96e-05Large prompt
curl -s http://localhost:4061/v1/chat/completions -H "Authorization: Bearer $KEY" -d @large.jsonreturnsOK, 48705 prompt tokens,x-litellm-response-cost: 0.0121821LiteLLM_SpendLogsrows for the one request, both at0.0121821: one with the raw upstream idresp_09ff5d8c..., one with the encoded idresp_bGl0ZWxsbTpj...select key_alias, spend from "LiteLLM_VerificationToken"showsbp44508-base | 0.0244538, which is 8.96e-05 + 2 x 0.0121821, so the large request was charged twiceAfter (346cbb9)
Small prompt
curl -s http://localhost:4061/key/generate -H 'Authorization: Bearer sk-bp44508-master' -d '{"key_alias":"bp44508-after"}'returns a new keycurl -s http://localhost:4061/v1/chat/completions -H "Authorization: Bearer $KEY" -d @small.jsonreturnsOK, 334 prompt tokens,x-litellm-response-cost: 7.28e-05LiteLLM_SpendLogsrow for it at7.28e-05Large prompt
curl -s http://localhost:4061/v1/chat/completions -H "Authorization: Bearer $KEY" -d @large.jsonreturnsOK, 48705 prompt tokens,x-litellm-response-cost: 0.00098064LiteLLM_SpendLogsrow for the request at0.00098064, with the encoded idresp_bGl0ZWxsbTpj..., so the inner Responses result is the one loggedselect key_alias, spend from "LiteLLM_VerificationToken"showsbp44508-after | 0.00105344, which is exactly 7.28e-05 + 0.00098064, so each request was charged onceThe per-request cost is lower in After because OpenAI served the repeated prompt from its cache; the row and charge counts are the signal
Type
🐛 Bug Fix
✅ Test
Caveats (if any)
Medium
Low
Final Attestation