Repository navigation
fix(anthropic): log the safeguards classifier and compaction summary calls in the parent request's session - #53405
Conversation
…calls in the parent request's session On /v1/messages, the safeguards classifier call and the compact_20260112 summary call each logged under a fresh session id, so their spend log rows never grouped with the Claude Code session that triggered them. The shared sub-call logging kwargs now carry the parent's top-level litellm_session_id and its resolved trace id. Metadata session keys stay out because deployment affinity reads them
…rovider affinity header Carry the missing_session_id: generate marker into the safeguards classifier and compaction summary sub-call metadata, so a session the proxy minted is never sent upstream as an affinity header. The spend-row session test now asserts the row the Logs page groups by.
[Medium impact] The PR appears safe to merge with no new actionable findings.
|
…to safeguards and compaction sub-calls
…uest, not the setup-time logging params The setup-time Logging params replaced the request's proxy_server_request with None and used Claude Code's Anthropic metadata.user_id in place of the proxy's litellm_metadata, so sub-calls joined a session-named trace instead of the parent call's. The merge order now matches the Responses path, where the request kwargs and litellm_metadata win
…s session when it is sent in litellm_metadata or under missing_session_id omit
Main now builds spend rows in Rust (BerriAI#52161), so the sub-call session fallback under missing_session_id: omit moves into the Rust row builder too, with a golden scenario for it
…s routing session The sub-calls now carry the parent's session for logging, so Switchyard and the adaptive router would count them as turns of the caller's conversation. They are marked as inheriting the session, and both routers skip a session marked that way
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
…m_safeguards_classifier_parent_session # Conflicts: # litellm/llms/anthropic/messages/utils.py
|
bugbot run |
| return str(sid) | ||
| explicit: Final = None if inherits_parent_session(litellm_params) else _explicit_session_id(litellm_params) | ||
| if explicit: | ||
| return explicit |
There was a problem hiding this comment.
Inherited sub-calls still train adaptive router
Medium Severity
Skipping an inherited session only clears the explicit id, so _resolve_session_key still hashes the first SIGNAL_GATE_MIN_MESSAGES messages. Compaction summaries reuse that history, so with no parent session the summary can share the parent's bandit key and record_turn still runs. The new hook test stays under the message gate, so it never catches this.
Reviewed by Cursor Bugbot for commit 45ced8b. Configure here.
There was a problem hiding this comment.
Pre-existing, not from this PR. Base sends this sub-call with no session, so it hashes the same messages into the same key
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 45ced8b. Configure here.
Pass the provider-signed limit to the Rust row builder again after BerriAI#53599 spelled out its arguments, and record BerriAI#53405's two new golden rows with that config key


Handwritten 1-3 sentence description
When Claude Code runs in auto mode on a non-Claude model, the safety check and compaction summary calls now show up in the session of the request that triggered them. Before, each got its own random session, so the logs' session view left them out
Details
TLDR
Problem this solves:
How it solves it:
User Flow
Before: in Claude Code auto mode on a non-Claude model, the safety check call is missing from the session
safeguards_classifier_modeland points Claude Code at the proxy with--permission-mode autols -la, so POST /v1/messages runs the safety checkAfter: the safety check call is in the turn's session
Compaction summary calls get the same change
Linear ticket
Resolves LIT-10761
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<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 moreDelays 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
Each leg ran a 2-worker proxy with its own Postgres and Redis, real OpenAI and Gemini calls, a shared Langfuse project and Claude Code v2.1.331's TUI. Before is the merge base
Last updated: 45ced8b. QA ran on bc894cf. Changes since QA: omit mode gives a sent session only to sub-call rows, and clients can no longer send the sub-call marker. Proof remains valid because other policies skip that branch, and the omit case ran again at 45ced8b. Verification: unit tests and Rust goldens
litellm_metadatamissing_session_id: omitrequest_correlation_in_logsShared setup (config, proxy, clients)
The legs ran one after the other, so each Langfuse window holds one leg. The proxy skips
--reload, which ignores--num_workers, and--detailed_debugand--use_v2_migration_resolver, since each leg runs on its own new databaseEnv vars, with values left out, are
DATABASE_URL(a fresh database per leg),REDIS_HOSTandREDIS_PORT(one Redis per leg),LITELLM_MASTER_KEY,OPENAI_API_KEY,GEMINI_API_KEY,LANGFUSE_PUBLIC_KEY,LANGFUSE_SECRET_KEY,LANGFUSE_HOST, andPORT(a free port per leg)config.yaml
Proxy, from each tree
python litellm/proxy/proxy_cli.py --config config.yaml --host 127.0.0.1 --port $PORT --num_workers 2 --timeout_worker_healthcheck 60 --telemetry False --use_prisma_db_pushEach proxy served from 2 workers, for example
ps --ppid <proxy pid>on the After leg printed the resource tracker plus twomultiprocessing.spawnworkersThe omit case adds
missing_session_id: omitundergeneral_settings, the correlation case addsrequest_correlation_in_logs: trueunderlitellm_settings, and each leg restarts after the changeClaude Code 2.1.331, in an empty project folder holding
app.pyandREADME.mdThe correlation case also sets
ANTHROPIC_CUSTOM_HEADERS="x-litellm-trace-id: corr-cc-trace-base"(corr-cc-trace-headon After), which Claude Code sends on every requestThe Python steps run with
PROXY_BASE_URL=http://127.0.0.1:$PORTandLITELLM_MASTER_KEYset for that leg, and needpip install anthropic httpxspend_window.py lists the spend rows in a time window through GET /spend/logs/ui
session_view.py opens one session through GET /spend/logs/session/ui
lf_observations.py reads the LiteLLM generations Langfuse holds in a time window. Its columns are start time, type, name, observation id, the first 12 characters of the trace id, parent observation id, and Langfuse session id
session_headline.py lists the grouped Logs rows, one per session, through GET /spend/logs/ui with
group_by_sessionsdk_compact.py sends a ~108k token history plus a tool call turn with
compact_20260112compaction,safeguards, and a Claude Code session headersdk_body_session.py sends the same compaction request with the session only in
litellm_metadataand no session headersdk_no_session.py sends a tool call turn with
safeguardsand no session at allBefore (fdc16fd)
Claude Code auto mode turn
list the files in this directory using the Bash tool with ls -la, then tell me how many there areand press Enter. It runsls -lawith no prompt, so the auto mode check ranLangfuse readback of the same turn
The classifier sits alone in its own trace, outside every main call's trace
Grouped Logs rows for the same turn
The grouped Logs view shows the classifier as a session of its own
Compaction + safeguards request
Session sent only in litellm_metadata
litellm_metadatamissing_session_id: omit
missing_session_id: omit, run the same Claude Code turn, then send a request with no sessionrequest_correlation_in_logs with an x-litellm-trace-id header
request_correlation_in_logs: trueand the trace header set, run the same Claude Code turn. The main calls keep Claude Code's session, and the classifier call gets a random oneAfter (bc894cf)
Claude Code auto mode turn
Langfuse readback of the same turn
The classifier sits in the trace of the parent call whose answer held the
ls -latool useGrouped Logs rows for the same turn
The grouped Logs view shows one row for the session
Compaction + safeguards request
Session sent only in litellm_metadata
litellm_metadatamissing_session_id: omit, ran again at 45ced8b
missing_session_id: omiton the 45ced8b proxy, run the same Claude Code turn, then send a request with no sessionrequest_correlation_in_logs with an x-litellm-trace-id header
The run noticed these. Only the first is new with this PR
/live-pr-risk report at 45ced8b
PASS. Base fdc16fd and head 45ced8b each ran as a proxy with 2 workers and its own Postgres and Redis, with real OpenAI and Gemini calls behind forwarding recorders. 98 cells per leg ran with no policy and again under
missing_session_id: omit, plus 30 failure cells. A client-sentlitellm_session_id_inheritednow acts as on base on every route tried, and the proxy's own sub-calls keep itBreaking. None. Every cell matched base on status, spend row session, upstream affinity and session headers, and the Switchyard session
Backward incompatible. Classifier and compaction summary rows carry the parent session and skip Switchyard and adaptive router session scoping. Shivam asked for this in LIT-10761's suggested fix, which forwards the parent's
litellm_session_idthe way_parent_session_kwargsalready does for the auto router's classifier calls. It is in Decisions and the High caveat. At f296471 a client could send the new marker itself and keep its own session on a generateContent row under omit. 45ced8b strips the marker from client input, so those rows are empty again, as on baseRegression risk. Low, traced and not reached. The failure spend row copies raw client
metadatawith no strip, and the pass-through pre-call hook still sees the client marker. No code reads the marker on either path today, and every failure cell with a forged marker matched base under omitDependency graph. Verified live are the HTTP strip on chat, messages, responses and generateContent (each bucket and duplicate keys), the queue route's
caller_metadata, Responses WebSocket turns, both pass-throughs, and the safeguards and compaction sub-calls. WebSocket frame metadata never reached the hook on either side, so that strip has no marker-specific proof. The legacy spend path, Langfuse and the 189 integration tests carry from f296471, since this diff touches none of themNot verified. The tree merged with main was not run live. The merge is clean and none of main's 48 commits changes a strip or marker line. Carried from f296471 are the Fireworks, ChatGPT and opencode session headers, Kubernetes pod pinning, and the S3, Datadog and PostHog exports. Under omit, generateContent drops a session sent in the
baggageheader on base and head alike. That is filed for follow-upType
🐛 Bug Fix
Caveats (if any)
High
Medium
Low
litellm_session_id_inherited, like the existing generated markerrequester_custom_headerskeycompact_20260112rust-wheelfails the same 10 Bedrock and callback tests on mainDecisions and the options not taken
litellm_metadata, goes on as the top-level session only, with the trace id and the marker for a session the proxy mintedsession_idwould let a sub-call overwrite a complexity router's per-session tier pinmissing_session_id: omita sub-call's row takes the parent session it inherited, never a trace idmissing_session_id: generatethe minted session groups the rows but never goes upstreamprovider_affinity_headerand the Switchyard router'sx-switchyard-session-id, and Kubernetes pod discovery pins them to the session's podrequest_correlation_in_logsthe sub-calls carry the caller's session that anx-litellm-trace-idheader moved asidelitellm_session_id_inheritedmarker, and Switchyard and the adaptive router skip a session marked that wayFinal Attestation
Bugbot summary