Repository navigation
fix(apply): Split Claude Code's trailing reminders off tool outputs - #558
Conversation
Claude Code appends a <system-reminder> block with a token counter to every tool_result. The components saw it as part of the output, so on real Claude Code traffic: - format and toon declined, because the output was no longer JSON. - dedup declined, because the counter differs in every call. - extract_llm's code strategy paid for a call whose parser then failed. normalize now splits a trailing run of complete <system-reminder> blocks off each Anthropic tool_result before the pipeline runs. The slot keeps the block, and both writeback paths append it again. preText still holds the whole original, so an unchanged output stays byte-identical. On the issue's repro, the Claude Code shaped body now compacts 74.6% (format,toon) and 48.5% (dedup), against 0% before. Fixes #556 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
Review (two passes)
Two review passes ran on this PR. The second pass checked each finding from the first pass against the code. Verdict: ready to merge. All CI checks pass. ./apply/ and ./components/... tests pass on the PR head.
Suggested changes (not blocking)
- Add a regression test for the summarize (count-changed) write-back path with a trailing reminder. The current round-trip tests use only the equal-count path (dedup, format/toon).
writeBackToolText(apply/apply.go~1856) also re-appendsslots[k].tail, but no committed test covers it with a reminder in place. A temporary test that ran[summarize, extract_llm, cachesplit]with a trailing reminder on every tool_result passed: the surviving tool_result was compacted, the tail was re-appended once, and norole=tooltext leaked. This is the path that caused the live 400 errors, so a committed test is worth having. - Make the header comment in
apply/reminder.gomore exact. It says no component sees the reminders. That is true only for reminders at the end of tool_result text. Reminders in separate top-level text blocks next to a tool_result (the #457addSiblingpath, seetestdata/anthropic_tool_use.json) and in plain string user messages are not split, so components still see them. Those messages are never written back, so nothing leaks.
Low-severity notes
- Nested open tag (
apply/reminder.go:35).strings.LastIndex(rest, reminderOpen)picks the last open tag in the remaining text. If a reminder's text contains a literal<system-reminder>, the split lands in the middle of a block. Example:out\n<system-reminder>\nblah <system-reminder> x\n</system-reminder>gives bodyout\n<system-reminder>\nblah, so components get an unmatched open tag. Body plus tail still equals the original text, and Claude Code does not send nested tags. A fix is to pair the trailing close tag with the nearest unmatched open tag before it. Another fix is to document that nested tags are out of scope. - Scope. Only the Anthropic
/v1/messagestool_result branch innormalizecallssplitTrailingReminders. The OpenAI chat (role=tool) and Responses paths do not. The PR states this in its open questions. - Older issue, not caused by this PR. If one tool_result's
contentis an array of 2 or more text blocks, those slots share onetool_use_id.byID[id]=kinwriteBackToolText(~1838) andtoolSlotByID(~1744) then keep only the last slot. So on the count-changed path, the path and tail of the wrong slot can be used. The equal-count path uses slot position and is not affected. This PR does not make it worse. If you change this code later, key the map by slot position or by (id, block index).
Checked and correct
- When summarize drops or merges a tool message, its reminder goes with it. There is no leak and no duplicate.
- Write-back changes only the
contenttext.cache_control,is_errorand sibling blocks do not change. - Whitespace before the reminder stays in
tail. Body plus tail equals the original text, so an unchanged request stays byte-identical and the prompt cache is kept.
Assisted-By: Claude (Anthropic AI) [email protected]
Review follow-up for #558. - Add TestTrailingReminderSurvivesCountChange. It runs summarize, extract_llm and cachesplit over tool_results that end with a reminder. Each kept tool_result must end with its own reminder, once, and none may reach the wire as role=tool. Without the tail re-append in writeBackToolText, the test fails. - Make the reminder.go header comment exact: only a tool_result's own text is split. A reminder in a separate text block or a plain user message stays visible to the components. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
OsherElhadad
left a comment
There was a problem hiding this comment.
Review of #558
Verdict: the fix is correct for the shape it targets; merge after one required change (bound the block, see 1) and two small test additions. The premise in the PR text and #556 is narrower than stated (see "Premise"), so please reword it.
I ran real Claude Code sessions (2.1.290, 2.1.296 and 2.1.299) through a local proxy built from this branch (77b472f3) and from its base (67c5f758), with a stub model behind it, on synthetic fixtures (JSON, long logs, repeated reads, grep/find, a pytest-like run). Everything below is a paired run on the same fixtures, 2 runs per arm unless noted.
Premise: what Claude Code really sends
- 2.1.290 / 2.1.296 / 2.1.299 do not put the counter inside the tool result. Each tool_result turn is followed by a separate
{"role":"system","content":"<total_tokens>N tokens left</total_tokens>"}message.proxy/agentcompaction.goalready documents this shape for 2.1.296 (#518). The in-result block of #556 (2.1.241) did not reproduce on any of the three versions, with four different model names. - On that traffic this PR is a byte-for-byte no-op. Paired runs of base and head on native 2.1.299 traffic give identical component activity and identical upstream bodies (format 15,395 / dedup 9,054 / toon 5,484 tokens on the JSON task, on both builds). Nothing was broken there, so nothing is fixed.
- Captured production traffic agrees. In ~300k captured before/after tool outputs from real Claude Code sessions, none ends with the counter block. 691 (0.23%) do end with a trailing
<system-reminder>of another kind (instruction attribution, the TodoWrite nag, an auto-mode notice). So trailing reminders in tool results are real, just not this one. The PR splits those too, which is good, but the comment, the PR text and the issue should say "trailing reminders", not "the token counter on every tool_result". - To still exercise this code live, I folded each sibling counter message into the tool_result before it (the 2.1.241 shape) with a pass-through shim in front of the proxy. All "old shape" numbers below are from that replay.
Results, old (in-result) shape, house pipeline, mean of 2 runs per task
| Task | Component | base: tokens removed | head: tokens removed |
|---|---|---|---|
cat the same JSON twice, then jq |
format / dedup / toon | 0 / 0 / 0 | 15,395 / 9,054 / 5,484 |
| JSON + noisy log + source file | format | 0 | 11,163 |
| long log, pytest-like output (ANSI) | cmdfilter / textclean | 7,501 / 16 | 7,500 / 16 |
| grep / find / reads | searchfold | 9,404 | 9,408 |
| 60-line repeated retries + progress redraws | extract | 825 | 1,234 |
| system prompt with git snapshot (synthetic body) | cachesplit | 1,327 stable tokens | 1,327 (same) |
8 declarations named in toolfilter.remove |
toolfilter | 3,894 tokens | 3,894 (same) |
- On the JSON task, over the 3 requests of a run, the tokens sent fall from 48.7k to 18.8k on head and stay 48.7k on base (0%).
- cmdfilter, searchfold and textclean are shape-tolerant, so they fire on both builds. dedup, format, toon and extract do not, which matches #556.
- The model keeps seeing the reminder. Over all paired runs, every rewritten tool output on head (32 of 32) still ends with its own reminder and counter. On base, 12 of 22 rewritten outputs lost it, because cmdfilter and extract rewrote the text that included it. So the PR also stops dropping reminders.
- Prefix stability. Bytes of earlier messages that change between consecutive upstream requests are equal on base and head in every deterministic arm (86 to 129 per run old shape, 254 to 381 native). Two arms differ because the stochastic model took a different path (native extract_llm: 21.8k vs 10.2k bytes; the repeated-lines task: 1.5k on base vs 86 on head); I would not read either as an effect. Outputs no component touched are byte-identical to the client's. The cache-read share on the paired JSON task was 94.3% on head vs 81.6% on base; treat that as noise at n=2.
- cachesplit never fires on real 2.1.299 traffic: the git snapshot moved out of
systeminto the first user message, so there is nothing for it to split. Unrelated to this PR, worth its own issue.
extract_llm per strategy (old shape; the 26.8 KB JSON output, ~9.3k tokens)
| strategy | base | head |
|---|---|---|
code |
every call fails: json.decode ... unexpected character '<' (2 calls, 0 tokens saved) |
accepted, 8,619 tokens saved |
single |
rejected: below the keep-ratio floor | accepted, 8,619 |
rlm |
rejected: "dropped a referenced identifier" (the identifier is system-reminder) or keep-ratio |
accepted, 8,619 |
auto |
both legs rejected | accepted, 8,619 |
deterministic |
"result not smaller", 0 saved | 8,619 |
- Model calls over the 2 runs: base made 6, 6, 6 and 5 for code/single/rlm/auto; head made 3 for each. The second run is served from the extraction replay cache on head. On base it never hits, because the counter is part of the key. That is a real cost win this PR does not mention.
- With
code, the model spend over the 2 runs was 28% lower on head ($0.0135 vs $0.0188 at list rates), partly from that replay cache, while saving more. In the full house+extract_llm pipeline the JSON calls on base were 6 calls for 0 tokens. - Caveat: 8,619 is the same figure for every strategy, so it is dominated by the final projection, not by the model leg.
Correctness and edge cases
| Case | Result |
|---|---|
| several trailing blocks, block in the middle, unclosed tag, stray close | covered by the PR's tests, pass |
stray </system-reminder> at the end of an output that has an earlier open tag |
hides the output from every component (issue 1) |
| a legitimate-looking block of any size | a 64 KB block moved into the tail (issue 1) |
| array content with text, image, reminder-only text block | image kept, reminder-only block left whole, dedup collapses the repeated text and keeps its own reminder |
| OpenAI chat tool messages with a reminder-like tail | untouched, bytes equal, Changed=false |
| extract marker on an output with a reminder | marker, then the reminder; the stash holds the body only, so a restored copy carries no reminder, which is right |
| dedup of two outputs with different counters | repeat keeps its own counter (also checked live, 32 of 32) |
| token accounting | Run.TokensBefore/After are identical with and without the reminders (5,016 / 1,712 both), so saved tokens and saved USD never count them; tokens_before under-reports by ~20 tokens per output (nit) |
| cachesplit and keep-alive | splitVolatileTail runs before normalize and edits system only; keep-alive replays the forwarded body, reminders included. No interaction |
gofmt -l, go vet and go test -race ./apply/... ./components/... ./proxy/... at the PR head: clean and all pass.
Mutation checks on the three lines the PR adds in apply.go, run against the tests that exist:
- drop
+ s.tailinBodyOpts(line 824): caught. preText: outinstead of the whole text (line 1558): caught.- drop the trailing-whitespace trim in
reminder.go: caught. - drop
+ slots[k].tailinwriteBackToolText(line 1855): survives. With that mutant, every retained tool_result loses its reminder on any count-changing turn (summarize). The line is right; nothing tests it (issue 2).
Issues and suggested fixes
- Required: bound the block.
strings.LastIndex(rest, reminderOpen)pairs the final close tag with the last open tag anywhere, with no size or nesting check. Two real cases:HEADER + <sr>A</sr> + 50 KB of output + </sr>makes the body 6 bytes (the 50 KB is the "tail", invisible to every component), and a single 64 KB<system-reminder>block is hidden the same way. It is lossless (body+tail == text) but silently turns compaction off for exactly the outputs that quote these tags (for example reading this repo's own docs or a transcript). Suggested change, which passes the PR's 10 cases plus both probes:Add two table rows toconst maxReminderBytes = 4096 // counter ~90 B; other CC blocks < 1 KiB ... open := strings.LastIndex(rest, reminderOpen) if open < 0 || len(rest)-open > maxReminderBytes || strings.Contains(rest[open+len(reminderOpen):len(rest)-len(reminderClose)], reminderClose) { break }
TestSplitTrailingRemindersfor them. - Add a test for the count-changing path. Take
TestNoToolRoleOnAnthropicWireAfterCountChange, appendccReminder(i)to each tool body, and assert every surviving tool_result still contains<total_tokens>. It passes on this head and fails with line 1855's+ slots[k].tailremoved. - Reword the premise in the PR text, #556 and the
reminder.gocomment: the block is a trailing reminder, seen in-result on 2.1.241; 2.1.290 to 2.1.299 send the counter as a siblingsystemmessage. Say what real traffic the 0.23% belongs to. - Nit:
tool_reminder_test.goonly models the 2.1.241 shape. A one-line comment saying so avoids the next reader assuming current Claude Code looks like this. - Nit: say in the PR text that
tokens_before/tokens_afterexclude the reminders.
Separate: TestCalculatorPricesFromTheRowsModelNotABlend
The PR says it fails on unmodified main (3 of 3 runs). I could not reproduce that: it passes here, on x86-64. I ran the whole ./dash package with -count=2 on current main (4ada00e0), on this PR's base (67c5f758) and on this head: all three pass, both runs each. So it does not fail on unmodified main on x86-64, and it is unrelated to this change.
A likely cause, worth a separate issue: the test asserts a.PingUSDEach == 300_000*cheap.CacheRead+cheap.Output with exact float equality. On arm64, Go fuses x*y + z into a single FMA. Compiling the package for arm64, KeepAliveCalc (dash/keepalive.go:1383, float64(prefix)*p.CacheRead + p.Output) becomes an FMADDD, while the assertion's own expression has no floating-point instruction left (it is constant-folded with separate rounding). The two can differ in the last bit, but only on arm64. I could not run it on arm64, so treat this as a hypothesis. Comparing with a tolerance (math.Abs(a-b) < 1e-12) would remove the flake. If the author is on Apple Silicon, that would explain "3 of 3 runs".
|
|
||
| import "strings" | ||
|
|
||
| // Claude Code appends a context-awareness block to the end of every tool_result (#556): |
There was a problem hiding this comment.
Premise: this holds for Claude Code 2.1.241. On 2.1.290 to 2.1.299 the counter is a separate role:"system" message after the tool_result turn (see proxy/agentcompaction.go, #518), and in ~300k captured tool outputs none ends with the counter block. Trailing reminders of other kinds do exist (0.23%), and this function splits them too. Suggest rewording to "trailing reminder blocks" and naming the versions.
| if !strings.HasSuffix(rest, reminderClose) { | ||
| break | ||
| } | ||
| open := strings.LastIndex(rest, reminderOpen) |
There was a problem hiding this comment.
Required: LastIndex(rest, reminderOpen) pairs the final close tag with the last open tag anywhere in the output, with no size or nesting check.
HEADER + <system-reminder>A</system-reminder> + 50 KB of output + </system-reminder>gives a 6-byte body and a 50 KB "tail".- One 64 KB
<system-reminder>...</system-reminder>block at the end is moved into the tail the same way.
It is lossless (body+tail == text), but every component then sees an empty or tiny output, so compaction silently turns off for exactly the outputs that quote these tags. Suggested fix (passes the 10 existing cases and both probes):
const maxReminderBytes = 4096 // counter ~90 B; other Claude Code blocks < 1 KiB
...
if open < 0 || len(rest)-open > maxReminderBytes ||
strings.Contains(rest[open+len(reminderOpen):len(rest)-len(reminderClose)], reminderClose) {
break
}| continue | ||
| } | ||
| txt := schema.MessageText(out[i]) | ||
| txt := schema.MessageText(out[i]) + slots[k].tail |
There was a problem hiding this comment.
No test covers this line. Mutation check: deleting + slots[k].tail here keeps the whole ./apply suite green. With the mutant, every retained tool_result loses its reminder on any count-changing turn (summarize), because txt != preText is then always true when a tail exists. The code is right; please add a test. A copy of TestNoToolRoleOnAnthropicWireAfterCountChange with + ccReminder(i) on each tool body, asserting each surviving tool_result still contains <total_tokens>, passes here and fails with the mutant.
| out, tail := splitTrailingReminders(text) | ||
| tm := toolMessage(out, blk.Get("tool_use_id").String()) | ||
| pre, _ := json.Marshal(tm) | ||
| norm = append(norm, tm) |
There was a problem hiding this comment.
Nit: norm now carries the body only, so Run.TokensBefore/After and the dashboard's tokens_before/after exclude the reminder (checked: 5,016 tokens with and without three trailing reminders). Saved tokens and saved USD are unaffected (both sides exclude it), but the totals under-report what the upstream bills by ~20 tokens per output. Worth one sentence in the PR text.
| {"reminder and whitespace only", "\n\n" + r1, "\n\n" + r1, ""}, | ||
| {"unclosed tag", "out\n<system-reminder>\nno end", "out\n<system-reminder>\nno end", ""}, | ||
| {"stray end tag", "out\n</system-reminder>", "out\n</system-reminder>", ""}, | ||
| {"nested open in body", "a <system-reminder> b\n\n" + r1, "a <system-reminder> b", "\n\n" + r1}, |
There was a problem hiding this comment.
Please add the two cases from the review: a stray close tag at the end after an earlier open tag with a large body in between (expect the whole text to stay as body), and a single block larger than the cap (expect no split).
|
|
||
| // ccReminder is the block Claude Code appends to every tool_result (#556). The counter changes | ||
| // on every call, so two runs of one command never give identical text. | ||
| func ccReminder(left int) string { |
There was a problem hiding this comment.
Nit: this models the 2.1.241 shape only. A one-line comment saying so would stop the next reader assuming current Claude Code looks like this (2.1.290 to 2.1.299 send the counter as a sibling system message).
|
Follow-up on |
…ose tag Review follow-up for #558. splitTrailingReminders paired the final close tag with the last open tag anywhere in the text. An output that quotes the tags and ends with a stray close tag, or one large block, moved into the tail, so every component saw an empty or tiny output. Stop the split at a block over maxReminderBytes (4096) or one with a close tag inside it. - Add table rows for both cases, each caught by its own check, and one at the cap. - reminder.go: name the versions. 2.1.241 put the counter in the tool_result. 2.1.290 to 2.1.299 send it as a role:"system" message, and other trailing reminders still occur. - tool_reminder_test.go: say ccReminder models the 2.1.241 shape only. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
|
@OsherElhadad thank you for the review. All points are done.
I will update #556 separately.
|
| Build | Result |
|---|---|
| arm64 | fails 5 of 5: keepalivetab_test.go:442: ping cost = 0.03000500, want prefix x cache_read + one output token |
GOARCH=amd64 (Rosetta) |
passes 5 of 5 |
arm64, with dash/keepalive.go:1383 changed to float64(float64(prefix)*p.CacheRead) + p.Output |
passes 5 of 5 |
The explicit float64(...) conversion stops Go from fusing the multiply and add, so the FMA is the cause. Line 1094 uses the same expression. A fix is either that conversion at both lines, or a tolerance in the test. I did not change dash/ in this PR. I can open a separate issue or PR.
Assisted-By: Claude (Anthropic AI) [email protected]
Summary
Claude Code can end a
tool_resultwith one or more trailing<system-reminder>blocks. Before this fix, the engine compacted 0% of such outputs for the shape-sensitive components. Nownormalizesplits a trailing run of these blocks off each Anthropic tool output before the pipeline runs, and the write-back adds it again unchanged. The model still sees the reminders, and the components no longer see them in a tool output.Fixes #556.
Which traffic this applies to
tool_result:<system-reminder><total_tokens>N tokens left</total_tokens></system-reminder>.role:"system"message after the tool_result turn (fix(thread): a Claude Code compaction splits the main thread, so the status line freezes #518,proxy/agentcompaction.go). On that traffic this PR is a byte-for-byte no-op (@OsherElhadad, paired runs).What we found
With a trailing block left in the output (2.1.241 shape):
formatandtoondeclined, because the output was no longer pure JSON.dedupdeclined, because the counter changes on every call, so no two outputs are identical.extract_llmwithstrategy: codepaid for a model call, and the parser it wrote then failed on the<.cmdfilterandextractrewrote the text with the reminder in it, so the reminder could be lost. On base, 12 of 22 rewritten outputs lost it. On head, 0 of 32 did.What changed
apply/reminder.go: newsplitTrailingReminders(text) (body, tail).<system-reminder>…</system-reminder>blocks, with the whitespace around them.maxReminderBytes(4096), or one with a close tag inside it, is not split. This stops output that quotes the tags from going into the tail, where no component would see it.body + tail == textalways.apply/apply.go:normalizegives the componentsbody, and storestailon the slot.writeBackToolText) addtailback before they compare withpreText.preTextstill holds the whole original text. So an unchanged output stays byte-identical (I1), and the prompt cache is safe.Each output keeps its own reminder. When
dedupcollapses a repeat, the repeat still ends with its own current counter.How it was tested
TestSplitTrailingReminders, 14 cases: none, one, two, trailing whitespace, a block in the middle, reminder-only, unclosed tag, stray end tag, an open tag inside the output, a stray end tag after a short and a 50 KB quoted block, a block over the cap, and a block at the cap.apply.Bodyround-trip tests (these use the 2.1.241 shape):TestTrailingReminderDoesNotBlockDedup: two outputs that differ only in the counter collapse, and the repeat keeps its own reminder, once.TestTrailingReminderDoesNotBlockFormat: JSON plus a reminder is reduced, and the reminder comes back after the output.TestTrailingReminderInTextArray: the same for array-shapedtool_resultcontent.TestTrailingReminderUnchangedIsByteIdentical: with nothing compacted, the body comes out byte for byte.TestTrailingReminderSurvivesCountChange:[summarize, extract_llm, cachesplit]changes the message count and rewrites a kept tool output. Each kept tool_result ends with its own reminder, once, and no message goes out asrole=tool.Mutation checks: each of the two new conditions in
splitTrailingReminders, and the+ slots[k].tailinwriteBackToolText, has a test that fails without it.The issue's repro, run against
context-guru-proxybuilt from this branch (POST /compact, no upstream):format,toondedupformat,toondedupgo test ./apply/... ./components/...pass locally, and CI passes.Notes
Run.TokensBefore/Afterand the dashboard'stokens_before/tokens_afternow exclude the reminders, about 20 tokens per output. Saved tokens and saved USD do not change, because both sides exclude them./v1/messagestool results only. The OpenAI chat and Responses paths do not split anything.extract_llm's replay cache now hits on the second run, because the counter is no longer part of its key. Over two runs,strategy: codemade half the model calls and cost 28% less (@OsherElhadad).dash'sTestCalculatorPricesFromTheRowsModelNotABlendfails on arm64 only and is not related to this PR. See the comment below.Assisted-By: Claude (Anthropic AI) [email protected]