Repository navigation
perf(apply): the rewrite path was mostly harness, not components - #72
Merged
OsherElhadad merged 27 commits intoAug 17, 2026
Merged
Conversation
added 13 commits
August 16, 2026 18:48
…st correlation The proxy had slog calls but no logging: no handler was ever installed, so DEBUG went nowhere, and the only per-component lines came from metrics.Slog at INFO with neither tenant nor session on them — several lines per request, burying the request itself. Four things: - internal/logging owns the level/format/sink decision (CG_LOG_LEVEL, CG_LOG_FORMAT, CG_LOG_FILE) and installs the default handler. Local use needs no configuration: text on stderr. CG_LOG_FILE adds a JSON sink for a log shipper and is the ONLY thing that makes logs leave the box. CG_LOG_PLAIN=1 opts out entirely, swapping in the stdlib's own text handler. - Credentials are scrubbed on the way OUT, so a careless call site added later cannot leak one — which matters more now that the caller's own provider key flows through request handling. A ReplaceAttr covers attribute values (including the ones baked in by Logger.With) and a wrapper handler covers the message. The patterns are the ones dash already used: they moved to internal/redact and dash/redact.go delegates, because two copies of a credential denylist is one copy that goes stale. - Every line of one request's lifecycle carries the tenant id — never its token — and, from the point apply resolves it, the session. The logger travels in the request context, which is why no component signature changed. - The lines say what was DECIDED, not just what happened: one INFO per request, and at DEBUG the cached-prefix boundary, the bypass gate, the expand loop's resolved-against-unresolved counts, why a stream had to be buffered, and one line per component with its verdict, token delta and the gates that turned candidates away. Those gate names and counts are read off the same Report.Gates map /stats sums into components.<name>.gates, so a log line and the metric cannot disagree. Signed-off-by: Osher-Elhadad <[email protected]>
The default hosted pipeline ([format, dedup, failed_run, cmdfilter, extract,
cachesplit], sync) spent most of its CPU re-doing work it had already done. A
CPU profile over 24 real captured Claude Code requests (median 600 KB, 71
messages) attributed the rewrite path as: normalize 44%, wireBreakpoints 22%
(and it runs twice per request), a full transcript deep-clone per component 10%.
None of that is component work.
Six changes, each measured on that capture, output verified byte-identical:
- wireBreakpoints walked the body with seven `#.field` gjson queries, each a
full re-scan that squashed every matched array. Now one pass over the
top-level object, with a substring prefilter before any structural parse
(neither spelling can be a field if "cache" is not even in the bytes), and
the post-rewrite cap re-count only when something actually changed — an
untouched body still carries exactly the inbound count.
- The pipeline deep-cloned the whole transcript per component for its revert
snapshot. It now keeps ONE snapshot and re-clones only the messages a
component changed; a revert re-establishes an independent copy, because
req.Input then aliases the one we were holding. Every snapshot entry is
still exactly one clone of a live message, so fidelity is unchanged — two
new tests fail without either half.
- The lossless round-trip check (two unmarshals into `any` plus a DeepEqual)
ran for all ~70 messages up front; it only matters for a message a component
changed, so it is computed on demand.
- Every normalized message was marshalled twice: once in normalize, once for
the count-change rebuild path only summarize takes. The rebuild now reads
slot.pre.
- normalize called encoding/json.Unmarshal on a type that implements
json.Unmarshaler, so encoding/json contributed nothing but a checkValid
re-scan of bytes gjson had already parsed — 40% of the unmarshal cost. It
calls UnmarshalJSON directly, and fetches each message's `content` once.
- ContentKey is memoized (like internal/tokens.Count): every offloader asks
skipReduce about every candidate, so one request normalized and sha256'd the
same tool output three or four times. Keyed by (len, hash) — a wrong key
here would mean a wrong stashed original, unlike a stale token count.
Measured, 24 real captured requests, same test code both sides:
end-to-end 552.6 ms -> 253.3 ms (-54%)
one median req 15.6 ms -> 6.9 ms (-56%), 9554 -> 3232 allocs (-66%)
per-component duration_ms, pipeline total 1.75 ms -> 1.06 ms (-39%)
live /compact through the proxy, 73 requests, median 37.1 -> 19.2 ms
live LLM calls through the gateway, cg_added_ms_avg 37.1 -> 25.8
Byte-identical output verified over 373 real captured requests (73
Terminal-Bench + 300 SWE-bench) via a golden hash of every rewritten body, with
the hashes recorded on the unmodified code. Fail-open, never-worse and
reversibility are untouched; the #32 replay test still puts breakpoints on the
wire for 72 of 73 requests.
What did NOT help and was reverted: prefiltering normalize's content walk on a
"tool_result" substring (no measurable change — real user messages nearly all
carry one).
Signed-off-by: Osher-Elhadad <[email protected]>
Grafana stores no logs, so something had to. Loki wins on the property that matters more than any feature comparison: it is read through the Grafana already running on this box, so a latency spike on the service dashboard is one click from the log lines for the same tenant and the same minute — one thing to secure, back up and explain. Its storage model is also the same shape as the Prometheus beside it: a single binary indexing a handful of labels, chunks on the local filesystem, one more container. Elasticsearch would search better and wants a JVM and gigabytes of RAM on a box whose job is serving agent traffic; ClickHouse is a better analytical store than reading logs is an analytical problem; files and grep — kept as the fallback — cannot answer "every line for this tenant's session over three days" without a human and an ssh session, which is the question this exists for. - `install.sh grafana` now brings up all four containers, loopback only, and installs the logrotate snippet. `grafana-status` checks Loki's readiness (not just its port — it answers while the ingester still rejects pushes), that the log file exists, that lines actually arrived in the last ten minutes, and which tenants Loki has seen. That last set of checks exists because a healthy promtail in front of an empty log directory renders an empty dashboard with no error anywhere. - The proxy never talks to Loki. It writes the journal always and CG_LOG_FILE as JSON when set; promtail owns delivery and remembers its position. A shipper inside the process being debugged loses exactly the logs you need when that process is what is going wrong. - `tenant` and `level` are Loki labels; `session` and `component` deliberately are not — a session label would mint one stream per agent conversation and eventually take the index down. They are read out of the JSON at query time, which is what the dashboard's two text fields do. - The logs dashboard filters by tenant, session, level and component, and its gate table answers "the component did nothing and I cannot tell why" off the same Report.Gates map /stats sums. Single-tenant proxies log tenant="local" rather than an empty string, which promtail would drop — leaving the selector empty for exactly the people running this locally. Signed-off-by: Osher-Elhadad <[email protected]>
A request row recorded what happened to a request but nothing about what the
request ASKED for, so the levers that explain a cost were invisible: reasoning
effort, thinking budget, sampling parameters, and — the one this project exists
to reason about — where the prompt-cache breakpoints sat.
Capture, normalized across both dialects (Anthropic `output_config.effort` /
`thinking.{type,budget_tokens}` / object `tool_choice` / block `system`; OpenAI
`reasoning_effort` / `max_completion_tokens` / string `tool_choice`), plus the
provider's stop reason off the same response bytes the token tiers come from.
Real columns, not a JSON blob: every field is either GROUPED BY in an aggregate
or shown on the row, so a blob would put json_extract() in the middle of every
aggregate and give free text somewhere to hide from the redactor. The sampling
columns are NULLABLE because "unset" and "0" are different facts and 0 is a
legitimate value — a sentinel would make a deterministic request read as an
unspecified one.
Client-supplied metadata is attacker-influenced input, so each text field passes
through a credential-shape check and an identifier-shape bound BEFORE the insert,
never on read. Unrecognized-but-harmless values survive verbatim: a dashboard
that renders ordinary data as «redacted» lies about its own coverage.
Breakpoints ride on apply.Trace, split by location, from the count the pipeline
already makes to respect the provider's cap of four — so placement costs the
request path nothing. The remaining fields are one structural pass over the
top-level object, measured at 0.55 ms/MB against 2.7 ms/MB for a per-field query
loop, and it never parses `messages`.
/api/breakdown groups requests, tokens and spent-vs-saved by one allowlisted
dimension, so per-model cost, cost by reasoning effort and cost by breakpoint
count are one query rather than three that can drift. Per-day usage bars need no
new query at all: bucketing already happens in SQL, so a day is a parameter.
Schema version 6 — the intended migration for a derived view: the old file is
renamed aside and the non-derived tables carried across.
Signed-off-by: Osher-Elhadad <[email protected]>
Left behind by the switch from a per-field query loop to the single pass; a package-level var nothing reads is not a compile error, so nothing caught it. Signed-off-by: Osher-Elhadad <[email protected]>
…s tenant logging.Debugging(ctx) is the single guard for "is anyone reading DEBUG", used by apply's decision loop and extract_llm's candidate accounting instead of each one reaching for Enabled(). And BodyOpts's panic recovery now logs through the request's own logger — a panic is the line you most want attributed to a tenant, and it was going out on the default logger with nothing on it. Signed-off-by: Osher-Elhadad <[email protected]>
The UI reads all fifteen fields as top-level keys, which holds only while Meta is embedded anonymously; a json tag on that field would nest them and blank the request drawer with nothing else failing. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
The pipeline snapshots messages before each component so it can revert on error/panic/never-worse. When the JSON round-trip clone fails, fallbackClone falls back to bifrost's DeepCopyChatMessage — and per [email protected]/schemas/utils.go its block copier (deepCopyChatContentBlock, l.803) copies only Type, Text, Refusal, ImageURLStruct, InputAudio and File. ChatContentBlock also carries three non-OpenAI fields (chatcompletions.go l.1122-1128): CacheControl, Citations and CachePoint. All three were silently dropped. So on that path a revert did not restore the message, it degraded it: a request that arrived with cache_control on a block came back out without it. That is the never-worse invariant broken on the least visible path — the one that only runs after something else already went wrong — and it is not cosmetic here. A dropped breakpoint is a full cache write instead of a cache read, ~12.5x the price, and getting breakpoints onto the wire is the entire point of cachesplit/cacheinject. The clone now restores the three fields after bifrost's copy, cloning the pointer values (TTL/Scope/Enabled) rather than sharing them, so snapshot and live message stay independent in both directions. The failure is reachable, not theoretical: ChatMessageContent.MarshalJSON errors when a message carries both string and block content, which a component can produce, and that is what the new test builds. TestFallbackCloneKeepsCacheFields fails on the parent commit ("revert dropped cache_control: a prompt-cache breakpoint is gone from the wire") and passes here. Output equivalence unchanged: golden hashes still match over the same 373 real captured requests (73 Terminal-Bench + 300 SWE-bench), the #32 replay still puts breakpoints on the wire for 72 of 73, and the latency benchmarks are unmoved (253 ms over 24 requests, 6.5 ms median request, 3222 allocs) since this path is off the hot path. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]> # Conflicts: # proxy/proxy.go
…ssage The writeback ran sjson.SetBytes over the WHOLE body per changed message. sjson allocates and copies the entire request for every write, so the cost was O(k * body): 30 rewritten tool outputs on a 600 KB request copied ~18 MB to produce one 600 KB result. Each write also re-scanned the body with gjson to find its target, and applyMetaWrites did the same once per metadata key. Now each changed message's own bytes are edited and all of them are spliced back in one pass. The output is byte-identical, not merely equivalent JSON, because sjson's splice is local: appendRawPaths ([email protected]) emits json[:res.Index], recurses into that subtree's Raw, then appends json[res.Index+len(res.Raw):]. Editing a message and putting it back at the message's span is therefore the same bytes as editing at "messages.<i>.<rest>" on the whole body. Everything outside an edited span is copied verbatim, which is what invariant I1 requires. Two things make that safe rather than clever: - Spans come from the offsets gjson already produced for each message, plus the byte shift splitVolatileTail now reports (it rewrites the top-level `system` value, so everything after it moves). Re-parsing the messages array to find the spans instead was the obvious version and it was SLOWER than what it replaced: measured on the median captured request, one array parse is 1.21 ms against 0.44 ms for a whole-body sjson write, so it only paid above ~3 rewrites per request. That version was a 13% regression; this one has no extra parse, and drops one that rebuildCountChanged was already duplicating. - gjson documents Index as "zero means index unknown" and it is relative to whatever json the Result came from, so no span is trusted on its word: the body's own bytes at that span must equal the message's Raw or the splice declines and the original request is forwarded. A wrong offset therefore costs a rewrite, never a corrupt body. The shift needs its own test, because captured traffic cannot cover it: Claude Code orders the body `messages` before `system`, so the split shifts nothing on real requests, and json.Marshal of a map sorts keys the same way. TestSpliceRewrites- EveryMessageAtItsOwnSpan builds the body with `system` first and both splits and rewrites in one request; it fails (fail-open, no rewrite forwarded) with the shift hard-coded to 0 and with it off by one. Measured, 24 real captured requests: end-to-end 253.6 ms -> 243.5 ms (-4.0%) bytes allocated 167 MB -> 144.5 MB (-13.4%), allocs unchanged one median request 6.61 ms -> 6.60 ms (flat) Per-component duration_ms is untouched by construction — pipeline.runOne's timer wraps the component call, and this is all after it, so the -39% stands. Output verified byte-identical over 1868 real captured requests (73 Terminal-Bench + 1795 SWE-bench) against golden hashes recorded before the change, and the #32 replay still puts breakpoints on the wire for 72 of 73. applyMetaWrites now takes the message rather than the body, since metaWrite.path was already message-relative; bodyIndexOf is gone, splitSlotPath does that job. Signed-off-by: Osher-Elhadad <[email protected]>
Both sides rewrote the breakpoint counter for different reasons, and both reasons stand. Reconciled to ONE implementation: the perf branch's single structural walk (ParseBytes().ForEach + mayHold/elemMarks), accumulating into the metadata branch's location-split Breakpoints instead of one int. The split is what feeds the four dashboard columns; the single pass is what takes the counter off ~22% of the rewrite path. Neither needed the other's implementation — the walk already knows which top-level key it is under, so the location comes out free, where the 7-path form had to derive it from the query string. wireBreakpoints stays as the one-line Total() wrapper the cap check calls. Kept from fix/clone-and-writeback: the conditional re-count (an untouched body carries exactly the inbound count, so n > inbound is false by construction), the duplicate normPre marshal loop's removal (slot.pre already holds it), and the spliceMessages writeback with its fail-open span check. Kept from the observability work: every DEBUG line behind its `debug` guard, dumpToolOutputs, and the cap-breach ERROR — now on the session-bearing context logger, which is why it no longer repeats "session" as an attribute. sort.Ints was the only caller of "sort"; slices was already imported for formatGates, so spliceMessages uses slices.Sorted(maps.Keys(edits)). Verified: gofmt/vet clean, go test -race green. Byte-identity goldens reproduce on 373 captured requests (73 terminal-bench + a 300-request swebench prefix). The merged counter returns the same per-location numbers as the 7-path version on 3736 real bodies (every captured request, inbound and post-pipeline). #32 replay: breakpoints reach the wire on 72 of 73. Per- component duration_ms unchanged — components/pipeline.go is byte-identical to the perf branch and Pipeline.Run holds the same cumulative CPU. Signed-off-by: Osher-Elhadad <[email protected]>
added 14 commits
August 17, 2026 06:50
Resolving the connect-ibm-service.md conflict took the credential branch's version wholesale, because its facts were current and the prose branch's were stale. That discarded the prose branch's anchor fix: use-with-claude-code.md's 'The one-liner' heading had become 'Steps', and hosted.md was repointed while this file was not. mkdocs build --strict catches it; the merged tree did not build until now. Both docs branches passed on their own - taking one side of a conflict wholesale is what lost it. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit df749b5)
Resolving the connect-ibm-service.md conflict took the credential branch's version wholesale, because its facts were current and the prose branch's were stale. That discarded the prose branch's anchor fix: use-with-claude-code.md's 'The one-liner' heading had become 'Steps', and hosted.md was repointed while this file was not. mkdocs build --strict catches it; the merged tree did not build until now. Both docs branches passed on their own - taking one side of a conflict wholesale is what lost it. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit df749b5)
…e median The regression this guards - content redaction on the request goroutine, ~53ms - is unconditional work, so it lands on every sample including the fastest. Contention only ever makes a sample slower. The minimum is therefore the statistic least polluted by the machine while staying fully sensitive to the defect. The median gate failed roughly one run in three on a loaded box, with the package run alone. A gate that reports the machine rather than the code gets ignored exactly when it is right. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit a2b665c)
…e median The regression this guards - content redaction on the request goroutine, ~53ms - is unconditional work, so it lands on every sample including the fastest. Contention only ever makes a sample slower. The minimum is therefore the statistic least polluted by the machine while staying fully sensitive to the defect. The median gate failed roughly one run in three on a loaded box, with the package run alone. A gate that reports the machine rather than the code gets ignored exactly when it is right. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit a2b665c)
A fixed 5ms budget cannot mean the same thing at both ends of this machine's range. Idle, a fake-upstream request settles near 1-2ms; with the suite saturating 16 cores its own median was 331ms. The gate was reporting the machine, failing about one run in three with nothing wrong. Budget is now max(5ms, 10% of the measured baseline), which catches the ~53ms regression at any baseline while contention that slows both handlers equally cannot trip it. The median stays the statistic: the minimum was tried and is worse, being one unaveraged sample - in one run the paired medians differed by 1.27ms where the paired minima differed by 8.13ms. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 3aad033)
A fixed 5ms budget cannot mean the same thing at both ends of this machine's range. Idle, a fake-upstream request settles near 1-2ms; with the suite saturating 16 cores its own median was 331ms. The gate was reporting the machine, failing about one run in three with nothing wrong. Budget is now max(5ms, 10% of the measured baseline), which catches the ~53ms regression at any baseline while contention that slows both handlers equally cannot trip it. The median stays the statistic: the minimum was tried and is worse, being one unaveraged sample - in one run the paired medians differed by 1.27ms where the paired minima differed by 8.13ms. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 3aad033)
The limiter is charged before the argon2 verify, deliberately, because 64 MiB per attempt is itself an amplifier. So the attempts the loop is allowed each pay a full KDF, and on a contended machine those can outlast the limiter's own one-minute window - at which point the earliest attempts have aged out and the bound correctly did not fire. From inside the test, "not limited" and "the window expired underneath us" are indistinguishable, and failing on the second is a test reporting the machine rather than the code. It now skips with the elapsed time named when the loop outran the window, and still fails outright when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 26e8e50)
The limiter is charged before the argon2 verify, deliberately, because 64 MiB per attempt is itself an amplifier. So the attempts the loop is allowed each pay a full KDF, and on a contended machine those can outlast the limiter's own one-minute window - at which point the earliest attempts have aged out and the bound correctly did not fire. From inside the test, "not limited" and "the window expired underneath us" are indistinguishable, and failing on the second is a test reporting the machine rather than the code. It now skips with the elapsed time named when the loop outran the window, and still fails outright when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 26e8e50)
… conclude Same root cause as the sign-in limiter test: each registration the loop is allowed hashes a password with argon2 at 64 MiB, so on a contended machine the allowed attempts outlast the limiter's one-minute window and age themselves out. The bound then correctly does not fire, which from inside the test looks exactly like the bypass it is checking for. It now skips with the elapsed time named when the loop outran the window, and still fails when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 0531c36)
… conclude Same root cause as the sign-in limiter test: each registration the loop is allowed hashes a password with argon2 at 64 MiB, so on a contended machine the allowed attempts outlast the limiter's one-minute window and age themselves out. The bound then correctly does not fire, which from inside the test looks exactly like the bypass it is checking for. It now skips with the elapsed time named when the loop outran the window, and still fails when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 0531c36)
…ter tests The form's own minlength=12 was refusing registration before the server saw it. Server, form and hint now all say 8; the mailed code, the 5-attempt cap, the per-email and per-address rate limits and a 64 MiB argon2id hash are what bound online guessing. The limiter tests are timed because each attempt they are allowed pays a full KDF, so on a loaded machine they outlast the one-minute window they exist to exhaust - which reads as a bypass when it is not. Signed-off-by: Osher-Elhadad <[email protected]>
…ter tests The form's own minlength=12 was refusing registration before the server saw it. Server, form and hint now all say 8; the mailed code, the 5-attempt cap, the per-email and per-address rate limits and a 64 MiB argon2id hash are what bound online guessing. The limiter tests are timed because each attempt they are allowed pays a full KDF, so on a loaded machine they outlast the one-minute window they exist to exhaust - which reads as a bypass when it is not. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
changed the base branch from
stack/3-metadata-and-logging
to
feat/hosted-tls-and-agent-compaction
August 17, 2026 08:29
OsherElhadad
merged commit Aug 17, 2026
61ce358
into
feat/hosted-tls-and-agent-compaction
5 checks passed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on the PR below.
Profiling said the components were not the problem. On real captured Claude Code traffic (73 requests, median 600 KB / 71 messages) the components' own logic was ~9% of the rewrite path.
normalizewas 44%,wireBreakpoints22% (seven full-body gjson scans, run twice per request), a full transcript deep-clone per component 10%, and re-hashing the same tool output 3–4× another 5%.The per-component
duration_msin the dashboard excluded the clone and the baseline tokenization, so the visible milliseconds were understating the real cost rather than pointing at it.Measured effect, paired A/B against a baseline worktree:
duration_mstotal: 1.75 → 1.06 ms (−39%) — same −39% with caches cold, so it is not memoization flattering the numbercg_added_ms_avg37.1 → 25.8 ms, and 73/73 compaction outputs byte-identicalOutput equivalence is proven, not assumed: every rewritten body hashed on the unmodified code first, then re-verified after each change, over 1,868 real captured requests. No captured body is committed — the test reads gitignored local paths and skips without them.
One optimization was reverted for not helping (a
tool_resultprefilter: 271 vs 273 ms).A latent correctness bug fixed with it.
bifrost.DeepCopyChatMessagedoes not copyCacheControl,CitationsorCachePoint, so on the fallback clone path a component revert silently dropped prompt-cache breakpoints — a full cache write at roughly 12.5× the read price, on the path that only runs when something already went wrong.A test that could not fail. The byte-shift test initially passed against a deliberately broken shift: Claude Code orders
messagesbeforesystem, so the split shifts nothing on all 1,868 real requests, andjson.Marshalof a map sorts keys the same way, reproducing the blind spot. Rebuilt withsystemfirst and mutation-checked — shift forced to zero and off-by-one both fail now, and both fail open.sjson'sReplaceInPlaceis deliberately unused: withstringifyit returns the input unchanged with a nil error when a value needs escaping, which would drop rewrites while reporting success.