Skip to content

fix(proxy): traceparent/baggage fallback must not override caller metadata - #43020

Closed
fandujar wants to merge 5 commits into
BerriAI:mainfrom
fandujar:fix/traceparent-fallback-yields-to-caller-metadata
Closed

fandujar wants to merge 5 commits into
BerriAI:mainfrom
fandujar:fix/traceparent-fallback-yields-to-caller-metadata

Conversation

@fandujar

@fandujar fandujar commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • An explicit metadata.trace_id gets replaced by the traceparent header's trace id
  • Same for metadata.session_id and the baggage header
  • Some platforms inject traceparent on every request, so this hits every caller

How it solves it:

  • The header fallback only runs when the caller left the field empty
  • On Responses and Messages routes, ids the proxy promotes from metadata count too
  • Nothing changes for callers that don't set these fields

User Flow

Before: a caller that sets its own trace id can't find its trace in Langfuse

  1. They send POST https://litellm-domain/v1/chat/completions with "metadata": {"trace_id": "my-trace-id", "session_id": "my-session-id"}
  2. The request passes through a load balancer that adds a traceparent header, and comes back 200
  3. The trace shows up in Langfuse under a 32 character hex id and session baggage-session-42, not the ones they sent
  4. GET https://langfuse-host/api/public/traces/my-trace-id returns 404

After: the same request keeps the ids the caller chose

  1. They send the same POST https://litellm-domain/v1/chat/completions with the same metadata
  2. The request passes through the same load balancer and comes back 200
  3. The trace shows up in Langfuse as my-trace-id in session my-session-id
  4. A caller that sends no trace id or session id still gets the ones from the headers, as before

Affected release

Regression in v1.98.0, where the traceparent / baggage fallback was added

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • 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

Proxy started with litellm --config config.yaml --port 4000, real gpt-4o-mini completions on every call. Langfuse host pointed at a local ingestion endpoint that records the trace-create events the proxy sends, so the id and session id below are exactly what Langfuse would store. missing_session_id: reject is on so that a wrongly dropped session id would show up as a 400

model_list:
  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/UPSTREAM_KEY
      api_base: <OpenAI-compatible gateway>

litellm_settings:
  success_callback: ["langfuse"]

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  missing_session_id: reject

Every request sends the same two headers, which is what a load balancer that injects trace context would add:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
baggage: session.id=baggage-session-42

Before (d3462c6)

Caller sets trace_id and session_id

  1. curl http://localhost:4000/v1/chat/completions -H 'Authorization: Bearer sk-...' -H "$TRACEPARENT" -H "$BAGGAGE" -d '{"model":"gpt-4o-mini","max_tokens":5,"messages":[{"role":"user","content":"say pong"}],"metadata":{"trace_id":"my-trace-id","session_id":"my-session-id","trace_name":"case1"}}'
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case1"}

Caller sends an empty session_id

  1. curl http://localhost:4000/v1/chat/completions -H 'Authorization: Bearer sk-...' -H "$TRACEPARENT" -H "$BAGGAGE" -d '{"model":"gpt-4o-mini","max_tokens":5,"messages":[{"role":"user","content":"say pong"}],"metadata":{"session_id":"","trace_name":"case2"}}'
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case2"}

Responses API, caller sets trace_id and session_id

  1. curl http://localhost:4000/v1/responses -H 'Authorization: Bearer sk-...' -H "$TRACEPARENT" -H "$BAGGAGE" -d '{"model":"gpt-4o-mini","max_output_tokens":16,"input":"say pong","metadata":{"trace_id":"my-trace-id-3","session_id":"my-session-id-3","trace_name":"case3"}}'
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case3"}

Caller sets neither

  1. curl http://localhost:4000/v1/chat/completions -H 'Authorization: Bearer sk-...' -H "$TRACEPARENT" -H "$BAGGAGE" -d '{"model":"gpt-4o-mini","max_tokens":5,"messages":[{"role":"user","content":"say pong"}],"metadata":{"trace_name":"case4"}}'
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case4"}

