Repository navigation
fix(serving): read the session Claude Code actually sends today - #1391
Conversation
Claude Code rows were logging no session at all. My earlier claim that the
gateway side worked was wrong, and so was the format it was built on.
## The parser was written against a retired format
`metadata.user_id` stopped being an underscore composite in Claude Code
**2.1.78** (2026-03-17). Current clients send a JSON object:
{"device_id": "...", "account_uuid": "...", "session_id": "..."}
A regex anchored at `^user_` cannot match a value whose first character is `{`,
so `session_identity()` returned None for every current Claude Code request --
silently, since a declaration nobody sends is indistinguishable from one that
fails to parse. The format I coded against was real, just six months obsolete,
and no captured request existed anywhere in the tree to catch that.
This was established by live capture: real Claude Code binaries run against a
logging server via ANTHROPIC_BASE_URL, plus a version bisect over published
tarballs (2.1.77 composite, 2.1.78 JSON, through 2.1.266). The synthetic ids in
the tests are stand-ins for that capture, not the capture itself.
## Two sources, not one
Current Claude Code also sends `x-claude-code-session-id`, a bare UUID, on
every request -- purpose-built for this and needing no inference, so it is read
first and is now the strongest source after the gateway's own header. The
module docstring claimed no coding agent sends a session header; that stopped
being true and now says so.
`_claude_code_session_id` handles both body shapes: JSON read by member NAME
(an operator's CLAUDE_CODE_EXTRA_METADATA keys serialize ahead of the canonical
ones, so position is not dependable), and the composite kept as the legacy
branch for pre-2.1.78 clients. Which one answered is recorded as
`metadata.user_id.session_id` or `metadata.user_id`, since they are not equally
strong claims.
`parent_session_id`, present on a subagent run, is deliberately NOT read -- it
names the session that spawned this one, the same trap as OpenCode's
`x-parent-session-id`.
## What this does not establish
The capture proves current Claude Code is unparseable by the old regex. It does
not prove the operator's blank rows are current Claude Code arriving on the
Anthropic surface -- an intermediary that forwards the system prompt while
dropping both the metadata and the header would produce identical symptoms and
would still be labelled claude-code. That is checked against the deployment's
own `api_logs`, not from here.
Five other hypotheses were investigated and ruled out with evidence: the
Anthropic route's body-copy ordering is sound (the deepcopy precedes every
mutation), every logging entrypoint on that surface is wired, and the write and
read paths populate `api_logs.session_id` and `metadata->>'session_id'` from
one dict in one INSERT outside the full-content branch.
Tests cover the JSON shape, a value longer than MAX_SESSION_ID_CHARS (only the
extracted member is measured), key-order independence, the subagent case,
malformed and non-object JSON, the legacy composite, the header, and the header
winning over the body it duplicates. `make lint`, `make test` (4990 passed) and
`make docs-verify` pass.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpETEerrhcCpsg69ucjrEt
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f651d969b6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Codex's finding, and it reproduces: `RecursionError` is not a `ValueError`, so the `except ValueError` around `json.loads` did not catch it. `metadata.user_id` is client-controlled and `json.loads` recurses per level of nesting, so a deeply nested value escaped `session_identity` and turned an otherwise valid request into a 500. Measured against the unguarded decode: depth 400 (2.4KB) returned None as intended, depth 2000 (12KB) raised, depth 50000 (300KB) raised. Two guards, neither standing alone: * A length bound on the container before decoding. Claude Code caps its own serialized metadata at 512 bytes and a real value measures ~190, so 1024 is generous for every shape it sends while putting the reachable nesting depth far under the interpreter's limit. This is a bound on the CONTAINER, distinct from MAX_SESSION_ID_CHARS which bounds the id read out of it. * `RecursionError` added to the caught exceptions, so a lowered recursion limit or a future larger format cannot reopen the hole. Tests: the reproducing depth returns None rather than raising; an over-long but well-formed object is rejected without decoding; and a real value is asserted to sit well inside the bound, so the guard cannot be tightened into breaking the traffic it exists to serve. `make lint` and `make test` pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WpETEerrhcCpsg69ucjrEt
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 42579f175a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Codex's second finding, and it caught an inconsistency in my own reasoning.
The legacy branch deliberately insists on the whole `user_<h>_account_<u>_
session_<s>` composite -- the docstring says why: another client's ordinary
user id that merely contains `_session_` (`customer_session_internal`) must
not have its tail read as a session. The JSON branch I added abandoned that
line and accepted any object carrying a `session_id` member.
So a non-Claude client using a JSON object as its user identity --
`{"session_id": "tenant-plan"}` -- would have had every request behind that
value collapsed into one invented session, corrupting both the console's
session filter and RouteWise's per-session cache accounting. This field is
Anthropic's USER identifier; a session read out of it is an inference, and it
has to be justified by the shape.
The branch now requires `device_id` and `account_uuid` to be present.
Presence, not content: `account_uuid` is the empty string when the client
authenticated with an API key rather than an account, which is a real shape
that must still resolve. Both keys appear in every captured variant from
2.1.78 through 2.1.266 -- canonical, with an empty account, with
`parent_session_id` on a subagent run, and with CLAUDE_CODE_EXTRA_METADATA
keys serialized ahead of them.
Tests: the exact value Codex named yields None; either marker missing yields
None; and the empty-account_uuid shape still resolves, so the check cannot be
mistaken for a content requirement.
`make lint` and `make test` pass.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpETEerrhcCpsg69ucjrEt
Resolves the zh_CN catalog conflict in docs/developer/database.md's translations. Both sides only touched generated regions: dev's admin-console wording change retired one msgid to the obsolete block, and this branch retired the old Claude Code composite msgid to the same block. Kept both retirements and took dev's newer POT-Creation-Date. make docs-verify: translations match the English build, 141 documents linked. make lint clean; make test 5291 passed, 57 skipped. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WpETEerrhcCpsg69ucjrEt
Claude Code rows were logging no session at all. My earlier conclusion in #1371/#1374 — that the gateway side worked and only OpenCode/Kilo were affected — was wrong, and so was the format the parser was built on.
The parser was written against a retired format
metadata.user_idstopped being an underscore composite in Claude Code 2.1.78 (2026-03-17). Current clients send a JSON object:{"device_id": "...", "account_uuid": "...", "session_id": "..."}A regex anchored at
^user_cannot match a value whose first character is{, sosession_identity()returnedNonefor every current Claude Code request — silently, because a declaration nobody sends is indistinguishable from one that fails to parse. The format I coded against was real, just six months obsolete, and no captured request existed anywhere in the tree to catch that.Established by live capture: real Claude Code binaries run against a logging server via
ANTHROPIC_BASE_URL, plus a version bisect over published tarballs — 2.1.77 composite, 2.1.78 JSON, unchanged through 2.1.266. The synthetic ids in the tests are stand-ins for that capture, not the capture itself.Two sources now, not one
Current Claude Code also sends
x-claude-code-session-id, a bare UUID, on every request — purpose-built for this and needing no inference, so it is read first and is now the strongest source after the gateway's own header. The module docstring asserted that no coding agent sends a session header; that stopped being true and now says so.The body parse is consequently a fallback, mattering for 2.1.78–2.1.99 clients, which send the JSON but not the header. It handles both shapes:
CLAUDE_CODE_EXTRA_METADATAkeys are serialized ahead of the canonical ones, so position is not dependable.Which one answered is recorded as
metadata.user_id.session_idormetadata.user_id, since they are not equally strong claims.parent_session_id, present on a subagent run, is deliberately not read — it names the session that spawned this one, the same trap as OpenCode'sx-parent-session-id.Two defects found in review, both fixed
Both were real and both are mine, in the code this PR adds:
42579f1).RecursionErrorinherits fromRuntimeError, notValueError, so the handler aroundjson.loadsnever caught it — andmetadata.user_idis client-controlled. Reproduced against the unguarded decode: depth 400 (2.4 KB) handled, depth 2000 (12 KB) escaped, depth 50000 (300 KB) escaped. Fixed with a 1024-char bound on the container before decoding (Claude Code caps its own serialized metadata at 512 bytes; a real value is ~190) and by catchingRecursionError, so neither guard stands alone.be437f3). The JSON branch accepted any object carrying asession_idmember, abandoning the very rule the legacy branch enforces — that another client's ordinary user id must not have a session read out of it.{"session_id": "tenant-plan"}would have collapsed every request behind that value into one group.device_idandaccount_uuidare now both required, by presence not content, sinceaccount_uuidis the empty string on API-key auth.What this does not establish
The capture proves current Claude Code is unparseable by the old regex. It does not prove the operator's blank rows are current Claude Code arriving on the Anthropic surface. An intermediary that forwards the system prompt while dropping both the metadata and the header (LiteLLM, claude-code-router, any OpenAI-compat shim) would produce identical symptoms and would still be labelled
claude-code, becausemetadata["agent"]is derived from the system prompt. That is checked against the deployment's ownapi_logs, not from here.Five other hypotheses were investigated and ruled out with evidence:
metadata;log_rejection, fires before the resolver could apply);api_logs.session_idandmetadata->>'session_id'from one dict in one INSERT, outside the full-content branch;metadata, so it is not an alternative explanation.Verification
make lintclean,make test→ 4997 passed, 56 skipped,make docs-verify→ translations match the English build.Tests cover: the JSON shape; a value longer than
MAX_SESSION_ID_CHARS(only the extracted member is measured); key-order independence; the subagent case assertingparent_session_idis not preferred; malformed and non-object JSON; the legacy composite; the header; the header winning over the body it duplicates; the reproducing recursion depth; an over-long but well-formed object; a real value asserted inside the bound; the{"session_id": "tenant-plan"}case; and either Claude marker missing. The parametrized header list is kept in sync with_AGENT_SESSION_HEADERS.zh_CN carries all new paragraphs, including one bad
msgmergefuzzy match that had inheritedX-Session-ID's translation.🤖 Generated with Claude Code
https://claude.ai/code/session_01WpETEerrhcCpsg69ucjrEt