Repository navigation
fix(logging): classify anthropic_messages as async so CustomLogger hooks fire exactly once - #33481
yucheng-berri wants to merge 5 commits into
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
PR overviewThis pull request adjusts LiteLLM logging behavior so One logging edge case remains open: mixed custom logger implementations can be misclassified, causing the selected streaming hook to be skipped while the fallback is also bypassed. In deployments using affected custom audit loggers, an authenticated streaming request could avoid being recorded by that logger. One issue has already been addressed, so the remaining risk is narrow and tied to specific logger configurations rather than broad request handling. Open issues (1)
Fixed/addressed: 1 · PR risk: 4/10 |
Greptile SummaryThis PR fixes a double-logging bug where async SDK entrypoints that don't set one of the six recognized
Confidence Score: 5/5Safe to merge — the change is well-scoped, every altered code path is guarded by the first-wins stamp, and all production callers of the promoted instance method were already using instance-call syntax. The stamp mechanism is minimal and additive: logging objects that have never passed through No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/litellm_logging.py | Core logging class gains is_async_entrypoint attribute; _is_sync_litellm_request promoted to instance method with authoritative stamp check; sync dispatch gate and per-callback conditions updated to support sync-only CustomLoggers — all changes are logically correct. |
| litellm/utils.py | Sync and async @client wrappers stamp logging_obj.is_async_entrypoint using a first-wins guard (is None check), correctly preserving the outer async stamp when nested sync calls reuse the same logging object. |
| tests/test_litellm/litellm_core_utils/test_litellm_logging.py | Extensive new tests cover: stamp propagation, deduplication for dual-hook loggers, sync-only logger fallback delivery, gate behavior, end-to-end executor dispatch, and the first-wins nested call scenario — existing tests updated to use instance method calls. |
| tests/test_litellm/passthrough/test_passthrough_main.py | Test updated to create a fresh LitellmLogging instance (is_async_entrypoint=None) to verify the flag-based fallback still classifies passthrough routes as async — coverage unchanged. |
| tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py | Single assertion updated from static method call to instance method call — semantically equivalent with is_async_entrypoint=None, coverage unchanged. |
Reviews (7): Last reviewed commit: "fix(logging): tolerate logging stubs wit..." | Re-trigger Greptile
|
Re the P2 (other async-only call types still misclassified): agreed, and that surface is deliberately out of scope here per one-scenario-one-PR. It is tracked in LIT-4475 with the audit list (agenerate_content, arerank, amoderation, aspeech, aocr, asearch, a2a asend_message, video/container call types), the repro recipe (DD_BASE_URL recording sink plus a legacy string callback such as the cache callback to open the sync dispatch), and the agreed fix shape: reproduce each call type live first, then either add it to the classifier guard or plumb its flag through litellm_params like aresponses does. The anthropic_messages path fixed here is the only one with a live-verified repro today; the fix was verified end to end on a live proxy (exactly one intake event on /v1/messages non-streaming and streaming, controls unchanged, spend logs exactly-once throughout) |
|
Acknowledged — the scoping is reasonable and the LIT-4475 tracking (with the full audit list and the live-repro-first requirement before adding to the classifier) is exactly the right way to handle it. No further objection on that point from this PR's perspective. |
…oks fire exactly once Async /v1/messages requests set no a* flag in litellm_params, so _is_sync_litellm_request classified them as sync and the executor-run sync success_handler fired CustomLogger.log_success_event on top of async_log_success_event, shipping two DataDog intake events per call with the same litellm_call_id. The classifier now takes the call type and returns false for anthropic_messages, whose logged SDK entrypoint is async-only; the failure path and streaming gates get the same treatment. Sibling async-only call types are tracked in LIT-4475. Resolves LIT-4447
780b640 to
9d985c8
Compare
… entrypoints never double-log (#33496) * fix(logging): stamp request async-ness at the client wrapper so async entrypoints never double-log The a* flag allowlist in _is_sync_litellm_request required every async entrypoint to plant its own flag in litellm_params; entrypoints that forgot (anthropic_messages, agenerate_content) were misclassified as sync and fired CustomLogger sync hooks on top of the async ones. The client decorator already knows which wrapper ran, so each wrapper now records logging_obj.is_async_entrypoint (first-wins across nested client calls sharing a logging object; agenerate_content delegates to the sync generate_content wrapper mid-request) and the classifier reads the recorded bit, keeping the flag heuristic only for logging objects built outside the client decorator. Replaces the anthropic_messages call-type guard from the previous commit. Resolves LIT-4475 * test(logging): assert exactly-once async dispatch for the nested async-outer sync-inner wrapper flow Extends the first-wins regression test to also count CustomLogger hook firings with the executor sync dispatch open, per review feedback on the PR; kills the sync-stamp mutants
…vents exactly once
1 similar comment
9b0852c to
57fd658
Compare
57fd658 to
089187b
Compare
| def _custom_logger_has_only_sync_success_hooks(callback: CustomLogger) -> bool: | ||
| """True when the logger class overrides a sync success hook but no async success hook.""" | ||
| cls = type(callback) | ||
| has_async = ( |
There was a problem hiding this comment.
Low: Mixed custom logger hooks can bypass logging
This combines success and stream overrides into one capability check. For example, a logger implementing log_stream_event and async_log_success_event is considered async-capable for streaming, but the async path invokes its inherited no-op async_log_stream_event and the sync fallback skips log_stream_event. An authenticated caller can select streaming and keep the request out of that custom audit logger. Determine fallback eligibility independently for the hook selected by the current request mode.
6490585 to
089187b
Compare
…m_logger_hooks sweep flag (#33577) The async success/failure paths run the sync handler only to service legacy sync-only callbacks (langfuse, s3, sync-only CustomLoggers), so thread run_custom_logger_hooks=False from the two async sync-sweep sites (dispatch_success_handlers, handle_sync_success_callbacks_for_async_calls) and the async wrapper failure path. That suppresses the sync CustomLogger hook and the standard/openmeter emitters the async handler already ran, closing the anthropic_messages double-log without depending on the a* request classifier Replaces the is_async_entrypoint wrapper stamp, which required mutable per-request state and broke duck-typed logging stubs in CI Co-authored-by: yucheng <yucheng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
|
1 similar comment
|
|
|
Closing as superseded. The double logging for anthropic_messages and generate_content was fixed on litellm_internal_staging by #33589 using the existing litellm_params marker convention. The remaining pieces this PR carried (wrapper-level async classification and the sync-only CustomLogger fallback) can be revisited separately if the flag approach needs generalizing |
Relevant issues
Linear ticket
Resolves LIT-4447
Resolves LIT-4475
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)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 (real Postgres, real Anthropic and Gemini APIs), DataDog logs intake redirected to a local recording sink via
DD_BASE_URL; config hassuccess_callback: ["datadog"]pluscache: true(the cache setting registers the legacy"cache"string callback that opens the sync dispatch for async calls; the e2e compose stack that surfaced LIT-4447 has it too)Before, one non-streaming
/v1/messagescall and one native geminigenerateContentcall each ship two events with onelitellm_call_id:After (this PR), the same calls plus
/chat/completions,/v1/responses, and a streaming/v1/messagescall:LiteLLM_SpendLogshas exactly one row per request before and after (spend tracking is async-only and was never double-counted; the duplicate-request_id group-by returns zero rows). SDK probes confirm sync entrypoints keep their sync hook:litellm.google_genai.generate_content(sync) fireslog_success_eventexactly once,litellm.agenerate_contentfiresasync_log_success_eventexactly once. A further probe registers a CustomLogger subclass that overrides onlylog_success_eventalongside a dual-hook logger inlitellm.callbacksand callslitellm.anthropic_messages: the sync-only logger fires its sync hook exactly once via the fallback and the dual-hook logger fires its async hook exactly once. The same holds when the sync-only logger is the only registered callbackType
🐛 Bug Fix
Changes
Every successful
/v1/messagescall shipped two log events to the DataDog intake, and the same held for gemini's native/generateContentroute (reproduced above) and any other async entrypoint that plants noa*flag._is_sync_litellm_requestclassified async requests by looking for one of six per-entrypoint flags inlitellm_params(acompletion,aresponses,aembedding,aimage_generation,atranscription,allm_passthrough_route); entrypoints that never plant a flag were misclassified as sync, so whenever a legacy string callback (for example the"cache"callback registered bycache: true) openedhandle_sync_success_callbacks_for_async_calls, each CustomLogger's synclog_success_eventfired on top ofasync_log_success_event, building the payload twice (hence the differing synthetic completion ids in the ticket forensics). Twelve integrations implement both hooks (datadog, langsmith, opik, braintrust, deepeval, newrelic, posthog, argilla, lago, literal_ai, mlflow, openmeter) and the failure path is symmetric. This is the same defect class as LIT-4192, which patched it for one more call type by planting one more flagThe fix records the answer where it is known instead of reconstructing it downstream: the
@clientdecorator already selects the sync or async wrapper fromis_async_callable(original_function), so each wrapper now stampslogging_obj.is_async_entrypointon the logging object it runs, and_is_sync_litellm_requestreads the recorded bit. Thea*flag heuristic remains only as a fallback for logging objects constructed outside@client(proxy passthrough endpoints, realtime, MCP). The stamp is first-wins: an async entrypoint that internally invokes a sync@clientfunction with the shared logging object, which is exactly whatagenerate_contentdoes when delegating togenerate_content, keeps its async classification; without first-wins the inner sync wrapper flips the bit back and the gemini double-log survives, which is how the live repro caught it. This mirrors howcall_typeandstreamare already recorded on the logging object at creationDeduplicating alone would silence a custom integration that overrides only the sync hooks, because the base
CustomLoggerasync hooks are no-ops rather than delegating to their sync counterparts; such integrations relied on the misclassification to receive anything on the affected routes. The sync dispatch gates therefore fall back to the sync hook when the logger's class overrides a sync hook without the matching async one (_custom_logger_has_only_sync_success_hooks,_custom_logger_has_only_sync_failure_hook), so sync-only integrations keep exactly one event per call while dual-hook integrations like datadog deliver via the async hook only. The executor gate_should_run_sync_callbacks_for_async_callsalso counts a sync-only CustomLogger as a reason to run the sync dispatch, since that dispatch is the logger's only delivery path; previously it stripped every CustomLogger instance, which made delivery depend on an unrelated string callback keeping the gate openThe PR's first commit fixed
anthropic_messageswith a call-type guard in the classifier; the second commit (reviewed as its own stacked PR, #33496) replaces that guard with the general mechanism, so the final diff contains only the wrapper-stamp approachBehavior changes
Async-only entrypoints that set no
a*flag stop double-firing CustomLogger hooks; they now deliver via the async hooks exactly once, matching/chat/completions. Verified live for/v1/messages(non-streaming and streaming) and geminigenerateContent; the same correction applies to every other async@cliententrypointA custom integration that overrides only the sync hooks (no async overrides at the class level; hooks attached to an instance do not count) keeps receiving events for async requests through the existing sync dispatch, exactly once per call. The dispatch gate itself now counts such a logger, so delivery no longer depends on an unrelated legacy string callback holding the gate open, and because the fallback is uniform across call types these integrations also start receiving events on flagged async routes (
acompletionand friends) where they previously received nothing. Failure delivery is symmetric. Integrations that override an async hook are untouched and keep exactly-once delivery via async. Final responses of streamed requests still do not reach sync-only integrations on these routes; the sync handler has always skipped once the streamed response was assembled by the async path (probe-verified on the pre-fix base), and this PR changes that in neither directionSync entrypoints are unchanged (the stamp agrees with what the flag heuristic already said for them; sync
generate_contentwas probe-verified to keep firing its sync hook exactly once). Logging objects created outside@clientkeep the flag-based classification byte-for-byte.LiteLLM_SpendLogsrows, response bodies, and cost headers are unchangedWhen this merges, the e2e assertion in
tests/e2e/logging/test_datadog_log_e2e.py(PR #33415) that tolerates same-call-id duplicates should be tightened to exactly one event, per the note in that test's docstringQA runbook
success_callback: ["datadog"],cache: true, and envDD_API_KEY=<any>,DD_SITE=datadoghq.com,DD_BASE_URL=<local sink URL>/v1/messages, one/v1beta/models/<gemini-model>:generateContent, one/chat/completions, and one streaming/v1/messagesrequestlitellm_call_idin the eventmessagepayload)litellm.google_genai.generate_content(sync SDK) with a CustomLogger registered and confirmlog_success_eventstill fires oncelog_success_eventas the only callback inlitellm.callbacks, calllitellm.anthropic_messages, and confirm the sync hook fires exactly onceFinal Attestation