After (c6fce25)

Caller sets trace_id and session_id

  1. Same curl as Before
  2. HTTP 200
  3. Sent to Langfuse: {"id": "my-trace-id", "sessionId": "my-session-id", "name": "case1"}

Caller sends an empty session_id

  1. Same curl as Before
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case2"}, the empty value still falls back to baggage

Responses API, caller sets trace_id and session_id

  1. Same curl as Before
  2. HTTP 200
  3. Sent to Langfuse: {"id": "my-trace-id-3", "sessionId": "my-session-id-3", "name": "case3"}

Caller sets neither

  1. Same curl as Before
  2. HTTP 200
  3. Sent to Langfuse: {"id": "4bf92f3577b34da6a3ce929d0e0e4736", "sessionId": "baggage-session-42", "name": "case4"}, unchanged

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Proof used a local ingestion endpoint, not a real Langfuse server
    • It records the same trace-create payload a real server receives
  • A caller who sets metadata.trace_id now keeps it over traceparent
    • Intended, but it does change which id wins for those callers

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

Note

Low Risk
Observability ID precedence change only; callers who omit ids still get header fallbacks, and explicit metadata wins as intended.

Overview
Fixes a proxy regression where W3C traceparent / baggage fallbacks overwrote caller-chosen trace and session ids in request metadata (often breaking Langfuse lookup when load balancers inject OTel headers).

Adds _caller_set_trace_field so header extraction and missing_session_id handling treat a field as caller-provided when it appears in the active metadata bucket (metadata or litellm_metadata), including promoted metadata.trace_id / session_id on Responses/Messages routes. traceparent / baggage are only applied per field when that field is unset or empty (empty values still fall back to headers).

Tests cover precedence (body vs headers, per-field steering, litellm_metadata empty-string fallback, missing_session_id: reject with baggage).

Reviewed by Cursor Bugbot for commit c6fce25. Bugbot is set up for automated code reviews on this repo. Configure here.

…adata

The W3C traceparent/baggage fallback in
add_litellm_metadata_from_request_headers documents itself as last-resort:

    Lower priority than everything above - only fires when neither the
    explicit litellm headers nor the Anthropic-metadata path found anything

But it guards on the top-level `litellm_trace_id` / `litellm_session_id` body
keys and never checks `metadata`, which is the documented way callers set
trace_id / session_id (`metadata: {"trace_id": ...}` on /chat/completions).
A caller that explicitly sets metadata.trace_id has it silently replaced by the
header value, so the implementation contradicts its own stated precedence.

This is not a corner case on managed platforms: GCP's front end injects a
traceparent into every inbound request, so the fallback fires on traffic whose
caller never sent the header. The request still returns 200 and the trace still
reaches the logging backend, just under an id the caller never chose, so any
caller correlating by its own id silently fails to find its trace.

