Repository navigation
fix(offload): keep and mark the last tool exchange after a splice - #727
Conversation
After cache_aware_summarizer spliced a summary in, every following turn
re-wrote the whole kept history to the cache. The provider never reads a
cache entry that ends at a text turn on the next request; it reads one
that ends at a tool_result. The splice folded every tool exchange into
the summary, so the kept history was text turns only.
Two parts, only when the summarizer splices:
- A fresh summary span now ends before the last tool exchange, so that
tool_use and its tool_result stay verbatim (retreatPastLastToolExchange).
- The summarizer names that tool_result in Ctx.CacheAnchorToolID, and
apply's count-changing rebuild writes one {"type":"ephemeral"}
cache_control onto it in the raw body.
The breakpoint is added only if the rebuilt body has fewer than 4, the
provider's cap; otherwise it is skipped and counted. /stats gains
cache_anchor_written, cache_anchor_no_slot and cache_anchor_not_found.
Live, on real Claude Code traffic: the turn after a splice read 20,975
(system, tools, summary and the kept exchange) and wrote 134, against a
read of 13,438 and a write of 992 before.
Fixes #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
cache_aware_summarizer now keeps the last tool exchange outside a fresh span (#723). Three tests still asserted the old span: - the split-group rebuild test expected the group summarized away; it is the last tool exchange, so it is now kept whole (still never split); - the marker-text span test computed its expected span without the retreat; - the duplicate-skip test saved a checkpoint for the un-retreated span. Refs #723 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 5f501e036b71 |
blocking |
Verdict: blocking
Findings
- apply/apply.go:784 — an equal-count splice gets no cache anchor, and no counter moves
- What fails: a checkpoint whose span is one text message (
CoveredCount == 1). On the splice turn,tryReusebuilds[head, summary, tail]with the same message count as the input. The rebuild branch runs only whenlen(chat.Input) != len(norm)orsummaryStructureChanged.summaryStructureChanged(apply/summaryshape.go:18) matches only the plainsummarizemarker=== History Summary ===. The cache-aware wrapper starts with=== Compacted Context (cache-aware summary) ===. So the branch is skipped, the per-message writeback still sends the splice, butanchorCacheBreakpointnever runs. That turn keeps the pre-#723 behaviour: no breakpoint on the kept tool_result, so the next turn re-writes the kept history. All three new counters stay flat, so/statscannot see the gap. - Proof:
boundary = start + CoveredCount = headCount+1, soout = msgs[:headCount] + [summary] + msgs[headCount+1:]andlen(out) == len(msgs). The covered single message cannot be a tool result:summarizeSpan's head retreat forbids a head that ends on a tool-calling assistant, so a one-message span that ends right before the last exchange's call is a text message.dropOrphanedToolResultsthen drops nothing and the count stays equal. - Fix: teach
summaryStructureChangedthe cache-aware wrapper prefix, or write the anchor on the equal-count path too. The shape is rare under the default 0.9 request trigger, but it is silent, and the PR's own counters exist to prevent exactly that.
- What fails: a checkpoint whose span is one text message (
Non-blocking
- OpenAI-shaped traffic counts
cache_anchor_not_foundon every splice.lastKeptToolResultIDreturns the OpenAItool_call_id, butanchorCacheBreakpointsearches for atool_resultcontent block, which OpenAI bodies never carry. The counter then reads like an error on a healthy deployment. Gate the anchor on the Anthropic shape, or say in the counter's doc that it also counts non-Anthropic shapes. - Stale comment.
retreatPastLastToolExchange's docstring (andrequestedToolCalls') says bifrost leaves AnthropicToolCallsempty.attachToolUse(apply/apply.go:1727) liftstool_useblocks intoToolCallson the normalized path. The retreat does not depend on the claim, but a reader who follows it gets the wrong model of the data. - Dash undercounts breakpoints by one on splice turns.
tr.Breakpointsis taken before the pipeline runs; the anchor adds one breakpoint on the wire afterwards. Minor observability drift. - Data dependence. The anchor works from ids and counts only. It reads no stored customer data, so no
docs/data-dependence.mdrow change is needed. The PR body should state this, per CLAUDE.md.
What I checked
- Read
CLAUDE.md,docs/design.md, the full diff, and the code around each change:apply/apply.go(the rebuild path,rebuildCountChanged,writeBackToolText,normalize,attachToolUse,toolMessage),apply/metawrite.go,apply/summaryshape.go,components/offload/cache_aware_summarizer.go(Offload,tryReuse,replayStale,splice),summarize_pairing.go,cache_aware_async.go,cache_aware_cold.go,cache_aware_keepalive.go,components/component.go,metrics/metrics.go,proxy/proxy.go. - Traced the span math for the new and changed tests: the
anchorBodyfixtures,buildSplitGroupBody, and the retreat boundary rules againstsummarizeSpan,advanceSpanBoundaryandtrimSpanForKeptVerbatim. The retreat keeps the cut on a wire-group edge and keeps the last exchange whole; a straddling or in-tail exchange returnsendunchanged. - Checked the budget guard: the count is taken on the body as rebuilt, and the write happens only below the cap of 4, so the wire cannot reach 5. A block that already carries a breakpoint is left alone.
- Checked fail-open:
anchorCacheBreakpointreturns the body unchanged on every error path; a missing block only increments a counter. - Checked that every path that splices (
tryReuse,replayStale) setsCacheAnchorToolID, and that a reverted component restores the message count, so the rebuild branch and the anchor are skipped together. A fresh commission freezes the retreated span inCoveredCounton every path that stores one (startAsyncSummary,deferSummary,registerKeepAliveCandidate). - Verified the new
/statsfields wire throughproxy.goand the golden test, and that the Prometheus coverage map lists all three. - Did not run tests; live tests are not approved for this review.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 5f501e036b71 |
approve |
Verdict: approve
Findings
None. I could not break the change. Details of the closest calls, all verified safe:
- Span shrink vs. pairing.
retreatPastLastToolExchangemovesendback to the assistant
turn of the last tool exchange. I checked the new tail head (call) against
advanceSpanBoundary's rules: the cut lands on a wire-group edge, the tail never begins on a
role=toolmessage, and the span cannot end on an unanswered call on well-formed input.
dropOrphanedToolResultsinsplicebackstops malformed input, as before. - Index safety. Every index walk in the new code is guarded (
first-1 >= start,
call <= startshort-circuits beforemsgs[call],i >= from && i >= 0). No negative or
out-of-range index path exists. - Checkpoint consistency. The retreat runs only on the fresh-commission path, after
tryReuse.CoveredCountfreezes the retreated cut (end-startis passed to
startAsyncSummary/registerKeepAliveCandidate/deferSummary), so a later reuse or
replayStalesplices at the same boundary and re-derives the same anchor id. - Cap.
anchorCacheBreakpointcounts breakpoints on the body as rebuilt and writes only
when the total is below 4. It can never produce a 5th breakpoint.elemMarkscovers both
spellings (cache_control,cachePoint) and stays structural. - Fail-open. Every refusal path returns the body unchanged: no tool id, no slot, block not
found, sjson error. A reverted summarizer leaves the count unchanged, so the rebuild (and the
anchor) never runs on a reverted splice. - Anchor id provenance.
lastKeptToolResultID(out, headCount+1)scans past head + summary
only. The id comes from the sametool_use_idthe normalizer read, so the raw-body match in
anchorCacheBreakpointalways finds the block the splice kept.
Non-blocking
apply/metawrite.go:270— on OpenAI-shaped traffic, a splice setsCacheAnchorToolID, but
the anchor search is Anthropic-shaped (tool_resultblocks). Every splice there increments
cache_anchor_not_foundalthough nothing is wrong. The counter then reads as a defect signal
on an OpenAI-shaped deployment. Also, the retreat itself applies there and keeps one extra
tool exchange verbatim with no anchor possible. Consider gating the retreat or the counter on
the wire shape.apply/summaryshape.go:18— a one-message span keeps the message count, and
summaryStructureChangedmatches onlysummarize's=== History Summary ===wrapper, not
this component's=== Compacted Context ===. Such a splice goes through the per-message
writeback and gets no anchor. Fail-open; behaves exactly as before this PR. Pre-existing for
the splice itself.components/offload/summarize_pairing.go:185— the comment says bifrost leaves the
assistant'sToolCallsempty on Anthropic.attachToolUse(apply/apply.go:1727) lifts
tool_useintoToolCallsin the normalized view, so they are populated on proxy traffic.
The from-results search is unaffected; the comment is stale.- The three new
/statskeys are not indocs/reference/reference.md. Their siblings
(prefix_stash_oversizedand others) are not listed either, so this matches existing
practice. Optional to add.
What I checked
- The full diff
65485b86..HEAD(2 commits), andCLAUDE.md+docs/design.mdrules first. apply/apply.go:784-800— the rebuild path, the anchor call site, and its interaction with
finishRestore(a failed restore insert falls back to the pre-pipeline body; fail-open).apply/metawrite.go—anchorCacheBreakpoint,CountBreakpoints,elemMarks, the budget
argument, and the BedrockcachePointspelling.components/offload/summarize_pairing.go—retreatPastLastToolExchangeand
lastKeptToolResultID, walked by hand over: sibling-text groups, multi-result runs, exchanges
already in the tail, exchange at the span start, no-tool transcripts, nil groups
(OpenAI-shaped), andstart = 0.components/offload/cache_aware_summarizer.go— all threeCacheAnchorToolIDset sites
(tryReuse, replayStale insidedeclineButReplayStale, and the fresh path), and the retreat's
position relative totrimSpanForKeptVerbatim,tryReuse, the gates,min_tokens,
requiredCount, andregisterKeepAliveCandidate.components/offload/cache_aware_async.go—CoveredCount/CoveredHashare written from the
retreated span, so reuse and stale replay stay consistent with the frozen cut.apply/apply.gonormalize — assistanttool_usemessages survive normalization
(attachToolUse), so the message before a tool run is the assistant turn the retreat expects;
wireGroupsgives sibling/tool messages their shared group.apply/rebuildCountChanged— retained messages are re-emitted from original raw bytes, so
the anchoredtool_resultblock and itstool_use_idare present in the rebuilt body.- Tests: the three new tests traced by hand against their fixtures (span arithmetic, group
indices, breakpoint counts, counter deltas), plus the three adapted tests
(TestCacheAwareSummarizerRebuildWithASplitGroup,TestCacheAwareSpanIsNotCutByMarkerText…,
TestADeferredCommissionSkipsASpanACheckpointAlreadyCovers) — each adaptation matches the
new production span, and the never-split and wire-pairing assertions still run. - Metrics wiring:
metrics.Snapshotfields,proxy.go/stats, the golden key list, and the
promexport coverage map. The append-only/statscontract is kept (new keys only). - The PR description states the data dependence ("metadata only, no change"), per the
docs/data-dependence.mdrule. Live tests were not run (not approved); code review only.
5f501e0 to
17a15f9
Compare
…hapes Review of #727: - A one-message span keeps the message count, so the rebuild ran only if summaryStructureChanged recognised the summary message. It knew summarize's header and not cache_aware_summarizer's, so that splice went through the per-message writeback and got no anchor. Both headers are now constants in schema, used by the builders and the check. - The anchor search is for tool_result blocks, which an OpenAI-shaped body has none of, so every OpenAI splice counted as not found. The anchor now runs only for Anthropic, Bedrock and Vertex bodies. - Two comments said bifrost leaves an Anthropic tool_use out of ToolCalls; apply's normalize puts it there. Corrected. Fixes #723 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 1, at head Reviewer 2, finding 1 (an equal-count splice gets no anchor): fixed.
Both reviewers, non-blocking: OpenAI-shaped traffic counts
Both reviewers, non-blocking: the stale ToolCalls comment: fixed. Both Reviewer 2, non-blocking: dash undercounts breakpoints by one: left as is, on purpose. Reviewer 2, non-blocking: data dependence. The PR body states it: "No change. The anchor is a cache_control key, metadata only." Agreed that no Reviewer 1, non-blocking: the 3 new Not changed: How it was tested (eval box):
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 9b838fd13784 |
approve |
Verdict: approve
Findings
None.
Earlier findings, and the author's replies
- Reviewer 2, finding 1 (an equal-count splice gets no anchor) — fixed. I verified the fix
by hand on the new test's fixture:summaryStructureChangednow matches both headers. InTestAnEqualCountSpliceStillWritesTheAnchor
the fixture gives a one-message span (summarizeSpanend 3 → advance 4 → retreat to 2 over
7 normalized messages), sotryReusesplices to 7 messages — equal count. The summary
message's text now starts withschema.CacheAwareSummaryHeader, so the rebuild branch runs,
rebuildCountChangedre-emits the kept tool_result from its original raw bytes, and the
anchor is written (wireBreakpoints= 2 there, under the cap).- The constants keep both wrappers byte-identical to their old literals
(summarize.go:1000,cache_aware_summarizer.go:1186,responses.go:293), so no
forwarded prefix changes and no cached bytes flip. I compared each new constant against the
old string in the round-1 tree. summarize's own equal-count splices already took the rebuild through its header, so the
widened check changes nothing for that component.
- Both reviewers, non-blocking (OpenAI-shaped traffic counts
cache_anchor_not_foundon
every splice) — fixed. The anchor now runs only whenexplicitBreakpointProvider(provider)
is true (Anthropic, Bedrock, BedrockMantle, Vertex). I traced
TestAnOpenAISpliceDoesNotCountAMissingAnchor: the splice changes the count, the rebuild
succeeds, the provider gate refuses the anchor, and no counter moves. The gate reuses the
repo's existing provider set, so it cannot drift fromprefixsplit's notion. - Both reviewers, non-blocking (stale ToolCalls comments) — fixed. The new text in
summarize_pairing.gomatches whatattachToolUseactually does, and says the retreat does
not depend on it. Correct. - Reviewer 2, non-blocking (dash undercounts breakpoints by one) — rejected by the author,
and the reason is right.tr.Breakpointsis the inbound count, read before the pipeline,
and feeds cache attribution. Mixing the anchor in would conflate inbound and wire counts.
The anchor's own write is visible incache_anchor_written. I accept the rejection. - My non-blocking (the 3
/statskeys not in reference.md) — rejected with reason. The
sibling counters are unlisted there too. I verified that again; existing practice. Accepted. - Author's declared "not changed":
expand/response.go:158keeps the
=== History Summary ===literal. Its value equalsschema.SummaryHeader, so behavior is
right. Only a drift risk remains, in the file the author named. Acceptable.
Non-blocking
apply/apply.go:786— the provider gate keys on the provider name, not the body shape. A
Bedrock Converse body (thecachePointspellingCountBreakpointshandles) carries no
tool_resultblocks, so a splice there still countscache_anchor_not_found. It can never
write a wrong key there (the write path requires atool_resultblock), so this is counter
noise only, and only if Converse-shaped bodies reach this route.- Agreed with the author's follow-up proposal: the retreat still applies on OpenAI-shaped
traffic and keeps one extra tool exchange verbatim with no anchor possible. Gating it needs a
provider hint onCtx; a follow-up is the right size.
What I checked
- Last review: round 1, 5f501e0, 2026-10-26T06:56:56Z.
- New commits read: 4 in
5f501e03..HEAD—56f59a7f(the new base, #725 from main),
e4fdb79f+17a15f9c(the rebased round-1 commits),9b838fd1(the round-2 fix). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files; the inline file
is empty — there are none). - New items since my last review, and what I did:
- The rebase onto
56f59a7f: diffed my reviewed tree5f501e03against the rebased
pre-fix tip17a15f9c. The only differences are the #725 base changes
(cheapmodel, extract_sweep, keepalive, docs). No PR-owned file differs — the rebase made no
resolution changes.56f59a7fitself touches no file this PR changes. 9b838fd1non-test diff: read in full (apply/apply.gogate,summaryshape.go,
schema/summaryheader.go, both wrapper builders,responses.go, the two comment
corrections insummarize_pairing.go).9b838fd1tests:TestAnEqualCountSpliceStillWritesTheAnchorand
TestAnOpenAISpliceDoesNotCountAMissingAnchor, hand-traced message by message (span math,
group walk, splice count, survivor matching, breakpoint count, counter deltas).- The author's reply comment: checked every claim in it against the code, including the
rejections (dashtr.Breakpointsis the inbound count; reference.md practice) and the
"not changed" items (expand/response.go:158).
- The rebase onto
- Grep for remaining header literals: only tests,
expand/response.go:158(declared), and the
new constants file. No third copy of the cache-aware header exists. - Interaction with the new base: #725's
insertAskMessagemoves only the LAST message's
breakpoint; the anchor writes mid-body, and no file overlaps. No conflict. - Live tests were not run (not approved); code review only.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 9b838fd13784 |
blocking |
Verdict: blocking
Findings
- apply/responses.go:293 — the fix drops an equal-count cache_aware splice on the Responses route, where it was applied before
- What fails: an OpenAI Responses-route request,
cache_aware_summarizerin the pipeline, a checkpoint whose span is one message (CoveredCount == 1). The splice keeps the message count.summaryStructureChanged(apply/summaryshape.go:21) now returns true for the cache-aware header, so responses.go:598 enters the rebuild branch.rebuildResponsesCountChangedlocates the summary by scanning forschema.SummaryHeaderonly (line 293). It finds none,headstays -1, and it returnsok=false. Line 603 then returns the original body, and the equal-count writeback loop below (lines 606-623) never runs. Before commit 9b838fd,summaryStructureChangedreturned false for this splice, the writeback loop wrote the summary text into the covered item, and the compaction was applied. Now the splice is silently dropped: the turn pays for the checkpoint but forwards the full transcript. Fail-open, so no wrong bytes, but a compaction loss with no counter. - Proof:
summaryStructureChangedaccepts both headers; the Responses rebuild's head scan (responses.go:290-299) accepts one. The gate and the rebuild disagree, in the same commit that moved both headers into constants "so they cannot drift again".cache_aware_summarizerdoes reach this route: it checks neitherDisallowCountChangenorAllowSummarySpan(only plainsummarizedoes, summarize.go:329,390), andOpts.PrefixAskis wired there (responses.go:586). - Fix: accept
schema.CacheAwareSummaryHeaderin the head scan at responses.go:293, next toschema.SummaryHeader. The role check at line 300 already fits: the cache-aware summary is role=user. This also repairs the pre-existing drop of count-changed cache_aware splices on that route.
- What fails: an OpenAI Responses-route request,
Earlier findings, and this round's replies
- My round-1 finding 1 (an equal-count splice gets no anchor): fixed on the Chat route.
summaryStructureChangednow knows both headers (constants inschema/summaryheader.go), the builders use the constants byte-identically, andTestAnEqualCountSpliceStillWritesTheAnchorasserts the equal count, the replaced span and the marked tool_result. I traced the fixture: 7 normalized messages, the retreat cuts the span to one message, the count stays 7, the rebuild matches survivors by bytes, the anchor findstoolu_eqwith 2 of 4 slots used. The same fix causes finding 1 above on the Responses route. - Both reviewers, OpenAI
cache_anchor_not_found: fixed. The anchor now runs only behindexplicitBreakpointProvider(apply.go:786), the pre-existing helper that covers Anthropic, Bedrock, BedrockMantle and Vertex.TestAnOpenAISpliceDoesNotCountAMissingAnchorcovers it; I traced the span (3 messages, count changes, rebuild runs, anchor gated off). The splice itself still applies on the OpenAI Chat route, because the gate guards only the anchor. - Stale ToolCalls comments: fixed. Both docstrings in
summarize_pairing.gonow say thatattachToolUseliftstool_useintoToolCalls. - Dash breakpoint undercount: declined with a reason, and the reason is right.
tr.Breakpointsis the inbound count, an input to cache attribution; the anchor has its own counter (cache_anchor_written). Mixing the two would muddy the attribution. Accepted. - Data dependence: done. The PR body states "No change. The anchor is a
cache_controlkey, metadata only." Nodocs/data-dependence.mdrow is needed. - Reviewer 1's round-1 notes (OpenAI counter, stale comment,
reference.mdkeys, equal-count note) all match what I found in round 1; the first two are fixed as above, thereference.mdkeys are left as existing practice (their siblings are not listed either — I verified that in round 1). - The retreat on OpenAI-shaped traffic keeps one tool output verbatim with no anchor possible: accepted as a follow-up. The summarizer cannot see the provider; a
Ctxprovider hint is a fair separate change.
Non-blocking
expand/response.go:158still holds the=== History Summary ===literal, as the reply says. Pre-existing, Responses route only, and it concerns the plain summarizer's restore. Fine to leave.- The reply's claim "used by both builders and the check, so they cannot drift again" is not fully true: the Responses head scan (finding 1) and the expand literal above still carry their own knowledge of the headers.
What I checked
- Last review: round 1, 5f501e0, 2026-10-26T06:56:24Z.
- New commits read: the branch was rebased onto 56f59a7 (#725).
git log 5f501e03..HEADlists 4 commits:56f59a7f(the new base, #725's merge, not part of this PR),e4fdb79fand17a15f9c(this PR's two original commits, re-authored), and9b838fd1(the new fix). A tree diff of5f501e03against17a15f9cdiffers only in #725's files, so the re-authored pair is content-identical to what I reviewed in round 1. I read9b838fd1's full diff and the code around every hunk. - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
- New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (posted 32 s after mine, so unread in round 1): read in full. Its notes match my round-1 findings; nothing new to act on.
- The author's reply comment at 07:22:12Z: checked every claim against the code, as recorded above.
- Commit
9b838fd1: reviewed as a first review. Traced both new tests against their fixtures (span arithmetic, count equality, breakpoint budget, counter deltas), the constants for byte-identity with the old literals,explicitBreakpointProvider's provider set, and the Responses-route flow at responses.go:598-625, which produced finding 1.
- Confirmed the PR body states the data dependence.
- Did not run tests; live tests are not approved for this review.
…store Review round 2 of #727: the equal-count gate now accepted cache_aware_summarizer's header, but the Responses-route rebuild still looked for summarize's only. It found no summary, returned not-ok, and a one-message cache-aware splice on that route was dropped instead of written, as it had been before. apply now has one test for a spliced summary, isSummaryHeader, used by the gate and by rebuildResponsesCountChanged. expand's in-place restore on the Responses route accepts both headers too, from local constants a test pins to schema's (expand imports no context-guru package). Fixes #723 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 2, at head Reviewer 2, finding 1 (the Responses rebuild drops an equal-count cache-aware splice): fixed.
How it was tested (eval box):
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 3 of 3 | 48a53e652f1a |
approve |
Verdict: approve
Findings
None. The round-2 finding is fixed, and the fix introduces no new defect.
Earlier findings, and this round's replies
- My round-2 finding 1 (the Responses rebuild drops an equal-count cache-aware splice): fixed. I verified the fix in the code:
isSummaryHeader(apply/summaryshape.go) is the one test for a spliced summary, used by both the equal-count gate (summaryStructureChanged) and the rebuild's head scan (rebuildResponsesCountChanged, responses.go:293). The gate and the rebuild can no longer disagree — the exact defect class of round 2.- The head scan's role check fits: both summary paths build the message as
role=userwith the header first (emitCheckpointat summarize.go:749, the fresh path, andcacheAwareSummaryWrapperat cache_aware_summarizer.go:1186). responsesSummarySpanSafeaccepts the target span (a one-message plain item). Where it refuses, the rebuild returns not-ok and the original body is forwarded. That is fail-open, and it is the same treatment plainsummarizealready gets.- The fix also repairs the pre-existing drop of count-changed cache-aware splices on this route: they entered the rebuild before, and the header scan could not find them.
- My round-2 non-blocking (
expand/response.goliteral): fixed beyond what I asked. The in-place restore now accepts both headers (isSummaryText), from local constants.TestSummaryHeadersMatchSchemapins them toschema's, so they cannot drift. TheMarker(hash)requirement is preserved: an item must match role, header and marker together. This closes a pre-existing gap (a cache-aware summary was never restored in place on the Responses route), correctly pulled in as the same class. - My round-1 finding 1 (an equal-count splice gets no anchor): stays fixed (commit 9b838fd, verified in round 2; no change since).
- Both reviewers, OpenAI
cache_anchor_not_found: stays fixed. The anchor runs behindexplicitBreakpointProvider. No change since round 2. - Stale ToolCalls comments: stays fixed.
- Dash breakpoint undercount: declined with a reason I accept (round 2):
tr.Breakpointsis the inbound count, an input to cache attribution. - Reference.md keys, data dependence: accepted as settled (round 2).
- The retreat on OpenAI-shaped traffic: accepted as a follow-up. It needs a provider hint on
Ctx.
What I checked
- Last review: round 2,
9b838fd137841ee746e28b1aee4b6271aa4bc1d2, 2026-10-26T07:28:26Z. - New commits read: 1 in
9b838fd1..HEAD—48a53e65(the round-3 fix). Full diff read, plus the code around every hunk. - Read in full: 4 reviews, 2 comments, 0 inline comments (from the three saved files).
- New items since my last review, and what I did about each:
- Commit
48a53e65: reviewed as a first review. Checked thatisSummaryHeaderis used at both call sites (gate responses.go:598, head scan responses.go:293); that the summary message's role and text satisfy the head scan's checks (user, header-first, from all three emit paths); and thatrebuildResponsesCountChanged's refusal paths forward the original body. - The author's reply comment at 07:48:18Z: checked every claim against the code. The grep claim holds: the only non-test header literals are the two constants blocks (
schema/summaryheader.go,expand/response.go).rebuildCountChangedmatches survivors by bytes and tool_call ids, not by header — confirmed. - The new tests, traced by hand:
TestResponsesCacheAwareOneMessageSpliceIsWritten(equal count asserted, summary present, covered span gone; helperspipe,recordingModel,WaitForAllSummariesForTestall exist in the test package) andTestSummaryHeadersMatchSchema(pins both constants and exercisesisSummaryText). I did not run them; live tests are not approved. - The expand restore change: read the full loop. Role, header and
Marker(hash)are still required together; the stash-driven replacement path is unchanged. The test file's import ofschemais test-only, so the leaf package's own import graph is unchanged.
- Commit
- No new review from reviewer 1 since round 2 (their round-2 review at 07:26:05Z predates mine; nothing new to act on).
- Did not run tests; live tests are not approved for this review.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 3 of 3 | 48a53e652f1a |
blocking |
Verdict: blocking
Findings
- expand/response.go:158 — expanding a cache-aware summary on the Responses route can build an input array the provider rejects
- What fails: Responses route,
cache_aware_summarizer, marker mode full (the default), and the model
callsexpandon the marker. The stash under that marker key isjson.Marshal(span)of the
NORMALIZED messages (cache_aware_async.go:237,cache_aware_summarizer.go:934), on every route.
It is not an array of wire input items. - The new
isSummaryTextmatch sends that stash into the in-place restore. That restore's
precondition is written atexpand/response.go:122: "A Responses summary stash is an array of the
exact input items it replaced." True forsummarize, which stashes wire items through the
SummaryStashPayloadhook (apply/responses.go:580,summarize.go:333). False for
cache_aware_summarizer, which never uses the hook. - The
validcheck (lines 146-152) does not stop it. It only asks that each element is an object
with a role or a type. Normalized messages haverole. So a span that covers a tool exchange
splices{"role":"tool",...}messages (built bytoolMessage,apply/apply.go:1764— "synthetic
OpenAI-shaped tool message") and assistant messages withtool_callsintoinput. The Responses
API accepts message roles user, assistant, system and developer only. Calls are separate
function_callitems. The provider rejects the request with 400. - Before this commit, the same call built a valid request: no header match, no in-place splice, and
the stash JSON traveled as thefunction_call_outputstring. The commit turns a working (if
flattened) recovery into a failed request. Not fail-open. - Reachability: the span often covers tool exchanges.
responsesSummarySpanSafe
(apply/responses.go:139) allows whole call/output pairs inside a span on purpose. The retreat
keeps only the LAST exchange out of a fresh span. Reused and replayed checkpoints predate the
retreat. The forward path maps normalized messages back to wire bytes throughwriteSurvivor;
only the new expand path splices the normalized form directly. - Fix: in the
validcheck, also require each item to be a message this route accepts — role user,
assistant, system or developer, and notool_callsfield. Items that fail fall through to the
string answer, which is the old, valid behavior. Or limit the in-place path tosummarize's
stash. - A text-only span restores fine (
{"role":"user","content":"..."}is a valid input item). The break
needs a tool exchange inside the stashed span. No test covers expanding a cache-aware summary on
this route; the new tests cover the forward path and the constants only.
- What fails: Responses route,
Earlier findings, and the author's replies
- Reviewer 2, round-2 finding 1 (the Responses rebuild drops an equal-count cache-aware splice) —
fixed.isSummaryHeader(apply/summaryshape.go) now feeds both the equal-count gate and the
head scan inrebuildResponsesCountChanged, so the gate cannot send a splice to a rebuild that
cannot find it. I hand-tracedTestResponsesCacheAwareOneMessageSpliceIsWrittenend to end: 4
input items, keep_last_turns 2, span [1,2),tryReusesplices to 4 messages (equal count),
isSummaryHeaderfinds head=1, tail=2, spanEnd=2, first=last=1, and the splice is written with
the count equal. On9b838fd1the scan knew only summarize's header, head stayed -1, and the
splice was dropped — the test's failure there is consistent with my trace. The same scan also
repairs count-changed cache-aware splices on this route, which were dropped before this PR. - My round-2 non-blocking (Bedrock Converse bodies count
cache_anchor_not_found) — not fixed,
non-blocking. This commit touches no gate code. Counter noise only, as before. - My round-2 non-blocking (the retreat keeps one tool exchange verbatim on OpenAI-shaped traffic)
— follow-up, as agreed by both reviewers. Not in this commit, as proposed. - Reviewer 2's round-2 non-blocking (
expand/response.goheld a header literal) — fixed by this
commit. The constants are mirrored locally and pinned byTestSummaryHeadersMatchSchema.
Correct approach for a leaf package that imports no context-guru package. - The author's reply claims, checked:
- "One test for a spliced summary" — verified.
isSummaryHeaderis the only scan the gate and the
Responses rebuild use. - "
rebuildCountChangedneeds no header" — verified in round 1. It matches survivors by bytes and
tool_call_id. - "A grep shows no other header scan" — verified. Only
schema's constants, the pinned expand
mirror, and tests remain. - "The test's span is long enough that the summary saves tokens" — verified. The fixture's span
text is 120 repeats, past the never-worse guard. - No rejection reasons this round to assess.
- "One test for a spliced summary" — verified.
Non-blocking
- None new beyond the finding above.
What I checked
- Last review: round 2,
9b838fd137841ee746e28b1aee4b6271aa4bc1d2, 2026-10-26T07:26:05Z. - New commits read: 1 (
48a53e65fix(apply,expand): find a cache-aware summary in every rebuild and
restore). - Read in full: 4 reviews, 2 comments, 0 inline comments (the inline file is empty — there are none).
- New items since my last review, and what I did about each:
- Reviewer 2's round-2 review (posted 07:28:26Z, after mine): read in full. Its finding 1 is the
one this commit fixes; traced above. - The author's reply at 07:48:18Z: every claim checked against the code, as listed in the earlier
findings. - Commit
48a53e65: reviewed as a first review. Full diff (5 files), plus the code around every
hunk:rebuildResponsesCountChangedin full,summaryStructureChanged,Continuation's
responses case in full, both new tests, and the stash chain behind the marker —
commitAsyncSummary,summaryStashJSON,responsesSummaryStash,normalizeResponses,
responsesSummarySpanSafe,toolMessage,expand.Resolve, and the proxy's expand loop that
buildsresolved. That chain produced finding 1.
- Reviewer 2's round-2 review (posted 07:28:26Z, after mine): read in full. Its finding 1 is the
- Confirmed the base is unchanged (
56f59a7f) and the commit touches no file outside its fix. - Live tests were not run (not approved); code review only.
…atch gap Review round 3 of #727: - expand's in-place restore on the Responses route accepted any stashed object with a role or a type. A cache_aware_summarizer stash holds normalized chat messages, so a span with a tool exchange would splice a role=tool message and tool_calls into `input` (a 400 from the Responses API). It now restores in place only real Responses input items; anything else is answered as the flattened string, as before. - CI failure TestCacheAwareRealContentChangeInsideSpanStillDeclines: the host's hook took a deferral out of its registry and then started it, and in between it was neither registered nor in flight. A test waiting right after its request could see nothing pending and read its counters before the call ran. A taken deferral is now marked as dispatching under the registry lock until startAsyncSummary returns, and WaitForSummaryForTest waits for that mark. The stale-prefix guard itself is unchanged. - The #724 tests stash one message short of the RETREATED span, so they still catch an Offload-time start after #723 shortened the span. Fixes #723 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 3, at head Reviewer 1, finding 1 (expand restores a cache-aware stash in place as non-wire items, a 400 on Responses): fixed.
CI failure,
Also found while checking the mutations: #723's retreat shortens the span, so the #724 test that stashes "one message short of the span" stashed short of the OLD span and no longer caught an Offload-time start. It now stashes one short of the retreated span; the #724 mutation (no deferral) fails it again 3 of 3. How it was tested (eval box):
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 4 of 4 | d61c3bd57c14 |
approve |
Verdict: approve
Findings
None. My round-3 finding is fixed as proposed, and the two other changes in the commit are sound.
Earlier findings, and the author's replies
- My round-3 finding 1 (expand restores a cache-aware stash in place as non-wire items, a 400 on
Responses) — fixed. NewresponsesInputItem(expand/response.go) gates the in-place restore:- A
role=toolmessage fails the role switch (no case for it) and falls to the flattened string
answer. An assistant message withtool_callsortool_call_idfails the field check. Both are
the normalized shapestoolMessageandattachToolUsebuild — exactly the two I flagged. - A stashed element with no role must carry a
type, which is a wire item (function_call,
reasoning, and friends). Plain user/assistant/system/developer messages pass. Sosummarize's
wire stashes keep the in-place restore, and a text-only cache-aware span keeps the improvement
from round 3. - I traced
TestResponsesExpandOfACacheAwareToolStashStaysValidby hand: a stash of one
assistant-with-tool_calls and one role=tool message, a cache-aware summary carrying
Marker("HASH"). The first element failsresponsesInputItem,validstays false, no
replacement happens, and the stash travels as thefunction_call_outputstring. On the old
any-role-or-type check the same trace splices the role=tool item and the test'sForEachfails
— the M9 claim is consistent with the code.
- A
- My round-2/3 non-blocking (Bedrock Converse bodies count
cache_anchor_not_found) — not
fixed, non-blocking. This commit touches no gate code. Counter noise only. - My round-2/3 non-blocking (the retreat keeps one tool exchange verbatim on OpenAI-shaped
traffic) — follow-up, as agreed. Not in this commit. - Reviewer 2's round-3 review — read in full this round. It approved
48a53e65and its claims
match what I verified independently in rounds 2 and 3. Nothing new to act on.
The CI-failure fix, checked
- The race was real.
ResolveDeferredCacheAwareSummarytook a deferral out of its registry and
calledstartAsyncSummaryonly afterwards. In between,deferralPendingwas false and the job
was not yet ininFlight, soWaitForSummaryForTestcould return "nothing pending" and a test
read its counters before the call ran. I confirmed the window in the pre-fix code path. - The fix closes it with no production change.
markDispatchingruns before the deferral leaves
its registry, under that registry's lock;doneDispatchingruns afterstartAsyncSummary
returns.deferralPendingreads the map too. The map is read only by the test hook, so production
semantics are unchanged, as the author says. - Every mark has a done. I walked each path: the hook's cold and warm branches, both fallback
timers,deferWarm's replaced-deferral branch, and the two tests that take a deferral by hand
(they now calldoneDispatching). The lock order is one way (registry mutex, then
dispatchingMu); no path takes them the other way round, so no deadlock. - The new test is race-free by construction.
TestWaitForSummaryCoversTheGapBetweenTakeAndStart
sets the seam before it starts the goroutine, and its cleanup clears the seam only after
WaitForSummaryForTestreturns true, which requiresdispatchingto reach zero. The mutex chain
orders the goroutine's seam read before the cleanup's write. The 50 ms wait inside the gap must
and does return false —deferralPendingsees the mark. - The fixture updates are right. The three #724 tests now stash
end-1of the span after
retreatPastLastToolExchange, which is the span production commissions. The first test's 1 s wait
is correct: the deferral is held, so the wait can only time out; an Offload-time start would be
drained there and caught, which is the test's purpose.
What I checked
- Last review: round 3,
48a53e652f1a298a41fd080906c4ae77e2402e50, 2026-10-26T07:57:23Z. - New commits read: 1 (
d61c3bd5fix(expand,offload): restore only wire items in place; close the
dispatch gap). - Read in full: 6 reviews, 3 comments, 0 inline comments (from the three saved files; the inline
file is empty — there are none). - New items since my last review, and what I did about each:
- Reviewer 2's round-3 review (07:53:45Z, approve — posted while I was writing mine, so new to me
this round): read in full. Its verification of theisSummaryHeaderfix matches my round-3
trace. Nothing to reconcile. - The author's reply at 08:24:06Z: every claim checked against the code, as recorded above —
theresponsesInputItemgate, the unchanged image-restore test, the CI-failure cause and fix,
the M9/M10 mutation logic, and the #724 fixture change. - Commit
d61c3bd5: reviewed as a first review. Full diff (5 files), plus the code around every
hunk:Continuation's responses case with the new gate, the whole deferral registry in
cache_aware_cold.go(deferWarm, both takes, both fallbacks, the hook,dispatchDeferred),
summarize_testhook.goin full, and all four touched tests in full.
- Reviewer 2's round-3 review (07:53:45Z, approve — posted while I was writing mine, so new to me
- Confirmed the base is unchanged (
56f59a7f) and the commit adds no new production behavior beyond
the expand gate (thedispatchingmap serves the test hook only). - Live tests were not run (not approved); code review only.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 4 of 4 | d61c3bd57c14 |
approve |
Verdict: approve
Findings
None. The new commit fixes reviewer 1's round-3 finding correctly, and it introduces no new defect.
Reviewer 1's round-3 finding, checked myself
Agree with reviewer 1, finding 1 (expand restores a cache-aware stash in place as non-wire items, a 400 on Responses). The finding was real, and my round-3 approval missed it. I checked the chain now, at the round-3 head and at this head:
cache_aware_summarizerstashesjson.Marshal(span)of the NORMALIZED messages on every route (cache_aware_summarizer.go:933, cache_aware_async.go:237). It never uses the Responses stash hook thatsummarizeuses.normalizeResponsesbuilds those messages: afunction_callitem becomes an assistant message withtool_calls; afunction_call_outputbecomes arole=toolmessage withtool_call_id(toolMessage). At the round-3 head, the restore'svalidcheck asked only for an object with a role or a type. Both shapes passed. Spliced intoinput, the Responses API rejects them with 400. Not fail-open.- My round-3 check stopped at the marker and role conditions. I did not check what the stash itself contains. That was the gap.
Fixed in this commit, verified:
responsesInputItem(expand/response.go) accepts only real Responses input items: a typed item, or a role of user/assistant/system/developer with notool_callsand notool_call_id. Both normalized tool shapes are rejected.- A rejected stash skips only the in-place splice (
continue). The answer loop later carries the stash JSON as thefunction_call_outputstring — the behaviour before this PR. I read the wholeContinuationresponses branch to confirm this. summarize's stashes are wire items, so its restore is unchanged. I checked each wire shape againstresponsesInputItem: message items,function_call,reasoning,function_call_outputall pass, as before.- The normalized stash cannot contain other shapes that pass the check but are invalid input:
normalizeResponsesflattens every content form to a string-content message. So an accepted stash element is always{"role":...,"content":"<string>"}. - New test
TestResponsesExpandOfACacheAwareToolStashStaysValid, traced by hand: the tool-exchange stash is rejected, norole:toolortool_callsreachesinput, and the stash travels as the flattened answer. Correct.
The CI failure fix, checked
- The gap was real at the round-3 head:
ResolveDeferredCacheAwareSummarytook a deferral out of its registry and calledstartAsyncSummaryafter. In between, the deferral was neither registered nor in flight, soWaitForSummaryForTestcould return before the call ran. - The fix marks a taken deferral
dispatchingunder the registry's own lock, before it leaves, and clears the mark after the dispatch returns.deferralPendingreads that mark too. I checked every take/mark site pairs with adoneDispatching:deferWarm(192→204, no early return between),resolveWarmFallback(250→253),resolveFallback(292→298), the hook's cold (325→328) and warm (330→336) paths. The tests that calltakeWarmDeferraldirectly now clear the mark too. - Lock order is registry →
dispatchingonly. No path takes them in the other order. No deadlock. dispatchingis read only bydeferralPending, which onlyWaitForSummaryForTestuses. Production behaviour is unchanged, as the author claims.- The new test
TestWaitForSummaryCoversTheGapBetweenTakeAndStartis sound: aprefix_askcommission defers warm unconditionally (cache_aware_summarizer.go:983), so the hook takes the warm branch where the seam sits. During the seam window the mark is set, so the 50 ms wait must time out and return false. After the release, the call lands and the wait returns true.
The #724 test adjustment, checked
- The retreat from #723 shortens the span. A test that stashed "one message short of the span" stashed short of the OLD, longer span. The coverage check then accepted an Offload-time start, so the test lost its power to catch it.
- The three tests now compute the retreated end first (
retreatPastLastToolExchange) and stash one short of THAT.put(end-1)against a span ofend-startmessages withstart >= 1refuses the count again. The reasoning holds.
Earlier findings, and this round's replies
- My round-1 finding 1 (an equal-count splice gets no anchor): fixed in 9b838fd. Unchanged since round 2.
- My round-2 finding 1 (the Responses rebuild drops an equal-count cache-aware splice): fixed in 48a53e6. Unchanged since round 3.
- Both reviewers, OpenAI
cache_anchor_not_found: fixed (provider gate). Unchanged. - Stale ToolCalls comments: fixed. Unchanged.
- Dash breakpoint undercount, reference.md keys, data dependence: settled with reasons I accept (rounds 2-3).
- The retreat on OpenAI-shaped traffic: accepted as a follow-up (needs a provider hint on
Ctx). - Reviewer 1's round-2 non-blocking (Bedrock Converse counter noise): not fixed, non-blocking. This commit touches no gate code. Agreed.
Non-blocking
betweenTakeAndStartForTest(cache_aware_cold.go:216) is a test seam in a production file. The repo's other test hooks live insummarize_testhook.go. It is read without synchronization; safe in the current sequential tests, and never written in production. Placement only.
What I checked
- Last review: round 3,
48a53e652f1a298a41fd080906c4ae77e2402e50, 2026-10-26T07:53:45Z. - New commits read: 1 in
48a53e65..HEAD—d61c3bd5(fix(expand,offload): restore only wire items in place; close the dispatch gap). Full diff read, plus the code around every hunk. - Read in full: 6 reviews, 3 comments, 0 inline comments (from the three saved files).
- New items since my last review, and what I did about each:
- Reviewer 1's round-3 review (07:57:23Z, after my round-3 post): read in full. Its finding 1 is real — I verified the stash chain myself, as recorded above, and I state plainly that my round-3 approval missed it.
- The author's reply comment at 08:24:06Z: checked every claim against the code. The take/start gap, the #724 stash-shortening claim, and the "no production behaviour change" claim all hold.
- Commit
d61c3bd5: reviewed as a first review.responsesInputItemagainst every stash shape both summarizers can produce (normalizeResponsesin full,toolMessage, the function_call and reasoning branches); the wholeContinuationresponses branch for the flattened fallback; every take/mark/done pairing incache_aware_cold.go; the lock order; the three adjusted #724 tests and the two new tests, traced by hand.
- Did not run tests; live tests are not approved for this review.
fix(offload): cover the last tool exchange in an OpenAI summary (#730) The summary span stopped before the last tool exchange so the host could anchor a cache breakpoint on it (#727). OpenAI takes no explicit breakpoint, so the retreat only cost savings there. - Add Ctx.NoCacheBreakpoint, set from the provider by the host. - cache_aware_summarizer retreats the span only when a breakpoint can be written (Anthropic, Bedrock, Vertex). - Fix the stale "300 s - 270 s" text in keepalive/substitute.go and keepalive/openaiphase_test.go. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> fix(apply): give the Responses route and the bifrost adapter the no-breakpoint flag (#730) The Responses route is always OpenAI. It built its Ctx without NoCacheBreakpoint, so it still retreated the summary span. - Set NoCacheBreakpoint on the Responses Ctx. - Set it on the bifrost adapter Ctx, which never writes the anchor. - Add a Responses test: the summary covers the last function_call_output. - Rename the apply-level OpenAI test to say what it checks. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Summary
After
cache_aware_summarizerspliced a summary in, every following turn re-wrote the whole kept history to the cache. Now the splice keeps the last tool exchange verbatim and marks itstool_resultwith one cache breakpoint, so the next turn reads the summary and that exchange from the cache.Live, on real Claude Code traffic through the fixed binary (straight to the benchmark gateway, about $0.15):
13,438 is system + tools only. 20,975 adds the summary and the kept tool exchange.
What we found
keep_last_turnscounts messages, and the last few are the prompt and the reminder);What changed
Only when the summarizer splices. Nothing changes for any other request.
components/offload/summarize_pairing.go: newretreatPastLastToolExchange. A FRESH summary span ends before the last tool exchange, so itstool_useandtool_resultstay verbatim. It runs aftertryReuse, so a stored checkpoint is never refused by it. The cut is frozen in the checkpoint'sCoveredCount, so later turns keep the same exchange. If the kept tail has no tool exchange, or the exchange starts at the span start, nothing changes.components/offload/cache_aware_summarizer.gosetsCtx.CacheAnchorToolIDto the last kepttool_result's id on every turn it splices.apply/apply.go's count-changing rebuild then callsanchorCacheBreakpoint(apply/metawrite.go), which writes one{"type":"ephemeral"}cache_controlonto thattool_resultblock in the raw body.Breakpoint budget
cache_controlbreakpoints. Claude Code uses 3 (2 system, 1 on the trailing reminder). The anchor is the 4th./statscache_anchor_no_slot, and the turn behaves exactly as before this PR. Also counted:cache_anchor_written, andcache_anchor_not_found(the tool_result was not in the rebuilt body).cachesplit(in every shipped preset) only moves a system breakpoint, it never adds one, so it is unaffected.cacheinjectis in no shipped preset.Costs to weigh
How it was tested
All runs are on the eval box.
TestASpliceKeepsAndMarksTheLastToolExchange(apply)origin/main+ test(a) the last tool exchange was summarized awayTestRetreatPastLastToolExchange(offload)TestTheCacheAnchorIsSkippedWhenNoBreakpointSlotIsFree(apply)TestASpliceWithNoToolExchangeAddsNoAnchor(apply)(a) ... summarized away(b) the kept tool_result carries no cache_controlthe anchor was written with no free slotanchor counters moved with no tool exchangego test -race ./apply/... ./components/...go test -race ./proxy/...go vet,gofmt -l3 existing tests asserted the old span and now follow the new rule. They are in a separate commit:
TestCacheAwareSummarizerRebuildWithASplitGroup: the split group is the last tool exchange, so it is now kept whole. The "never split" invariant and the wire-pairing check still run.TestCacheAwareSpanIsNotCutByMarkerTextInAnEarlyMessage: the expected span applies the retreat. It still checks that the span reaches past the early docs read.TestADeferredCommissionSkipsASpanACheckpointAlreadyCovers: it saves the checkpoint for the retreated span.Data dependence
No change. The anchor is a
cache_controlkey, metadata only. The kept tool exchange is content the request already carries. Nothing new is stored.Not in this PR
It does not touch
cheapmodel/anthropic.go,extract_sweep*.goorprefixask_gate.go(#721, #725).Fixes #723
🤖 Generated with Claude Code