Skip to content

fix(logging): stamp request async-ness at the client wrapper so async entrypoints never double-log - #33496

Merged
yucheng-berri merged 2 commits into
litellm_lit4447_dd_dedupefrom
litellm_lit4475_async_entrypoint
Jul 16, 2026
Merged

yucheng-berri merged 2 commits into
litellm_lit4447_dd_dedupefrom
litellm_lit4475_async_entrypoint

Conversation

@yucheng-berri

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

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

Stacked on #33481. Live proxy on localhost:4475 (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)

Before (base of this PR, i.e. with only the #33481 call-type guard), one native gemini call double-logs; this upgrades LIT-4475 from suspected to reproduced:

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=anthropic_messages call_id=afaea9dd-...  <- /v1/messages control, exactly one
POST#2 call_type=agenerate_content call_id=f0331010-...   <- batched POST (async hook), same call id
counts: {agenerate_content/f0331010: 2, anthropic_messages/afaea9dd: 1}

After (this PR), the same calls plus a /chat/completions control 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 throughout (the duplicate-request_id group-by returns zero rows). SDK-level probes confirm the sync entrypoint keeps its sync hook: litellm.google_genai.generate_content (sync) fires log_success_event exactly once, litellm.agenerate_content fires async_log_success_event exactly once

Type

🐛 Bug Fix

Changes

Follow-up to #33481, which fixed the async-request misclassification for anthropic_messages with a call-type guard. This PR replaces that guard with the general mechanism so every async-only entrypoint is classified correctly, including the agenerate_content sibling that this PR reproduces live

The @client decorator already knows whether a request is sync or async; it selects wrapper or wrapper_async from is_async_callable(original_function). Each wrapper now records that fact on the logging object it runs (logging_obj.is_async_entrypoint), and _is_sync_litellm_request reads the recorded bit instead of guessing from an allowlist of a* flags in litellm_params. The flag heuristic remains only as a fallback for logging objects constructed outside @client (passthrough, realtime). The anthropic_messages call-type guard from #33481 is deleted; the bit covers it

The stamp is first-wins: an async entrypoint that internally invokes a sync @client function with the shared logging object (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 is the same pattern the logging object already uses for call_type and stream: a fact the wrapper knows at entry, recorded at creation, read downstream. It replaces the per-entrypoint flag planting (acompletion, aresponses, async_call) whose forget-one-flag failure mode produced LIT-4192, LIT-4447, and LIT-4475

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 agenerate_content (gemini native route) and /v1/messages; the same correction applies to any other async @client entrypoint without a flag. As in #33481, a custom integration implementing only the sync hooks stops receiving events for those async entrypoints; that profile was already unsupported on every flagged async route

Sync entrypoints are unchanged: the sync wrapper stamps false, which matches what the flag heuristic already said for them, and 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 (the bit stays unset). Spend rows, response bodies, and cost headers are unchanged

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

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

… 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
@greptile-apps

greptile-apps Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes double-logging for async-only entrypoints (e.g., agenerate_content, anthropic_messages) by stamping a is_async_entrypoint bit on the shared Logging object at the @client wrapper boundary, using first-wins semantics to survive nested sync-inside-async delegation. It supersedes the narrow anthropic_messages call-type guard from #33481 with a general mechanism.

  • Adds is_async_entrypoint: Optional[bool] = None to Logging.__init__; the sync wrapper stamps False and wrapper_async stamps True, each only when the bit is currently None (first-wins prevents the inner sync wrapper from flipping the bit back).
  • _is_sync_litellm_request is converted from @staticmethod to an instance method that reads the stamped bit first, falling back to the existing a*-flag heuristic for logging objects constructed outside @client (passthrough, realtime, MCP).
  • All three call-sites of the method (dispatch_success_handlers, streaming_handler.py, success_handler/failure_handler) and all affected tests are updated to use the instance method signature.

Confidence Score: 5/5

Safe to merge; the change is well-scoped to the logging dispatch path and does not touch request routing, auth, or cost calculation.

The first-wins stamp on is_async_entrypoint correctly fixes the double-log for nested async-over-sync delegation. All three call-sites of _is_sync_litellm_request are updated, the fallback heuristic is preserved for out-of-@client logging objects, and the new end-to-end tests guard against dispatch regressions.

No files require special attention.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/litellm_logging.py Adds is_async_entrypoint field and converts _is_sync_litellm_request to instance method; all three call-sites updated correctly; fallback heuristic preserved for out-of-@client logging objects.
litellm/utils.py Stamps is_async_entrypoint = False in sync wrapper and True in wrapper_async, both guarded by if logging_obj.is_async_entrypoint is None for correct first-wins behavior.
litellm/litellm_core_utils/streaming_handler.py Single call-site update: _is_sync_litellm_request(litellm_params) without call_type kwarg; straightforward and correct.
tests/test_litellm/litellm_core_utils/test_litellm_logging.py Test suite updated to instance-method signature; two new end-to-end tests added covering flagless-call-type dedup and first-wins nested-delegation; existing tests correctly updated with explicit is_async_entrypoint = True setup.
tests/test_litellm/passthrough/test_passthrough_main.py Static-method call replaced by constructing a fresh LitellmLogging (with is_async_entrypoint=None) to exercise the flag fallback path; correctly verifies allm_passthrough_route still classifies as async.
tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py Minimal change: static-method call updated to instance-method call on an already-existing logging_obj; semantics unchanged.

Reviews (2): Last reviewed commit: "test(logging): assert exactly-once async..." | Re-trigger Greptile

…c-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

The gap named in the review is addressed by 7e96d77: test_client_wrapper_stamp_is_first_wins_across_nested_calls now registers a recording CustomLogger with the executor sync dispatch open around the nested async-outer/sync-inner call and asserts events == ["async"], i.e. exactly one async hook and zero sync hooks for the agenerate_content-style delegation pattern, with a deterministic executor drain instead of a sleep. The suggestion in the review (assert no sync callbacks fired during the nested call, not just the bit value) is implemented verbatim in that commit

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

The fix in 7e96d77 is exactly what was needed. Looking at the updated test:

  1. Sync dispatch is open: _gate_opener in success_callback keeps the executor path live, so a sync-dispatch escape would show up in events
  2. Bit assertion: observed == {"inner_bit": True, "outer_bit_after_inner": True} confirms first-wins survives the nested call
  3. Hook count assertion: events == ["async"] verifies exactly one async fire with zero sync fires — the original gap is closed
  4. Standalone sanity check: the follow-up fake_inner_sync(...) + observed["inner_bit"] is False confirms the sync wrapper correctly stamps its own unshared logging object
  5. Deterministic drain: executor.submit(lambda: None).result() replaces the sleep, eliminating the race between assertion and executor thread

This kills all three sync-stamp mutants. LGTM.

@yucheng-berri
yucheng-berri merged commit f4494e6 into litellm_lit4447_dd_dedupe Jul 16, 2026
41 of 72 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_lit4475_async_entrypoint branch July 16, 2026 03:58
@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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.

1 participant