Repository navigation
feat(record): record replayable session traces, opt-in per account - #649
Conversation
|
Updated on 2026-10-22, after a talk with @alonh. This replaces my earlier proposal. @amiddavid, we are going with wire as the recording format. The eval team cannot use OTLP, but their replay already reads wire. What wire is. It is Inference-Perf's wire capture format (kubernetes-sigs/inference-perf#820, merged):
Wire is the raw record, so OTLP and any other format can be made from it later. The proxy already holds those exact bytes. The plan for this PR:
Unless you see a problem, I'll rework the PR this way. The content question (data-dependence) is the same for wire. |
|
wire is fine. |
|
@amiddavid, thanks. Wire is pushed:
Phoenix: The branch is behind |
Per review on #649. The proxy wrote the flat claude-record corpus shape, which Inference-Perf's OTel trace replay reads, but which Phoenix, Jaeger and other OTLP collectors cannot. It also rewrote each session's whole file every 10 s, and kept every session's spans in memory until the proxy stopped. The proxy now records one OTLP span per turn, sent once: - --record-otlp <url>: OTLP/HTTP through the Go OTel SDK. A BatchSpanProcessor with a bounded queue, which drops when full, so recording still never delays a request. - --record <dir>: the same spans as OTLP JSON lines, one file per session, appended. This is the OTel collector file exporter format. Either or both. The writer keeps only the last span id per session. Spans: - Trace id: the session UUID without dashes; any other session key is hashed to 16 bytes. The original key is in session.id. - Resource: service.name context-guru-proxy, cg.client.name, and cg.tenant.id in hosted mode. - gen_ai.provider.name next to the deprecated gen_ai.system. - Messages in the semconv schema: tool_call arguments as JSON values. - OpenInference attributes (openinference.span.kind, llm.*, input.*, output.*) so Phoenix shows model, tokens and messages. cmd/cg-record-convert reads either output and writes the corpus files, with turn reconstruction, which moves out of the proxy. Sessions split over several files (a restart) become one. Tests: the recorder tests now read their trace files through the converter. Same events through the previous branch and through export plus conversion give identical corpus files, once random span ids and collected_at are set aside. Exported to Phoenix 12.9.0: one trace per session, turns parented, model, token counts with cache split, and messages all shown. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Recording is all content: the full request and response of each call, redacted, for replay. So it can only be a deliberate exception to the metadata-only rule. The row says so, and that the decision is open on #649. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Groundwork for wire recording (proposal on #649). A streamed response splits the model's text across events at arbitrary points, so a secret the model repeats can be split too. Redacting each event on its own sees half a key in each, matches nothing, and keeps both halves. RedactSSE joins each content block's deltas (text, tool-call arguments, thinking), redacts the whole text once with Content, and gives the result back to the same events. A placeholder that would straddle two events goes whole into the first. The stream keeps its events and stays valid, and the deltas join to the redacted message. Other events are redacted on their own. A clean stream comes back byte for byte. Tested on every single cut and many double cuts of a text holding a key and a name: the deltas always join to the redacted text, and no event holds any part of either. A test also shows that per-event redaction does leak a split key. Not wired into the recorder yet. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Decided on #649 with the eval team: they cannot use OTLP, and their replay reads wire directly (kubernetes-sigs/inference-perf#820). --record <dir> now writes <session>.wire.jsonl: one line per call, with path, request, response (the SSE text for a stream), status, start_unix, total_ms, model and headers.session_id. Each line also has cg_first_byte_ms, cg_upstream_rounds, cg_incomplete and cg_recorded_by; the loader ignores keys it does not read. The bodies come from the event, not from the translated turn, so nothing the translation drops is lost (thinking blocks, unknown fields). They are redacted before the line is built: - the request with ContentJSON, so it stays valid JSON; - a streamed response with RedactSSE, across event boundaries; - any other response with ContentJSON. Headers are an allow-list: only the session id. A body cut at --record-body-cap says so in cg_incomplete. A turn's incomplete reasons from translation (no body, no usage) are written to its line too. --record-otlp is unchanged: the optional live OTLP view for Phoenix. The corpus converter (cmd/cg-record-convert, convert.go, otlpjson.go) is removed: the eval team replays wire, so nothing needs the corpus files. Turn reconstruction stays, as record.WithDerivedTurns, for any reader of wire that needs turns. Checked with Inference-Perf's own loader (wire_trace_converter.py at main) on a file the recorder wrote: detected as anthropic_wire, one trace per session (the session UUID), every call converted with its messages, tools, token counts with cache read, and the reply. A key split across two streamed events does not reach the converted trace. The recorder tests now read wire files, and rebuild the translated turns from them. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
40dd1a6 to
73b2ac2
Compare
Per review on #649. The proxy wrote the flat claude-record corpus shape, which Inference-Perf's OTel trace replay reads, but which Phoenix, Jaeger and other OTLP collectors cannot. It also rewrote each session's whole file every 10 s, and kept every session's spans in memory until the proxy stopped. The proxy now records one OTLP span per turn, sent once: - --record-otlp <url>: OTLP/HTTP through the Go OTel SDK. A BatchSpanProcessor with a bounded queue, which drops when full, so recording still never delays a request. - --record <dir>: the same spans as OTLP JSON lines, one file per session, appended. This is the OTel collector file exporter format. Either or both. The writer keeps only the last span id per session. Spans: - Trace id: the session UUID without dashes; any other session key is hashed to 16 bytes. The original key is in session.id. - Resource: service.name context-guru-proxy, cg.client.name, and cg.tenant.id in hosted mode. - gen_ai.provider.name next to the deprecated gen_ai.system. - Messages in the semconv schema: tool_call arguments as JSON values. - OpenInference attributes (openinference.span.kind, llm.*, input.*, output.*) so Phoenix shows model, tokens and messages. cmd/cg-record-convert reads either output and writes the corpus files, with turn reconstruction, which moves out of the proxy. Sessions split over several files (a restart) become one. Tests: the recorder tests now read their trace files through the converter. Same events through the previous branch and through export plus conversion give identical corpus files, once random span ids and collected_at are set aside. Exported to Phoenix 12.9.0: one trace per session, turns parented, model, token counts with cache split, and messages all shown. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Recording is all content: the full request and response of each call, redacted, for replay. So it can only be a deliberate exception to the metadata-only rule. The row says so, and that the decision is open on #649. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Groundwork for wire recording (proposal on #649). A streamed response splits the model's text across events at arbitrary points, so a secret the model repeats can be split too. Redacting each event on its own sees half a key in each, matches nothing, and keeps both halves. RedactSSE joins each content block's deltas (text, tool-call arguments, thinking), redacts the whole text once with Content, and gives the result back to the same events. A placeholder that would straddle two events goes whole into the first. The stream keeps its events and stays valid, and the deltas join to the redacted message. Other events are redacted on their own. A clean stream comes back byte for byte. Tested on every single cut and many double cuts of a text holding a key and a name: the deltas always join to the redacted text, and no event holds any part of either. A test also shows that per-event redaction does leak a split key. Not wired into the recorder yet. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Decided on #649 with the eval team: they cannot use OTLP, and their replay reads wire directly (kubernetes-sigs/inference-perf#820). --record <dir> now writes <session>.wire.jsonl: one line per call, with path, request, response (the SSE text for a stream), status, start_unix, total_ms, model and headers.session_id. Each line also has cg_first_byte_ms, cg_upstream_rounds, cg_incomplete and cg_recorded_by; the loader ignores keys it does not read. The bodies come from the event, not from the translated turn, so nothing the translation drops is lost (thinking blocks, unknown fields). They are redacted before the line is built: - the request with ContentJSON, so it stays valid JSON; - a streamed response with RedactSSE, across event boundaries; - any other response with ContentJSON. Headers are an allow-list: only the session id. A body cut at --record-body-cap says so in cg_incomplete. A turn's incomplete reasons from translation (no body, no usage) are written to its line too. --record-otlp is unchanged: the optional live OTLP view for Phoenix. The corpus converter (cmd/cg-record-convert, convert.go, otlpjson.go) is removed: the eval team replays wire, so nothing needs the corpus files. Turn reconstruction stays, as record.WithDerivedTurns, for any reader of wire that needs turns. Checked with Inference-Perf's own loader (wire_trace_converter.py at main) on a file the recorder wrote: detected as anthropic_wire, one trace per session (the session UUID), every call converted with its messages, tools, token counts with cache read, and the reply. A key split across two streamed events does not reach the converted trace. The recorder tests now read wire files, and rebuild the translated turns from them. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
|
@michaljacovi is this ready ? do u want us to merge it? |
|
@amiddavid, this is ready for review.
One thing needs you before merge: the trace-recording row in |
|
@amiddavid, yes, please merge. CI is green now: I pushed a gofmt fix and bumped One thing first: the trace-recording row in |
|
I confirm |
…h path The stream-through path (the common one: no expand marker advertised) never materialises a response body, so a recorder attached at the cp.finish defer would write empty responses for most turns. Measured: resp body reachable on 4 terminal paths, zero-by-design on 2, never assigned on 3. streamRec adds an optional *recTee. stream() stays as a thin wrapper so all four existing callers are byte-for-byte unchanged, and the two that are not inference turns (catch-all passthrough, /count_tokens) keep calling it and record nothing. recTee is bounded and reports truncation rather than silently dropping a tail: a turn that says 'truncated at N' is data, one that quietly lost its tail is a corpus defect found only at analysis time. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5 <[email protected]>
…s shape Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5 <[email protected]>
…GP false positive Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5 <[email protected]>
Recovers the human's turns from the conversation each request body replays, and emits them as cg.turn.derived spans. Nothing here claims claude_code.interaction: that name means "observed on the developer's machine", and a reconstruction wearing it would make a derived sequence number indistinguishable from a measured one. Calls are grouped by advertised tool set rather than by first message text. First-text keying was tried and fails on long sessions: once a conversation passes compaction its earliest turn drops out of the replayed window, so the same conversation silently acquires a new identity mid-session. Measured cost of that approach was 38 turns corpus-wide. Roughly half of all role:user text is not the human -- system reminders, command echoes, skill preambles, continuation notices, and peer or coordinator messages delivered as ordinary user text. The filter here was read off 30,224 real text parts, not guessed. Measured on 66 sessions: 651 of the 764 turns that happened (85.2%) against claude-record's 528 surviving interaction spans (69.1%), at 97.0% recall of the turns claude-record kept. Deliberately absent: a tool success flag and an execution duration. Failure appears in a tool result as prose, not a flag, and execution happens on a machine the proxy is not on. Both stay absent rather than being synthesised into columns that would look measured. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5 <[email protected]>
internal/record had zero importers: a complete, tested translation library that
nothing in the binary invoked, and newRecTee had no callers outside its own file.
This adds the missing half, so `--record <dir>` writes claude-record-shaped
*.otel.json for real traffic.
Why it matters more than the code does: every number in the eval-team comparison
is currently scored against claude-record's own interaction spans, and we have
filed an issue showing that reference loses ~31% of them to Jaeger eviction. One
session recorded by BOTH mechanisms, compared against what the developer knows
they typed, gives a ground truth belonging to neither recorder -- which is what
turns the "<=" hedges in our ratios into measured figures.
Design, all of it forced by the fail-open rule rather than chosen:
- recEvent carries raw bytes and scalars only. Translation, SSE aggregation and
redaction run on the writer goroutine, never the request path: redaction is
~53 ms/request against ~175 ns for a channel send, and serve's defer fires
before the handler returns, so that cost would be paid by the next request on
a keep-alive connection -- by every real agent.
- trace_id comes from session.ExplicitID(metadata.user_id), NOT tr.Session. In
observe mode -- the mode a dual-recorded session runs in -- tr.Session is
empty by construction, so keying on it would write one file named for the
empty string holding every session's spans. It is also the id claude-record
names its files by, which is what makes the two joinable per session.
- SSE bodies go through expand.AggregateSSE before translation, because
OutputMessages unmarshals one message object. Usage therefore comes from the
proxy's own parse: an aggregated body carries no usage key at all.
- All four response paths are wired, including the non-Anthropic SSE path that
cannot occur in our own session -- otherwise those users would get turns with
empty responses and no reason given.
- Filenames are sanitised because apply.SessionIDFor returns "tenant:base", and
on NTFS "tenant:base.otel.json" creates a hidden alternate data stream rather
than a file: no error, no file, no clue.
- A restart will not overwrite an existing session file; it writes alongside it.
Truncating the earlier half of a long session is unrecoverable.
Also fixes the newSniffer gate to include h.recorder. Latent in the shipped binary
since agg is always non-nil, but a --record-only Handler (which every unit test
builds) would have got an off sniffer and a silently usage-free corpus.
IncompleteNoUsage is new: ToSpan writes cg.usage.* unconditionally and
deliberately, since a genuine zero is data, so "no cache activity" and "never
measured" are otherwise indistinguishable.
Verified: 15 new tests, including byte-identical client output with recording on
and off through a real Handler and Mux. Smoke-tested live against a fake SSE
upstream in observe mode -- two turns, one file named by the session UUID, spans
correctly threaded.
Signed-off-by: Michal Jacovi <[email protected]>
Assisted-By: Claude Opus 5 <[email protected]>
A CG trace file carried only the observed model calls, so every consumer had
to re-run our Go reconstruction to see the human turns. A downstream analyzer
reads *.otel.json directly and will not know to do that, which made the turns
effectively unavailable to the tooling the comparison is judged in.
flush now writes spansWithDerivedTurns(s): the observed spans followed by one
cg.turn.derived span per reconstructed turn. Nothing is emitted as
claude_code.interaction -- that key means "observed on the machine", and
claiming it would make a derived sequence number indistinguishable from a
measured one.
Two properties the periodic flush forces, both verified by mutating the
implementation and watching the tests fail:
- Composed at write time, never stored. ReconstructTurns needs every call in
the session at once (it groups by advertised tool set, drops roots below
RootShare, de-duplicates replayed turns), so nothing correct can be
appended per-turn. Recomposing also makes the 10 s flush idempotent by
construction rather than by bookkeeping.
- Span ids are sha256(traceID, root, sequence), not random, so a turn keeps
its id across flushes. With random ids a consumer diffing two reads of a
live file would see churn where nothing changed.
Fails open per CLAUDE.md: a panic or an unparseable body yields the observed
spans unchanged. A file missing its derived turns is degraded; a missing file
is a lost session.
Also fixes an over-strict corpus assertion. TestCorpusReconstructionScore
required recon > kept unconditionally, but a tie is the ceiling, not a
failure: when claude-record lost nothing, no reconstruction can exceed it. The
claim is about a corpus containing eviction, so it is now gated on
kept < happened. Measured on a lossless 3-turn dual-recorded session,
recon == kept == happened.
Existing recorder tests now filter to the spans they are about via chatSpans,
rather than counting a file total that reconstruction is entitled to add to.
Signed-off-by: Michal Jacovi <[email protected]>
Assisted-By: Claude Opus 5 <[email protected]>
…uman turns Found by scoring the reconstruction on a second developer's corpus (33 sessions), whose shape differs from the first: code-review fan-outs, resumed sessions, and mid-session tool-set changes. - Drop any candidate turn equal to the `prompt` of an Agent/Task tool call. A subagent's first message is agent-written but arrives as role:user, and the tool-set anchor misses it when the fan-out outnumbers the main thread (68 vs 17 calls on one session) or shares the main tool set. - Treat "[SYSTEM NOTIFICATION - NOT USER INPUT]" and "Continue from where you left off." as injected. Neither is ever a claude_code.interaction prompt in either corpus. - Mark turns that were already history in a root's first observed call as Prior, emitted as cg.turn.prior_to_observation. A resume with a new session id replays the old conversation in its first request; without the mark every resume re-counts the earlier session. Marked, not dropped: the proxy cannot tell a resume from a session that predates recording. - Skip such history when another root already produced it. A tool-set change or forked subagent starts a new root whose first call replays everything; that double-counted 23 turns on 3 of 73 sessions. Corpus test: the turn count sums max(interaction.sequence) per resumed segment (Claude Code restarts it on resume), <task-notification> labels are not scored, and recall is asserted over kept turns whose prompt survives in some body, so claude-record's capture loss is no longer reported as a filter regression. 73-session corpus: 626 reconstructed of 796, recall 97.3% (99.1% where a body survives). 33-session corpus: recall 97.0% where a body survives; still fails the coverage bound because claude-record kept only 35% of its turns. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
<pasted_content> was listed as an injected wrapper and stripped, but it encloses text the human pasted, and claude-record keeps it verbatim in user_prompt. Since Claude Code 2.1.280 every paste arrives wrapped this way (up to 2.1.278 it was expanded inline), so a paste-only turn vanished and a prompt with a paste in the middle no longer matched. Found on a third developer's corpus, the first with pastes on the new format: recall where a body survives rose from 83.3% to 95.8% and from 92.6% to 96.3% on its two projects. The other two corpora are unchanged (99.1%, 97.0%). Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
cache_read and cache_write were cg.usage.* because claude-record had no such columns. claude-record 0.1.5 now writes them as gen_ai.usage.cache_read.input_tokens and gen_ai.usage.cache_creation.input_tokens, so use the same names and the two recorders' files line up column for column. The uncached remainder stays cg.usage.fresh_input_tokens; semconv has no name for it. The corpus fixture predates 0.1.5 and cannot contain the two keys, so the golden tests list them as post-corpus keys until the fixture is regenerated from 0.1.5 recordings. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Running the content scrubber over encoded JSON corrupted bodies: the assignment rule's value class admits a backslash, so in `token=XYZ\"` it consumed the escape and left a bare quote. On the first full day of recordings 63 of 314 bodies became invalid JSON, and since turn derivation parses them, it stopped at the first broken body (2 of 7 turns found in one session). ContentJSON scrubs each decoded string and splices back only the literals that changed, so the document stays valid and clean bodies are byte-identical. Object members are also checked as `"key": value` pairs, keeping the JSON-assignment coverage the encoded pass had. As a side effect the auth-header rule now fires inside escaped tool output, where it never matched before. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
…n turn After a Skill tool call for a skill already in context, Claude Code appends a role:user line "Skill /<name> is already loaded above; instructions unchanged." Turn reconstruction read it as a prompt, so one /fetch counted as two turns on the 2026-10-07 recordings. It is matched as the whole message, since "Skill /" alone can start a real prompt. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
tool_result images get flattened to a caption and replayed as plain role:user text, same shape as the pasted-image-ref case already filtered but with a different wrapper per capture path: "[Image: source: <filename>]", "[Image: original WxH, displayed at WxH...]". The Artifact tool's own "## Page contract" skill-load preamble is injected the same way. Neither is something the human typed. Measured 2026-10-08 on a Kahoot-quiz-images session: inflated 9-10 real turns to 13. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Sonnet 5 <[email protected]>
…ials The credential pass left the recording person in plain sight. On one real dual-recorded session the OS username appeared 47,817 times (every home-directory path and mangled project dir), the surname 56,528 times, the work email 917 times and GitHub Enterprise owner/repo URLs 312 times. Content now removes, before the credential pass: - owner/repo in github.com and GitHub Enterprise URLs, and bare profile URLs (site pages and anthropics/ kept) - the git user.email, then any email address (noreply, git@ and URL userinfo kept; the credential pass handles userinfo) - the git user.name: full name, login forms and last name in any case; first name only Capitalized or UPPER - the local OS username, as a whole word in any case - extra terms from CG_RECORD_REDACT_TERMS or ~/.claude-record/redact-terms.txt, the file claude-record reads This ports claude-record's identity pass (collector PR #38), in the same order. Every replacement is fixed text, so redacted calls keep identical shared prefixes for replay. claude-record's user.id alias is not ported: this recorder never writes metadata.user_id or any per-person id. Rerun over that session with the real local identity: no username, surname, work email or GitHub Enterprise owner left, and no invalid JSON bodies. CollectorVersion goes to cg-record/0.2.0 so files with and without identity redaction can be told apart. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
…ectory
--record was one process-wide switch: right on a laptop, wrong on a
shared instance, where it would record everyone or no one. Recording now
follows content capture's two-gate pattern, with one difference that
matters: the account's default is OFF.
- tenant: RecordTraces, a new column (migration v12, DEFAULT 0), so new
and existing accounts start unrecorded. Only the account itself can
change it; the registry refuses a manager in both directions, since
consent with a second owner is a setting
- proxy: recordFor gates newRecCtx. Single-tenant, the operator's flag
is the whole decision, as before. Hosted, the tenant must have opted
in, or nothing is cloned or queued for the request
- each tenant's files go under <record dir>/<tenant id>/, created 0700,
and sessions are keyed by tenant and session id, so one person's
session can never be appended to another's
- PUT /api/me takes record_traces; PATCH /api/tenants/{id} does not
- settings page: a separate checkbox for trace recording, next to the
transcript one, saying what is written and what is not removed
Not here yet: letting a user download or delete their own traces from
the dashboard. Today the operator hands over the account's directory.
Signed-off-by: Michal Jacovi <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
- proxy: the expand splice path handed the recorder the round's raw SSE stream labelled as JSON. The writer then could not parse it, and every such turn had no response. Mark it as SSE so the writer aggregates it. - proxy: the response tee was made for every request when --record was on. In hosted mode most tenants have not opted in. Make the tee only for a request that will be recorded. - turns: stripTagBlock stopped at a longer tag that shares the prefix (<system-reminders>), so a real block after it was kept as human text. It also took offsets from strings.ToLower, which can change the byte length. Keep searching, and lower ASCII only. - identity: the Capitalized first name was built by byte, which broke a multi-byte first letter (Élodie). Build it by rune. Each has a test. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Per review on #649. The proxy wrote the flat claude-record corpus shape, which Inference-Perf's OTel trace replay reads, but which Phoenix, Jaeger and other OTLP collectors cannot. It also rewrote each session's whole file every 10 s, and kept every session's spans in memory until the proxy stopped. The proxy now records one OTLP span per turn, sent once: - --record-otlp <url>: OTLP/HTTP through the Go OTel SDK. A BatchSpanProcessor with a bounded queue, which drops when full, so recording still never delays a request. - --record <dir>: the same spans as OTLP JSON lines, one file per session, appended. This is the OTel collector file exporter format. Either or both. The writer keeps only the last span id per session. Spans: - Trace id: the session UUID without dashes; any other session key is hashed to 16 bytes. The original key is in session.id. - Resource: service.name context-guru-proxy, cg.client.name, and cg.tenant.id in hosted mode. - gen_ai.provider.name next to the deprecated gen_ai.system. - Messages in the semconv schema: tool_call arguments as JSON values. - OpenInference attributes (openinference.span.kind, llm.*, input.*, output.*) so Phoenix shows model, tokens and messages. cmd/cg-record-convert reads either output and writes the corpus files, with turn reconstruction, which moves out of the proxy. Sessions split over several files (a restart) become one. Tests: the recorder tests now read their trace files through the converter. Same events through the previous branch and through export plus conversion give identical corpus files, once random span ids and collected_at are set aside. Exported to Phoenix 12.9.0: one trace per session, turns parented, model, token counts with cache split, and messages all shown. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Recording is all content: the full request and response of each call, redacted, for replay. So it can only be a deliberate exception to the metadata-only rule. The row says so, and that the decision is open on #649. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Groundwork for wire recording (proposal on #649). A streamed response splits the model's text across events at arbitrary points, so a secret the model repeats can be split too. Redacting each event on its own sees half a key in each, matches nothing, and keeps both halves. RedactSSE joins each content block's deltas (text, tool-call arguments, thinking), redacts the whole text once with Content, and gives the result back to the same events. A placeholder that would straddle two events goes whole into the first. The stream keeps its events and stays valid, and the deltas join to the redacted message. Other events are redacted on their own. A clean stream comes back byte for byte. Tested on every single cut and many double cuts of a text holding a key and a name: the deltas always join to the redacted text, and no event holds any part of either. A test also shows that per-event redaction does leak a split key. Not wired into the recorder yet. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Decided on #649 with the eval team: they cannot use OTLP, and their replay reads wire directly (kubernetes-sigs/inference-perf#820). --record <dir> now writes <session>.wire.jsonl: one line per call, with path, request, response (the SSE text for a stream), status, start_unix, total_ms, model and headers.session_id. Each line also has cg_first_byte_ms, cg_upstream_rounds, cg_incomplete and cg_recorded_by; the loader ignores keys it does not read. The bodies come from the event, not from the translated turn, so nothing the translation drops is lost (thinking blocks, unknown fields). They are redacted before the line is built: - the request with ContentJSON, so it stays valid JSON; - a streamed response with RedactSSE, across event boundaries; - any other response with ContentJSON. Headers are an allow-list: only the session id. A body cut at --record-body-cap says so in cg_incomplete. A turn's incomplete reasons from translation (no body, no usage) are written to its line too. --record-otlp is unchanged: the optional live OTLP view for Phoenix. The corpus converter (cmd/cg-record-convert, convert.go, otlpjson.go) is removed: the eval team replays wire, so nothing needs the corpus files. Turn reconstruction stays, as record.WithDerivedTurns, for any reader of wire that needs turns. Checked with Inference-Perf's own loader (wire_trace_converter.py at main) on a file the recorder wrote: detected as anthropic_wire, one trace per session (the session UUID), every call converted with its messages, tools, token counts with cache read, and the reply. A key split across two streamed events does not reach the converted trace. The recorder tests now read wire files, and rebuild the translated turns from them. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Per the eval team: wire should hold what was sent, and nothing else. - The cg_* keys are gone (first byte, rounds, incomplete, recorded_by). The live OTLP view still carries them. - headers are the request headers the client sent, not a session_id we made up. Credential headers are dropped: Authorization, x-api-key, cookies, the x-context-guru-* control headers, and any header whose name says key, token, secret, auth, password or credential. Every other value is redacted, so a credential in an unexpected header is still caught. Claude Code sends its session id as x-claude-code-session-id, which the Inference-Perf loader does not look for yet. It then names the trace after the file, and the recorder writes one file per session, so a session still groups correctly; only the trace id is not the session UUID. Checked again with Inference-Perf's loader on a file the recorder wrote with an Authorization header: no credential in the file or in the converted trace, and both calls converted into one trace. Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
…78669 The OTel exporter added in this PR pulled in golang.org/x/net v0.59.0, which trivy flags HIGH (CVE-2026-78669, net/http2); 0.60.0 is the fixed version. Also gofmt internal/record/wire.go and proxy/proxy.go, which the lint step rejected. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Michal Jacovi <[email protected]>
David Amid confirmed the trace recording row on #649 (2026-11-01), so the row now names who decided instead of "Awaiting a decision". Signed-off-by: Michal Jacovi <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
b41ce6e to
1b2aa13
Compare
|
Reviewer: GLM (one regression-only reviewer, started by the integrator on the owner's request) I reviewed only one question: can this PR hurt a user who never turns recording on, and FindingsNone blocking. I found no way this change hurts a non-recording user. Non-blocking
What I checked1. The request path with recording off. With no
2. Fail open with recording ON. 3. The tenant store. Migration v12 is one 4. Startup and flags. All five new flags default to off/empty via 5. Dependencies. OTel 1.47, grpc 1.84, protobuf 1.36.12 are new and used only by the 6. Dashboard UI. The 20 lines in dash/ui/app.js add one checkbox to the settings form and 7. Tests. Existing tests still pass. Runs on the eval box (head 1b2aa13, synced by tar
|
The recorder links OpenTelemetry, gRPC and protobuf. They add 11.5 MB (about 25%) to the default binary. Only the internal deployment needs the recorder. - sessionrec.go, recexport.go and their tests are behind cg_record. - recoff.go gives the default build a stub: NewSessionRecorder returns nil, and RecorderBuiltIn is false. - recctx.go keeps the request-path half, with no heavy dependency. - The record flags stay. A default build with a record flag set logs one warning and starts with recording off. - The record_traces column, migration and settings checkbox stay in every build, so an opt-in survives a switch of builds. - make build-record builds with the tag. - CI builds, vets and tests both variants. A guard test fails if the default build links an OpenTelemetry, gRPC or protobuf package. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
|
Reviewer: GLM (one regression-only reviewer, started by the integrator on the owner's request) Scope: only whether #649 can hurt a user who never turns recording on. The recorder's FindingsNone. I found nothing that can hurt a non-recording user, and nothing that delays, Non-blocking
What I checkedThe new commit (ca25c68) itself:
The default build (no tag):
The guard test:
The tagged build:
The request path with recording off (
Fail open with recording ON (for the team that turns it on):
The tenant store:
Dependencies: x/crypto 0.55→0.57, x/sync 0.21→0.23, x/sys 0.47→0.48, x/net →0.60 Dashboard UI: the 20 lines add one checkbox in Test runs (eval box, foreground, all pass):
|
`mkdocs build --strict` fails when a page in docs/ is not in the nav. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Performance test and how to build the recorderResult: a proxy that does not record is as fast as Build the recorder (for the internal deployment)make build-record
# or
CGO_ENABLED=0 go build -tags cg_record -o bin/context-guru-proxy ./cmd/context-guru-proxyThen start it with Turn recording off
The builds tested
D records every request. This is the worst case for the internal deployment. ResultsEach cell is the median of 3 runs. Latency is p50 in ms. Memory is peak RSS ( Default preset (
What recording costs (build D), for sizing the internal deployment
How it was tested
|
Turn recording on or off for one user (hosted mode)Result: each user turns recording on or off for themselves in the dashboard. No restart and no rebuild. The performance numbers are in the comment above. What the server needs first
How a user turns it on
Rules
Turn recording off for everyoneRemove |
This PR adds content storage: a new row in
docs/data-dependence.md(Features outside the pipeline), Kind = content. @amiddavid, it needs your confirmation before merge.Summary
--record <dir>records replayable traces of Claude Code sessions in Inference-Perf's wire format, for llm-d and Inference-Perf evaluation. The eval team replays these files directly.--record-otlp <url>also sends each recorded call live as an OTLP span, for Phoenix, Jaeger or any OTLP/HTTP collector. Either flag, or both.record_tracessetting. The setting is off for every account. Only the account itself can change it. In hosted mode each account is recorded in its own directory.internal/redactfirst, then the credential shapes it misses, then the recording person's identity (login, name, email).What
--recordwritesOne
<session>.wire.jsonlper session, one line per call, with only the fields the format defines (kubernetes-sigs/inference-perf#820):path/v1/messagesrequestresponsestatus,start_unix,total_ms,modelheadersAuthorization,x-api-key, cookies,x-context-guru-*, and any name with key, token, secret, auth, password or credential)Wire is the raw record, so nothing is translated away: thinking blocks, tool calls and unknown fields all survive. A streamed response is redacted across event boundaries, so a secret split over two events is caught. Human turns are not stored.
record.WithDerivedTurnsrebuilds them from the request bodies for anyone who needs them.Changes since the first review
@amiddavid's review asked for real OTLP and for conversion to move out of the proxy. The eval team then asked for wire, which they replay without a converter, so the design moved to wire (agreed in the thread):
BatchSpanProcessorwith a bounded queue, valid trace and span ids (the session UUID goes insession.id),service.name=context-guru-proxyplus the tenant id in hosted mode, andgen_ai.provider.name.--record-body-cap(per body, after redaction, 1 MB),--record-tee-cap(per in-flight response, 8 MB),--record-queue(256 calls).Rebased onto
main514b8be on 2026-10-27.How it was tested
Windows,
CGO_ENABLED=0, so no-race. There is no C compiler here, so the race detector has not run on this branch. A run in CI would help.go build ./...,go vet ./internal/record/ ./proxy/ ./tenant/ ./cmd/...go test ./internal/record/ ./tenant/ ./components/all/components/allincludes the data-dependence check)go test ./proxy/(recording, tenancy, capture, splice, control)Other test failures on Windows also fail on
main: nine inproxy(cache campaign, adapt,TestMailSinkFileIsOwnerOnly) andTestPreflightResolvesToolsOnTheServicePATHincmd/context-guru-proxy. They come from TempDir file locks, POSIX file modes and a Linux service PATH.Data dependence
<record dir>/<account id>/, because replay must re-send the real prompts to reproduce real prefix-cache behaviour.What it does at each level:
--recordor--record-otlp, nothing is captured.Recording is all content, so it is a deliberate exception to "features use metadata only". The row in
docs/data-dependence.mdsays "Awaiting a decision (#649)". Once it is confirmed, I'll replace that with the name and date, as the other content rows do.🤖 Generated with Claude Code
Built only with -tags cg_record
The recorder is now in a build only when
-tags cg_recordis set. The default build,make buildand the release do not link OpenTelemetry, gRPC or protobuf.Binary size,
CGO_ENABLED=0 go build ./cmd/context-guru-proxy:origin/main-tags cg_recordWith the release flags (
-trimpath -ldflags "-s -w"): 36,360,354 B, 44,286,114 B, 36,380,834 B, 44,290,210 B in the same order.Build the recorder:
--record,--record-otlpand the other record flags exist in both builds. In the default build, a record flag logs one warning (this build has no session recorder; rebuild with -tags cg_record) and the proxy starts with recording off.record_tracesaccount column, its migration and the settings checkbox stay in every build. They are small. An account's opt-in survives a switch of builds.go.opentelemetry.io/,google.golang.org/grpcorgoogle.golang.org/protobufpackage. A mutation (remove the tag fromproxy/recexport.go) makes it fail.recordjob that builds, vets and tests (-race) the tagged variant.docs/reference/session-recorder.md.