Skip to content

feat(record): record replayable session traces, opt-in per account - #649

Merged
amiddavid merged 24 commits into
mainfrom
record-phase1b
Nov 1, 2026
Merged

amiddavid merged 24 commits into
mainfrom
record-phase1b

Conversation

@michaljacovi

@michaljacovi michaljacovi commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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.
  • The request path does one non-blocking channel send. Translation, redaction and writing happen on a writer goroutine. Recording fails open: a full queue drops the call (counted, warned once), and it never delays or alters a request.
  • Consent has two gates: the operator's flag, and each account's own record_traces setting. 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.
  • Redaction: CG's internal/redact first, then the credential shapes it misses, then the recording person's identity (login, name, email).

What --record writes

One <session>.wire.jsonl per session, one line per call, with only the fields the format defines (kubernetes-sigs/inference-perf#820):

Field What it holds
path the API path, e.g. /v1/messages
request the request body as the client sent it, redacted
response the upstream response, redacted: the SSE text for a stream, else the JSON
status, start_unix, total_ms, model the call's outcome and timing
headers the client's request headers, with every credential header removed (Authorization, 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.WithDerivedTurns rebuilds 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):

  • The proxy no longer writes the claude-record corpus shape or rewrites a session's file every 10 s. Each call is appended once.
  • The offline corpus converter is gone. Nothing needs converting.
  • OTLP is a live export from the proxy, through the Go OTel SDK: OTLP/HTTP, a BatchSpanProcessor with a bounded queue, valid trace and span ids (the session UUID goes in session.id), service.name=context-guru-proxy plus the tenant id in hosted mode, and gen_ai.provider.name.
  • Size limits are flags: --record-body-cap (per body, after redaction, 1 MB), --record-tee-cap (per in-flight response, 8 MB), --record-queue (256 calls).

Rebased onto main 514b8be 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.

Run Result
go build ./..., go vet ./internal/record/ ./proxy/ ./tenant/ ./cmd/... pass
go test ./internal/record/ ./tenant/ ./components/all/ pass (components/all includes the data-dependence check)
go test ./proxy/ (recording, tenancy, capture, splice, control) pass
A file the recorder wrote, read by Inference-Perf's own wire loader every call converted; no credential in the file or the converted trace
3 live sessions recorded through CG and claude-record at once 216 of 216 calls, 23 of 23 turns match
Identity redaction on a real 3-hour recording login, surname and work email: 0 left; all bodies valid JSON

Other test failures on Windows also fail on main: nine in proxy (cache campaign, adapt, TestMailSinkFileIsOwnerOnly) and TestPreflightResolvesToolsOnTheServicePATH in cmd/context-guru-proxy. They come from TempDir file locks, POSIX file modes and a Linux service PATH.

Data dependence

  • Content: it keeps the full request and response body of each call, redacted, in <record dir>/<account id>/, because replay must re-send the real prompts to reproduce real prefix-cache behaviour.

What it does at each level:

  • Off: no recording. Without --record or --record-otlp, nothing is captured.
  • Metadata only: does not work. A trace without bodies cannot be replayed.
  • Everything: works, for accounts that opted in.

Recording is all content, so it is a deliberate exception to "features use metadata only". The row in docs/data-dependence.md says "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_record is set. The default build, make build and the release do not link OpenTelemetry, gRPC or protobuf.

Binary size, CGO_ENABLED=0 go build ./cmd/context-guru-proxy:

Build Size
origin/main 45,525,200 B
#649 before this change (1b2aa13) 56,998,663 B (+11.5 MB)
#649 now, default 45,549,059 B (+24 KB)
#649 now, -tags cg_record 57,002,753 B

With 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:

make build-record
CGO_ENABLED=0 go build -tags cg_record -o bin/context-guru-proxy ./cmd/context-guru-proxy
  • --record, --record-otlp and 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.
  • The record_traces account column, its migration and the settings checkbox stay in every build. They are small. An account's opt-in survives a switch of builds.
  • A guard test fails if the default build links any go.opentelemetry.io/, google.golang.org/grpc or google.golang.org/protobuf package. A mutation (remove the tag from proxy/recexport.go) makes it fail.
  • CI has a new record job that builds, vets and tests (-race) the tagged variant.
  • Doc: docs/reference/session-recorder.md.

@michaljacovi

michaljacovi commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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):

  • one JSONL line per HTTP call: path, request (the raw request body), response (the raw body, or the SSE text for a stream), status, start_unix, total_ms, and optional model and headers;
  • Anthropic Messages, Chat Completions and the Responses API are all supported;
  • the format is documented in wire_trace_converter.py.

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:

  1. The proxy records wire, redacted. Streamed responses are redacted across event boundaries, so a secret split over two events is caught. This part is built and tested.
  2. Phoenix is still served. One question for you: do you want OTLP sent live from the proxy (already built: OTLP/HTTP, batch processor, valid ids, session.id, OpenInference attributes), or made from wire afterwards?
  3. The corpus-file converter is not needed, and will not be part of this PR.

