Skip to content

fix(logging): classify anthropic_messages as async so CustomLogger hooks fire exactly once - #33481

Closed
yucheng-berri wants to merge 5 commits into
litellm_internal_stagingfrom
litellm_lit4447_dd_dedupe
Closed

yucheng-berri wants to merge 5 commits into
litellm_internal_stagingfrom
litellm_lit4447_dd_dedupe

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

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

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 has success_callback: ["datadog"] plus cache: 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/messages call and one native gemini generateContent call each ship two events with one litellm_call_id:

curl -sS http://localhost:4447/v1/messages \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet-5","max_tokens":32,"messages":[{"role":"user","content":"Say only: MARKER-LIT4447-BEFORE-2"}]}'

POST#7 id=chatcmpl-c4a1d1d7-... call_type=anthropic_messages call_id=b42e4a24-... cost=0.000256 start=1784158824.23524
POST#8 id=chatcmpl-f6599a69-... call_type=anthropic_messages call_id=b42e4a24-... cost=0.000256 start=1784158824.23524

curl -sS "http://localhost:4475/v1beta/models/gemini-3.5-flash:generateContent" \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"contents":[{"parts":[{"text":"Say only: L4475-BEFORE-GEMINI"}]}]}'

POST#1 call_type=agenerate_content call_id=f0331010-...   <- immediate single-event POST (sync hook)
POST#2 call_type=agenerate_content call_id=f0331010-...   <- batched POST (async hook), same call id

After (this PR), the same calls plus /chat/completions, /v1/responses, and a streaming /v1/messages call:

POST#1 call_type=anthropic_messages call_id=da34efa6-...
POST#1 call_type=agenerate_content  call_id=75ac3afa-...
POST#1 call_type=acompletion        call_id=986c5a27-...
POST#2 call_type=anthropic_messages call_id=cbf7d8a8-...  <- streaming
duplicates: NONE - every call logged exactly once

LiteLLM_SpendLogs has 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) fires log_success_event exactly once, litellm.agenerate_content fires async_log_success_event exactly once. A further probe registers a CustomLogger subclass that overrides only log_success_event alongside a dual-hook logger in litellm.callbacks and calls litellm.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 callback

Type

🐛 Bug Fix

Changes

Every successful /v1/messages call shipped two log events to the DataDog intake, and the same held for gemini's native /generateContent route (reproduced above) and any other async entrypoint that plants no a* flag. _is_sync_litellm_request classified async requests by looking for one of six per-entrypoint flags in litellm_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 by cache: true) opened handle_sync_success_callbacks_for_async_calls, each CustomLogger's sync log_success_event fired on top of async_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 flag

The fix records the answer where it is known instead of reconstructing it downstream: the @client decorator already selects the sync or async wrapper from is_async_callable(original_function), so each wrapper now stamps logging_obj.is_async_entrypoint on the logging object it runs, and _is_sync_litellm_request reads the recorded bit. The a* 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 @client function with the shared logging object, which is exactly what agenerate_content does when delegating to generate_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 how call_type and stream are already recorded on the logging object at creation

Deduplicating alone would silence a custom integration that overrides only the sync hooks, because the base CustomLogger async 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_calls also 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 open

The PR's first commit fixed anthropic_messages with 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 approach

Behavior 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 gemini generateContent; the same correction applies to every other async @client entrypoint

A 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 (acompletion and 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 direction

Sync entrypoints are unchanged (the stamp agrees with what the flag heuristic already said for them; sync generate_content was probe-verified to keep firing its sync hook exactly once). Logging objects created outside @client keep the flag-based classification byte-for-byte. LiteLLM_SpendLogs rows, response bodies, and cost headers are unchanged

When 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 docstring

QA runbook

  1. Start a proxy with an anthropic model, a gemini model, success_callback: ["datadog"], cache: true, and env DD_API_KEY=<any>, DD_SITE=datadoghq.com, DD_BASE_URL=<local sink URL>
  2. POST one non-streaming /v1/messages, one /v1beta/models/<gemini-model>:generateContent, one /chat/completions, and one streaming /v1/messages request
  3. Confirm the sink receives exactly one log event per call (match on litellm_call_id in the event message payload)
  4. Call litellm.google_genai.generate_content (sync SDK) with a CustomLogger registered and confirm log_success_event still fires once
  5. Register a CustomLogger subclass that overrides only log_success_event as the only callback in litellm.callbacks, call litellm.anthropic_messages, and confirm the sync hook fires exactly once

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/litellm_logging.py 96.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@veria-ai

veria-ai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This pull request adjusts LiteLLM logging behavior so anthropic_messages is treated as an async path and CustomLogger hooks are invoked consistently without duplicate firing. The touched logging code determines which custom logger hook path runs for success and streaming events.

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

@codspeed

codspeed Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit4447_dd_dedupe (c1a0c96) with litellm_internal_staging (fba7ac4)

Open in CodSpeed

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a double-logging bug where async SDK entrypoints that don't set one of the six recognized a* flags in litellm_params (notably anthropic_messages and agenerate_content) were misclassified as sync requests. The misclassification caused both log_success_event and async_log_success_event to fire on the same call for integrations implementing both hooks (e.g. DataDog, Langsmith).

  • Introduces is_async_entrypoint: Optional[bool] on the Logging object, stamped directly by the @client wrapper (sync → False, async → True) with a "first-wins" rule that prevents nested sync delegates (like generate_content inside agenerate_content) from flipping the bit back.
  • _is_sync_litellm_request now reads is_async_entrypoint as the authoritative source, falling back to the existing a*-flag heuristic only for logging objects constructed outside @client (proxy passthrough, realtime, MCP).
  • Adds _custom_logger_has_only_sync_success_hooks / _custom_logger_has_only_sync_failure_hook helpers so that integrations that override only the sync hooks still receive exactly one event per call via the fallback sync dispatch, even on async routes.

Confidence Score: 5/5

Safe 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 @client retain exactly the same flag-based classification as before. The first-wins guard correctly handles nested sync-within-async delegation. Tests directly exercise the DataDog double-fire scenario, the sync-only-logger fallback, the executor dispatch gate, and the nested-stamp preservation, matching the live repro described in the PR. No correctness issues were identified.

No files require special attention.

Important Files Changed

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

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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)

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

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.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…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
… 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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

1 similar comment
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri
yucheng-berri force-pushed the litellm_lit4447_dd_dedupe branch from 9b0852c to 57fd658 Compare July 16, 2026 19:01
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri
yucheng-berri force-pushed the litellm_lit4447_dd_dedupe branch from 57fd658 to 089187b Compare July 16, 2026 19:24
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 = (

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.

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.

…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>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ yucheng-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

1 similar comment
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ yucheng-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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

@yucheng-berri
yucheng-berri deleted the litellm_lit4447_dd_dedupe branch July 17, 2026 23:06
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