Guard both fallbacks on the caller's request-body metadata as well.
Deliberately narrow:
- x-litellm-trace-id still outranks the body (documented priority BerriAI#1)
- a request that steers neither field still adopts traceparent/baggage exactly
  as before
- steering is per-field: setting only trace_id still lets session_id come from
  baggage
- litellm_metadata is checked too, for LITELLM_METADATA_ROUTES (/v1/responses,
  /v1/messages, batches, files)

Also corrects the comment, which understated the guard.

4 new tests; each fails without the source change. The existing traceparent and
baggage tests are unchanged and still pass.
@fandujar
fandujar requested a review from a team September 24, 2026 18:49
@CLAassistant

CLAassistant commented Sep 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding findings or new actionable issues remain.

Summary

The PR makes traceparent and baggage fallback only when the caller has not supplied a usable trace or session ID, including IDs promoted from metadata on Responses and Messages routes. It adds tests for precedence, empty values, and missing-session policy behavior.

Reviews (6) · Last reviewed commit: "fix(proxy): stay within the LIT006 cast ..."

Comment thread litellm/proxy/litellm_pre_call_utils.py Resolved
Comment thread litellm/proxy/litellm_pre_call_utils.py Resolved
Comment thread litellm/proxy/litellm_pre_call_utils.py Resolved
@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing fandujar:fix/traceparent-fallback-yields-to-caller-metadata (c6fce25) with main (c9e8a04)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (c2eb549) during the generation of this report, so c9e8a04 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

… values

Addresses review. The first version treated any value in either `metadata` or
`litellm_metadata` as caller steering. On LITELLM_METADATA_ROUTES the body
`metadata` is provider-facing and is only promoted later, so a session_id there
suppressed baggage before apply_missing_session_id_policy ran, and a request
with a usable baggage session id got a 400 under `missing_session_id: reject`.
An empty session_id did the same, since the policy treats "" as absent

Now only the active metadata container counts, and only a truthy value, which
matches how apply_missing_session_id_policy decides a session id is present.
The helper takes a typed `object` rather than a bare dict

Adds regression tests for both cases, including the end to end reject path,
and drops the test docstrings
@fandujar

Copy link
Copy Markdown
Contributor Author

@greptileai both P1s fixed in bae1322 with regression tests, and the description now has a live before and after run

Comment thread litellm/proxy/litellm_pre_call_utils.py Resolved
Addresses review. On LITELLM_METADATA_ROUTES the proxy promotes the caller's
trace control fields (trace_id, session_id, ...) from `metadata` into
`litellm_metadata`, but only after the header fallback runs. Checking only
`litellm_metadata` let traceparent and baggage fill those fields first, and the
promotion then skipped them because they were already set, so the trace was
recorded under the header ids

The check now also reads `metadata` for fields in
LITELLM_TRACE_CONTROL_METADATA_FIELDS on those routes, and
apply_missing_session_id_policy uses the same check, so `reject` no longer
refuses a request whose session id is about to be promoted

The earlier test asserting that a session_id in `metadata` must not block
baggage on /v1/responses had the premise wrong, since that value is promoted.
It is replaced by tests that assert the promoted caller ids win on
/v1/responses and /v1/messages, with no policy, reject, and generate
@fandujar

Copy link
Copy Markdown
Contributor Author

@greptileai the promotion P1 is fixed in c2eb718, and the live before and after run is updated to that commit

Comment thread litellm/proxy/litellm_pre_call_utils.py Resolved
…oted one

Addresses review. Promotion copies a trace control field from `metadata` into
`litellm_metadata` only when the key is absent, so a key that is present but
empty in `litellm_metadata` wins and the `metadata` value is never used. The
check still looked at `metadata` in that case, which let
`missing_session_id: reject` accept a request that ends up with an empty
session id, and let an empty trace_id or session_id block the headers

The check now follows the same rule as promotion. If the active container has
the key, its value decides. Only when the key is absent does the promoted
`metadata` value count. This makes the conflicting-bucket cases behave exactly
as on main
@fandujar

Copy link
Copy Markdown
Contributor Author

@greptileai the empty shadowing key P1 is fixed in 36f07c8 with regression tests, and the live run is updated

The type-discipline gate failed: this branch added 4 unsuppressed `cast()`
calls and LIT006 was already at its limit. Each cast now carries a
`# cast-ok` reason. The two in the helper follow an `isinstance` check that
proves the Mapping. The two at the call sites stay because the method's
`data` parameter is a bare `dict`, and dropping those casts adds
basedpyright unknown-type errors instead. No behavior change
@fandujar
fandujar force-pushed the fix/traceparent-fallback-yields-to-caller-metadata branch from ea35fb9 to c6fce25 Compare September 24, 2026 20:05
@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review latest head

@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit c6fce25. Configure here.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Thanks for the fix. It continues in #43688 with your commits and authorship intact, plus an integration test, so CircleCI can run on it

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.

3 participants