Unless you see a problem, I'll rework the PR this way. The content question (data-dependence) is the same for wire.

@amiddavid

Copy link
Copy Markdown
Collaborator

wire is fine.

@michaljacovi

Copy link
Copy Markdown
Contributor Author

@amiddavid, thanks. Wire is pushed:

  • --record <dir> writes Inference-Perf's wire format: one <session>.wire.jsonl per session, one line per call. Only the fields the format defines.
  • Both bodies are redacted. A streamed response is redacted across event boundaries, so a secret split over two events is caught.
  • headers are the headers the client sent, with every credential header removed (Authorization, x-api-key, cookies, x-context-guru-*, and any name with key, token, secret, auth, password or credential).
  • Checked with Inference-Perf's own loader on a file the recorder wrote: every call converted, and no credential in the file or the converted trace.
  • The corpus converter is gone. The eval team replays wire directly.

Phoenix: --record-otlp <url> is a proxy flag. With it, every recorded session is also sent live as OTLP. It is not made from wire afterwards. Does a flag on the instance work for you?

The branch is behind main. I'll rebase it before it is ready to merge.

michaljacovi pushed a commit that referenced this pull request Oct 22, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 22, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 22, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 22, 2026
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 pushed a commit that referenced this pull request Oct 27, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 27, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 27, 2026
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]>
michaljacovi pushed a commit that referenced this pull request Oct 27, 2026
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]>
@amiddavid

Copy link
Copy Markdown
Collaborator

@michaljacovi is this ready ? do u want us to merge it?

@michaljacovi
michaljacovi marked this pull request as ready for review October 27, 2026 14:54
@michaljacovi

Copy link
Copy Markdown
Contributor Author

@amiddavid, this is ready for review.

One thing needs you before merge: the trace-recording row in docs/data-dependence.md is Kind = content, so it needs your confirmation. If you're OK with it, I'll replace "Awaiting a decision (#649)" with your name and the date, as in the extract_llm_sweep row.

@michaljacovi

Copy link
Copy Markdown
Contributor Author

@amiddavid, yes, please merge. CI is green now: I pushed a gofmt fix and bumped golang.org/x/net to 0.60.0 for the trivy CVE (CVE-2026-78669), which the OTel exporter pulled in.

One thing first: the trace-recording row in docs/data-dependence.md is Kind = content. Do you confirm it? If so, I'll put your name and today's date in it, or you can merge and I'll follow up.

@amiddavid

Copy link
Copy Markdown
Collaborator

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator

