Skip to content

fix(proxy): honor caller litellm_session_id in spend log session_id - #40856

Closed
deepanshupal wants to merge 14 commits into
BerriAI:litellm_internal_stagingfrom
deepanshupal:fix/spendlog-session-id
Closed

deepanshupal wants to merge 14 commits into
BerriAI:litellm_internal_stagingfrom
deepanshupal:fix/spendlog-session-id

Conversation

@deepanshupal

Copy link
Copy Markdown
Contributor

Summary

Fixes #40851.

When a caller passes litellm_session_id, the spend log's session_id was still taken from the per-call trace id (standard_logging_payload.trace_id, then litellm_trace_id, then a fresh uuid), so LiteLLM_SpendLogs.session_id never reflected the caller's session and grouping/filtering by session was broken.

The default path of _get_session_id_for_spend_log never consulted kwargs["litellm_session_id"]. Preferring it is safe: when the caller sends no session, get_litellm_params only derives it from session_id/trace_id, so the returned value equals the trace id that won before - sessionless requests are unchanged, and a real caller session now reaches the spend log.

Deliberate behavior preserved: the omit policy still honors only metadata.session_id (the Langfuse key), and the batch lifecycle's deterministic batch-id session still outranks everything so the create row and the poller's cost row stay grouped.

Testing

  • tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py: 226 passed, including 2 new tests (caller session wins over the per-call trace id; batch session still outranks a caller session).

Prepared with AI assistance; testing and review by me.

mateo-berri and others added 2 commits September 9, 2026 20:37
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
@deepanshupal
deepanshupal requested a review from a team September 12, 2026 13:37
@CLAassistant

CLAassistant commented Sep 12, 2026 •

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.
3 out of 4 committers have signed the CLA.

✅ mateo-berri
✅ yuneng-berri
✅ deepanshupal
❌ yassin-berriai
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing DeepanshuPal:fix/spendlog-session-id (e1730f3) with litellm_internal_staging (c2c2a62)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR updates spend-log session selection so explicit session IDs take precedence while preserving omit-policy and batch behavior

  • Prefers litellm_session_id over per-request trace IDs
  • Keeps deterministic batch session IDs at the highest non-omit precedence
  • Adds focused tests for caller and batch precedence

Confidence Score: 4/5

The behavior change is low risk, but the explicit comment-policy violation must be fixed before merging

The precedence logic handles valid caller sessions and batch grouping correctly, though empty sessions can suppress trace grouping and unnecessary docstrings violate repository guidance

Files Needing Attention: litellm/proxy/spend_tracking/spend_tracking_utils.py, tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py

Important Files Changed

Filename Overview
litellm/proxy/spend_tracking/spend_tracking_utils.py Adds caller-session precedence, but accepts empty session values and expands a docstring contrary to repository guidance
tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py Adds meaningful precedence regression tests, with unnecessary explanatory docstrings

Reviews (1): Last reviewed commit: "fix(proxy): honor caller litellm_session..." | Re-trigger Greptile

Comment on lines +698 to +700
caller_session_id: Final = kwargs.get("litellm_session_id")
if caller_session_id is not None:
return str(caller_session_id)

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.

P2 Empty Sessions Override Traces An empty litellm_session_id passes the non-None check, replacing a valid trace ID with a blank spend-log session.

Suggested change
caller_session_id: Final = kwargs.get("litellm_session_id")
if caller_session_id is not None:
return str(caller_session_id)
caller_session_id: Final = kwargs.get("litellm_session_id")
if caller_session_id:
return str(caller_session_id)

Comment on lines +684 to +689
"""Under `omit` only `metadata.session_id`, the key Langfuse reads, counts as a session. Batch call types
carry a deterministic session derived from the batch id, which outranks everything else because the
per-request trace ids differ between the create call and the cost poller's row. Otherwise the caller's
`litellm_session_id` wins: it is only absent or a copy of the trace id when the caller did not send one,
so preferring it changes nothing for sessionless requests while letting a real session id reach the
spend log instead of being overwritten by the per-call trace id."""

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.

P2 Unnecessary Docstrings Violate Guidance These source and test docstrings restate straightforward logic, violating CLAUDE.md's comments directive; this repository requirement must be satisfied 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!

@@ -692,6 +695,9 @@ def _get_session_id_for_spend_log(

if batch_trace_session_id is not None:
return batch_trace_session_id
caller_session_id: Final = kwargs.get("litellm_session_id")

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.

Medium: Caller-controlled session enables cross-tenant history retrieval

get_all_spend_logs_for_previous_response_id() expands a response ID to all rows with the same session_id globally. A caller can set this value to another tenant's session, create their own response ID, and use previous_response_id to replay that tenant's stored messages; scope the continuation lookup by authenticated API key, team, user, or organization before persisting caller-controlled sessions here.

@veria-ai

veria-ai Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

PR overview

This PR updates proxy spend tracking so a caller-provided litellm_session_id is recorded as the spend log's session_id. This allows response continuation logic to use the caller's session identifier.

One security issue remains open: continuation history is looked up globally by session_id, so a caller who supplies another tenant's session identifier could retrieve that tenant's stored messages through their own response chain. The lookup must be scoped to the authenticated API key, team, user, or organization before caller-controlled session IDs can be used safely.

Open issues (1)

Fixed/addressed: 0 · PR risk: 7/10

@codecov

codecov Bot commented Sep 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

yassin-berriai and others added 4 commits September 13, 2026 00:41
Multi-IdP deployments can now set virtual_key_claim_field and
unregistered_jwt_client_behavior on a JWTIssuerConfig entry. Tokens from
that issuer use the issuer-specific claim path and no-match policy for the
virtual key mapping lookup; issuers that omit them keep the global values.
The auth flow now enters the mapping lookup when any issuer configures the
field, not only when the global field is set.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
@yuneng-berri
yuneng-berri deleted the branch BerriAI:litellm_internal_staging September 13, 2026 04:52
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
mateo-berri and others added 3 commits September 13, 2026 09:59
The org cache entries written by prefetch_auth_objects carry the 5s
DEFAULT_IN_MEMORY_TTL. The first @log_db_metrics getter lazily imports
litellm.proxy.proxy_server, which on a cold CI runner can take longer
than 5s, so the org entry expired before get_org_object read it and the
getter fell through to the MagicMock database. Inject a frozen clock
into InMemoryCache so the test asserts the join, not import latency.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The default path of _get_session_id_for_spend_log never consulted
kwargs['litellm_session_id'], so a caller-supplied session was
overwritten by the per-call trace id and LiteLLM_SpendLogs.session_id
could never group by litellm_session_id. Prefer it after the batch
lifecycle's deterministic session: when the caller sent no session the
value is only the derived trace-id copy, so sessionless requests are
unchanged.

Fixes BerriAI#40851
@deepanshupal

Copy link
Copy Markdown
Contributor Author

Heads up: this fix now also lives in #41004 against main (staging was deleted during the branch cleanup). Same branch, same commits - happy to close whichever one you don't want.

@deepanshupal

Copy link
Copy Markdown
Contributor Author

Closing as a duplicate of #41004, which carries the same fix.

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.

[Bug]: LiteLLM_SpendLogs.session_id doesn't reflect litellm_session_id, breaks session grouping

5 participants