Reviewer: GLM (one regression-only reviewer, started by the integrator on the owner's request)
Head: 1b2aa13
Verdict: Approve

I reviewed only one question: can this PR hurt a user who never turns recording on, and
can it delay or fail a request when recording is on. I did not review the recorder's
design, its redaction quality or its output format.

Findings

None blocking. I found no way this change hurts a non-recording user.

Non-blocking

  1. Binary size: +11.5 MB (45.5 MB -> 57.0 MB, about +25%). OpenTelemetry, gRPC and
    protobuf are linked in even when no record flag is passed. Startup itself is unchanged
    with the flags off: NewSessionRecorder("") returns nil before any MkdirAll,
    exporter or goroutine exists (cmd/context-guru-proxy/main.go:449, proxy/sessionrec.go:131).
  2. With recording ON, the tee copy runs on the request goroutine (proxy/proxy.go:2452,
    tee.write inside the stream loop, between w.Write and Flush). It is bounded at
    --record-tee-cap (default 8 MB) per in-flight response. This is inherent to retaining
    a streamed body and is documented; a slow disk or a dead collector cannot reach it.
  3. With recording ON and a dead OTLP collector, process exit can take up to ~30 s longer
    (recExport.Shutdown is bounded by recExportTimeout, proxy/recexport.go:41). Shutdown
    only; no request is delayed.
  4. The sniffer gate now includes h.recorder != nil (proxy/proxy.go:2437). With
    recording on but a tenant not opted in, and agg == nil, usage sniffing runs for a
    tenant whose turns are not recorded. Read-only work; nothing the client sees changes.
    In the shipped binary agg is always non-nil, so this is latent.

What I checked

1. The request path with recording off. With no --record and no --record-otlp,
Options.Record is nil, so Handler.recorder is nil. Per request the only new work is:

  • newRecCtx -> recordFor -> one nil check on h.recorder, returns the zero value
    (proxy/sessionrec.go:458-484). No JSON parse, no allocation.
  • In serve, one h.recorder != nil && rc.traceID != "" check before the tee is made
    (proxy/proxy.go:1791); the tee stays nil.
  • In streamRec, one nil check per streamed chunk (tee.write, proxy/proxy.go:2452).
  • The record block at the end of serve's defer is behind the same two-part gate
    (proxy/proxy.go:1885).
    The stream-through path, both buffered paths, header copying, status and flush order are
    byte-identical to main; stream is now a one-line wrapper over streamRec(..., nil)
    (proxy/proxy.go:2470). Tests confirm it: TestStreamRecForwardsIdenticalBytesWithAndWithoutTee,
    TestStreamRecNeverTruncatesTheClient, TestNilRecTeeIsInert, TestNilRecorderIsInert,
    TestRecCtxIsZeroWhenRecordingOff (proxy/rectee_test.go, proxy/sessionrec_test.go).

2. Fail open with recording ON. Record is a non-blocking send that drops and counts
when the queue is full (proxy/sessionrec.go:183). Redaction, translation, file writes and
OTLP export all run on the writer goroutine, each with its own recover. The OTLP side uses
the SDK's BatchSpanProcessor with a bounded 256-span queue that drops, so a dead collector
slows the exporter's own goroutine, not a request. A slow disk backs up the writer until the
queue fills, then turns drop. The record block in serve's defer is wrapped in its own
recover, so a recording panic reverts recording only. I found no path where a recorder error
reaches the client.

3. The tenant store. Migration v12 is one ALTER TABLE tenants ADD COLUMN record_traces INTEGER NOT NULL DEFAULT 0, appended last in migrations and applied by PRAGMA user_version
(tenant/tenant.go:1429, 1460), so an existing control DB gets it exactly once and every old
row reads as false. tenantCols appends t.record_traces last and scanTenant scans it last
(tenant/tenant.go:1468-1487) -- positions match. The UPDATE tenants SET ... column list
appends record_traces=? before WHERE id=? and the args append boolInt(next.RecordTraces), targetID in the same order (tenant/tenant.go:786-793) -- order matches. RecordTraces is
settable only through PATCH /api/me (ctlUpdateMe, proxy/control.go:1255), which calls
Update(t, t.ID, ...) with actor == target; the manager route PATCH /api/tenants/{id} has
no such field in its patch struct. tenant.Registry.Update refuses p.RecordTraces from any
actor whose ID differs from the target (tenant/tenant.go:671), so a manager can neither opt a
user in nor out. TestRecordTracesIsTheTenantsOwnConsent covers all four cases.

4. Startup and flags. All five new flags default to off/empty via envOr with empty
defaults. With both record flags empty, NewSessionRecorder returns (nil, nil) before any
I/O, the startup warning is skipped, and Options.Record stays nil. No existing flag changed.
--help runs clean on both old and new binaries (checked on the eval box).

5. Dependencies. OTel 1.47, grpc 1.84, protobuf 1.36.12 are new and used only by the
recorder. The x/ bumps are patch-level: x/crypto 0.55->0.57 is used only for argon2 password
hashing (tenant/password.go), x/sync 0.21->0.23 for singleflight/errgroup. All affected
packages' tests pass with -race. CGO_ENABLED=0 go build ./... succeeds. go vet ./...
is clean. Binary size above is the only user-visible change.

6. Dashboard UI. The 20 lines in dash/ui/app.js add one checkbox to the settings form and
one field to the save body. The checkbox is appended unconditionally whenever the form renders
(dash/ui/app.js:6601), next to the existing set-capture box, so $('#set-record') in
saveSettings cannot miss it on a rendered page. The save posts to /api/me, which is the
self-only route.

7. Tests. Existing tests still pass. Runs on the eval box (head 1b2aa13, synced by tar
into an empty dir):

  • CGO_ENABLED=0 go build ./... -- ok
  • go vet ./... -- ok
  • go test -race -count=1 ./tenant/... -- ok (34 s)
  • go test -race -count=1 ./proxy/... -- ok (466 s)
  • go test -count=1 ./internal/record/... -- ok
    The off-path has direct tests (listed under 1) plus the consent and nil-guard tests under 2
    and 3.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator

Reviewer: GLM (one regression-only reviewer, started by the integrator on the owner's request)
Head: ca25c68
Verdict: approve

Scope: only whether #649 can hurt a user who never turns recording on. The recorder's
own design, redaction and output format are out of scope.

Findings

None. I found nothing that can hurt a non-recording user, and nothing that delays,
fails or changes a request when recording is on.

Non-blocking

  1. The default build never runs recordflags_test.go's stub tests in CI. The record
    job runs -run TestDefaultBuildLinksNoOpenTelemetryGRPCOrProtobuf only, and the tagged
    run skips TestUntaggedBuildStartsWithRecordSet by t.Skip. TestWarnIfRecorderMissing
    does run tagged, so only the stub-contract test is untested in CI. I ran the full
    untagged ./cmd/context-guru-proxy suite on the eval box; it passes.
  2. warnIfRecorderMissing misses env-only --record-* flags. CG_RECORD_BODY_CAP=1
    alone does not warn. Correct anyway: those flags do not enable recording, so the
    warning would be noise.
  3. Default binary grows 24 KB (0.05%), from the golang.org/x bumps. Not noticeable.

What I checked

The new commit (ca25c68) itself:

  • proxy/recctx.go is a verbatim move of the code removed from sessionrec.go. I diffed
    the removed lines against the new file: identical, only the package/import header was
    added. No behavior change.
  • proxy/recoff.go stub: NewSessionRecorder returns nil, nil; Record/Close/Dir
    are nil-safe. sessionRecorder is unexported with no constructor that can return
    non-nil in the default build, and Options.Record is the only way in from main.
    A default build therefore cannot record at all.
  • main.go: warning first, then NewSessionRecorder (nil, nil → no fatal), and the
    RECORDING ENABLED log is inside if traceRec != nil. Startup is safe.

The default build (no tag):

  • CGO_ENABLED=0 go build ./... passes on the eval box.
  • go list -deps ./cmd/context-guru-proxy: 0 matches for go.opentelemetry.io/,
    google.golang.org/grpc, google.golang.org/protobuf.
  • Binary sizes on the box: default 45,549,123 B, merge-base 45,525,088 B (+24 KB),
    tagged 57,002,841 B. The 11.5 MB recorder cost is out of the default binary.
  • Started the default binary with --record /tmp/...: one warning
    ("this build has no session recorder"), then normal startup, clean shutdown. No fatal.
  • go vet ./... passes.

The guard test:

  • Passes untagged on the box.
  • Negative test, on a scratch copy: removed //go:build cg_record from sessionrec.go
    and recexport.go and deleted recoff.go — the test fails, naming the
    otel/grpc/protobuf packages. The guard is real.

The tagged build:

  • go build -tags cg_record ./... and go vet -tags cg_record ./... pass.
  • Smoke test: --record /tmp/... logs RECORDING ENABLED, creates the dir (0700),
    and shuts down with the cg.record: stopped counters line. Same behavior as 1b2aa13.

The request path with recording off (proxy/proxy.go, rectee.go, recctx.go):

  • chat calls h.newRecCtx(...) per request; with a nil recorder recordFor returns
    false at the first nil check and newRecCtx returns the zero recCtx. No allocation,
    copy, lock or goroutine.
  • serve gates the tee on h.recorder != nil && rc.traceID != "" — both false. The
    record block in the defer is behind the same gate. recTee.write is nil-safe, so
    streamRec costs one nil check per 16 KB chunk. The sniffer gate adds
    || h.recorder != nil, nil in the default build: unchanged.
  • Buffered paths (respBody assignments) are all behind if h.recorder != nil.
  • Response bytes, status, headers and flush timing to the client are untouched on the
    off path — streamRec writes the same bytes in the same order as stream did.
  • The full untagged ./proxy/... suite (hundreds of tests asserting response bytes,
    with the recorder nil as it always is untagged) passes with -race: that is the
    "recording off is unchanged" coverage.

Fail open with recording ON (for the team that turns it on):

  • Record is a non-blocking channel send with a drop counter and one loud warning.
  • The writer goroutine recovers panics at two levels; wg.Done is registered first, so
    Close cannot hang on a panicked writer.
  • OTLP export runs on the writer goroutine through a BatchSpanProcessor with a bounded
    queue; a dead collector cannot block a request. Close/Shutdown/flush are bounded
    by recExportTimeout.
  • The serve-side record block has its own recover.

The tenant store:

  • Migration v12 is ALTER TABLE tenants ADD COLUMN record_traces INTEGER NOT NULL DEFAULT 0 — additive; existing rows read as false. tenantCols appends the column and
    scanTenant reads it in matching order. The UPDATE column order matches its args
    (checked one by one).
  • Only PUT /api/me (ctlUpdateMe) accepts record_traces; the manager path
    (PATCH /api/tenants/{id}) has no such field, and Registry.Update refuses
    p.RecordTraces when actor.ID != targetID. A manager cannot turn it on or off for
    another account.
  • go test -race ./tenant/... and ./cmd/... pass on the box.

Dependencies: x/crypto 0.55→0.57, x/sync 0.21→0.23, x/sys 0.47→0.48, x/net →0.60
(CVE-2026-78669). Routine minor bumps; x/net/x/crypto were already vendored for
net/http. CGO_ENABLED=0 build verified. The 24 KB default-binary delta is the only
user-visible effect and is not noticeable.

Dashboard UI: the 20 lines add one checkbox in loadSettings and one field in
saveSettings's body, following the exact #set-capture pattern. !!t.record_traces
is false when the field is absent. The checkbox is appended before the parse_error
branch, so $('#set-record') exists whenever saveSettings can run.

Test runs (eval box, foreground, all pass):

  • untagged: go test -race -p 1 ./proxy/... (461 s), ./tenant/... (34 s),
    ./cmd/context-guru-proxy/... (36 s)
  • tagged: go test -race -p 1 -tags cg_record ./proxy/... ./internal/record/... (466 s)
  • All scratch dirs on the box removed afterwards.

`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]>
@amiddavid

Copy link
Copy Markdown
Collaborator

Performance test and how to build the recorder

Result: a proxy that does not record is as fast as main. Only recording itself costs CPU and memory.

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-proxy

Then start it with --record <dir> (or CG_RECORD_DIR), and/or --record-otlp <url> (or CG_RECORD_OTLP).

Turn recording off

  • For the whole proxy: remove --record and --record-otlp (and CG_RECORD_DIR, CG_RECORD_OTLP), then restart the proxy. No rebuild. The cg_record binary without these flags records nothing and runs as fast as main (build C below).
  • For one account (hosted mode): the account clears its own record_traces setting (Settings checkbox). It takes effect on the next request, with no restart. Only the account itself can change it. A manager cannot.
  • There is no switch that stops recording for the whole proxy without a restart.

The builds tested

Build What it is Binary size
A main (fc52617) 36.38 MB
B this PR (9c3771d), default build 36.40 MB (+16 KB)
C this PR, -tags cg_record, not recording 44.33 MB (+7.9 MB, +22%)
D build C, started with --record <dir> 44.33 MB

D records every request. This is the worst case for the internal deployment.

Results

Each cell is the median of 3 runs. Latency is p50 in ms. Memory is peak RSS (VmHWM). CPU is in kernel ticks for the whole run.

Default preset (house):

Response Concurrent A latency B latency C latency D latency A / D CPU A / D memory
JSON, 2 KB 1 8.37 8.12 8.18 8.96 2,552 / 4,607 126 / 185 MB
Stream, 64 KB 1 9.54 9.23 9.33 10.07 2,547 / 4,769 294 / 420 MB
Stream, 1 MB 1 15.25 15.25 14.69 16.42 2,093 / 3,767 292 / 994 MB
JSON, 2 KB 16 33.43 33.00 33.47 31.43 4,727 / 5,009 218 / 288 MB
Stream, 64 KB 16 31.38 30.92 31.17 30.34 4,765 / 5,292 476 / 637 MB
Stream, 1 MB 16 41.63 40.88 41.04 36.91 3,690 / 3,620 469 / 1,210 MB

off preset (the proxy's own cost only):

Response Concurrent A latency B latency C latency D latency A / D memory
JSON, 2 KB 1 4.03 4.05 4.05 4.73 120 / 171 MB
Stream, 1 MB 1 10.40 10.49 10.56 11.90 279 / 971 MB
Stream, 1 MB 16 23.51 22.86 22.98 22.42 537 / 1,198 MB
  • A, B and C match on latency, time to first byte, requests per second, CPU and memory, within the run-to-run spread.
  • The Go benchmarks: B and C allocate the same bytes and the same number of times per call.
  • Errors: 0 in every run.

What recording costs (build D), for sizing the internal deployment

  • CPU: about 1.9 times per request with one request at a time.
  • Memory: on 1 MB streams, about 1 GB peak instead of about 290 MB with one request at a time, and about 1.2 GB instead of about 0.5 GB with 16 at a time. --record-tee-cap (8 MB by default) and --record-queue (256 by default) set the upper limit.
  • Latency: up to about +1.5 ms p50 with one request at a time. No increase with 16 at a time.

How it was tested

  • A local fake upstream on the eval box. It answers a 2 KB JSON reply, a 64 KB stream or a 1 MB stream, sent in 16 KB chunks.
  • One proxy at a time, with the dashboard on. The request body is a 49-message conversation that uses tools.
  • A 200-request warm-up, then 2,000 requests (1,000 for 1 MB). Builds A to D alternate, 3 runs each.
  • The numbers are from a shared box, so differences under about 5% are noise.

@amiddavid

Copy link
Copy Markdown
Collaborator

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

  1. The proxy is the cg_record build (make build-record).
  2. The proxy starts with --record <dir>, --record-otlp <url>, or both. These flags only make recording possible. With no account opted in, nobody is recorded.
  3. The proxy runs in hosted mode, with accounts. In single-tenant mode, --record records every request.

How a user turns it on

  1. Sign in to the dashboard with your own key.
  2. Open Settings.
  3. Tick "Record my sessions as research traces" and save.
  • It applies from the user's next request.
  • To stop, untick the box and save. This also applies from the next request.
  • A script can do the same with PUT /api/me and {"record_traces": true} (or false), with the user's own key.

Rules

  • The box is off for every account by default.
  • Only the account owner can change it. A manager cannot turn it on or off for another user. The API refuses it (tenant/tenant.go). This is consent by design.
  • The box has no effect without the cg_record build and a --record flag. The text under the box says so. A user's choice is kept across a switch between builds.
  • The page warns the user before they tick it. Recording writes the full request and response of every call, after redaction, to the server. The redactor is best effort, so some secrets can pass through.

Turn recording off for everyone

Remove --record and --record-otlp (or CG_RECORD_DIR and CG_RECORD_OTLP) and restart the proxy. No rebuild is needed. There is no switch that does this without a restart.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants