Skip to content

fix(offload): keep and mark the last tool exchange after a splice - #727

Merged
amiddavid merged 5 commits into
mainfrom
fix/summary-anchor
Oct 26, 2026
Merged

amiddavid merged 5 commits into
mainfrom
fix/summary-anchor

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

After cache_aware_summarizer spliced 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 its tool_result with 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):

Turn Before (#723) This PR
1st turn after the splice read 13,438, write 992 read 13,438, write 7,635 (once: the summary and the kept exchange are new)
2nd turn read 13,438, write 1,028 read 20,975, write 134
3rd turn read 13,438, write 1,064 read 20,975, write 170

13,438 is system + tools only. 20,975 adds the summary and the kept tool exchange.

What we found

  • A provider rule, measured in Prefix questions (sweep, summary substitute) miss the cache: the breakpoint stays on Claude Code's trailing system message #721: a cache entry that ends at a text turn is never read by the next request. Reads resume only from an entry that ends at a tool_result.
  • The splice folded every tool exchange into the summary. The kept history was then text turns only, so no entry was readable, and every turn re-wrote it.
  • Measured before writing this, on real bytes:
    • keeping the last tool exchange alone does not help (read 12,939, write 8,700): no readable entry exists without a breakpoint on it;
    • a breakpoint alone has nothing to mark with the shipped tail (keep_last_turns counts messages, and the last few are the prompt and the reminder);
    • both together work (read 21,563, write 98).

What changed

Only when the summarizer splices. Nothing changes for any other request.

  1. (a) Keep the last tool exchange. components/offload/summarize_pairing.go: new retreatPastLastToolExchange. A FRESH summary span ends before the last tool exchange, so its tool_use and tool_result stay verbatim. It runs after tryReuse, so a stored checkpoint is never refused by it. The cut is frozen in the checkpoint's CoveredCount, 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.
  2. (b) Mark it. components/offload/cache_aware_summarizer.go sets Ctx.CacheAnchorToolID to the last kept tool_result's id on every turn it splices. apply/apply.go's count-changing rebuild then calls anchorCacheBreakpoint (apply/metawrite.go), which writes one {"type":"ephemeral"} cache_control onto that tool_result block in the raw body.

Breakpoint budget

  • The provider allows at most 4 cache_control breakpoints. Claude Code uses 3 (2 system, 1 on the trailing reminder). The anchor is the 4th.
  • The anchor is added only if the rebuilt body has fewer than 4. The count is taken on the body as rebuilt, after every component ran, so it includes anything cacheinject placed from its own earlier count. It can never make 5.
  • No free slot: the anchor is skipped and counted in /stats cache_anchor_no_slot, and the turn behaves exactly as before this PR. Also counted: cache_anchor_written, and cache_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. cacheinject is in no shipped preset.
  • Live: 3 anchors written, 0 skipped, 0 not found.

Costs to weigh

  • The kept tool output is not summarized, so a splice saves one tool output's tokens less.
  • The first turn after a splice writes the kept exchange once (7,635 against 992 above); from the 2nd turn on, each turn saves about 1k cache-write tokens, growing with the session.

How it was tested

All runs are on the eval box.

Run Tree Result
TestASpliceKeepsAndMarksTheLastToolExchange (apply) origin/main + test FAIL: (a) the last tool exchange was summarized away
TestRetreatPastLastToolExchange (offload) this branch PASS (new function)
TestTheCacheAnchorIsSkippedWhenNoBreakpointSlotIsFree (apply) this branch PASS
TestASpliceWithNoToolExchangeAddsNoAnchor (apply) this branch PASS
M1: no retreat (a) this branch FAIL (a) ... summarized away
M2: no anchor (b) this branch FAIL (b) the kept tool_result carries no cache_control
M3: no slot check this branch FAIL the anchor was written with no free slot
M4: the summarizer always names an anchor this branch FAIL anchor counters moved with no tool exchange
go test -race ./apply/... ./components/... this branch PASS
go test -race ./proxy/... this branch PASS (464 s)
go vet, gofmt -l this branch clean
live, real Claude Code + fixed binary + benchmark gateway this branch see the table above

3 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_control key, 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*.go or prefixask_gate.go (#721, #725).

Fixes #723

🤖 Generated with Claude Code

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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, tryReuse builds [head, summary, tail] with the same message count as the input. The rebuild branch runs only when len(chat.Input) != len(norm) or summaryStructureChanged. summaryStructureChanged (apply/summaryshape.go:18) matches only the plain summarize marker === 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, but anchorCacheBreakpoint never 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 /stats cannot see the gap.
    • Proof: boundary = start + CoveredCount = headCount+1, so out = msgs[:headCount] + [summary] + msgs[headCount+1:] and len(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. dropOrphanedToolResults then drops nothing and the count stays equal.
    • Fix: teach summaryStructureChanged the 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.

Non-blocking

  • OpenAI-shaped traffic counts cache_anchor_not_found on every splice. lastKeptToolResultID returns the OpenAI tool_call_id, but anchorCacheBreakpoint searches for a tool_result content 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 (and requestedToolCalls') says bifrost leaves Anthropic ToolCalls empty. attachToolUse (apply/apply.go:1727) lifts tool_use blocks into ToolCalls on 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.Breakpoints is 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.md row 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 anchorBody fixtures, buildSplitGroupBody, and the retreat boundary rules against summarizeSpan, advanceSpanBoundary and trimSpanForKeptVerbatim. The retreat keeps the cut on a wire-group edge and keeps the last exchange whole; a straddling or in-tail exchange returns end unchanged.
  • 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: anchorCacheBreakpoint returns the body unchanged on every error path; a missing block only increments a counter.
  • Checked that every path that splices (tryReuse, replayStale) sets CacheAnchorToolID, 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 in CoveredCount on every path that stores one (startAsyncSummary, deferSummary, registerKeepAliveCandidate).
  • Verified the new /stats fields wire through proxy.go and 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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. retreatPastLastToolExchange moves end back 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=tool message, and the span cannot end on an unanswered call on well-formed input.
    dropOrphanedToolResults in splice backstops malformed input, as before.
  • Index safety. Every index walk in the new code is guarded (first-1 >= start,
    call <= start short-circuits before msgs[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. CoveredCount freezes the retreated cut (end-start is passed to
    startAsyncSummary/registerKeepAliveCandidate/deferSummary), so a later reuse or
    replayStale splices at the same boundary and re-derives the same anchor id.
  • Cap. anchorCacheBreakpoint counts breakpoints on the body as rebuilt and writes only
    when the total is below 4. It can never produce a 5th breakpoint. elemMarks covers 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 same tool_use_id the normalizer read, so the raw-body match in
    anchorCacheBreakpoint always finds the block the splice kept.

Non-blocking

  • apply/metawrite.go:270 — on OpenAI-shaped traffic, a splice sets CacheAnchorToolID, but
    the anchor search is Anthropic-shaped (tool_result blocks). Every splice there increments
    cache_anchor_not_found although 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
    summaryStructureChanged matches only summarize'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's ToolCalls empty on Anthropic. attachToolUse (apply/apply.go:1727) lifts
    tool_use into ToolCalls in the normalized view, so they are populated on proxy traffic.
    The from-results search is unaffected; the comment is stale.
  • The three new /stats keys are not in docs/reference/reference.md. Their siblings
    (prefix_stash_oversized and others) are not listed either, so this matches existing
    practice. Optional to add.

What I checked

  • The full diff 65485b86..HEAD (2 commits), and CLAUDE.md + docs/design.md rules 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 Bedrock cachePoint spelling.
  • components/offload/summarize_pairing.go — retreatPastLastToolExchange and
    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), and start = 0.
  • components/offload/cache_aware_summarizer.go — all three CacheAnchorToolID set sites
    (tryReuse, replayStale inside declineButReplayStale, and the fresh path), and the retreat's
    position relative to trimSpanForKeptVerbatim, tryReuse, the gates, min_tokens,
    requiredCount, and registerKeepAliveCandidate.
  • components/offload/cache_aware_async.go — CoveredCount/CoveredHash are written from the
    retreated span, so reuse and stale replay stay consistent with the frozen cut.
  • apply/apply.go normalize — assistant tool_use messages survive normalization
    (attachToolUse), so the message before a tool run is the assistant turn the retreat expects;
    wireGroups gives sibling/tool messages their shared group.
  • apply/rebuildCountChanged — retained messages are re-emitted from original raw bytes, so
    the anchored tool_result block and its tool_use_id are 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.Snapshot fields, proxy.go /stats, the golden key list, and the
    promexport coverage map. The append-only /stats contract is kept (new keys only).
  • The PR description states the data dependence ("metadata only, no change"), per the
    docs/data-dependence.md rule. Live tests were not run (not approved); code review only.

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

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, at head 9b838fd13784.

Reviewer 2, finding 1 (an equal-count splice gets no anchor): fixed.

  • summaryStructureChanged (apply/summaryshape.go) now also recognises cache_aware_summarizer's header, so a one-message span reaches the count-changing rebuild, where the anchor is written. It is counted in the same /stats counters as any other splice (cache_anchor_written / _no_slot / _not_found).
  • Both headers are now constants in schema (SummaryHeader, CacheAwareSummaryHeader), used by both builders and by the check, so they cannot drift again. apply/responses.go uses the constant too.
  • New test TestAnEqualCountSpliceStillWritesTheAnchor: a span of exactly one message, the count unchanged (asserted), the kept tool_result must carry a breakpoint.
  • Mutation: drop the cache-aware header from the check (the pre-fix behaviour). The test fails with an equal-count splice wrote no anchor on the kept tool_result.

Both reviewers, non-blocking: OpenAI-shaped traffic counts cache_anchor_not_found on every splice: fixed.

  • The anchor now runs only for bodies with explicit breakpoints and tool_result blocks (Anthropic, Bedrock, Vertex: explicitBreakpointProvider).
  • New test TestAnOpenAISpliceDoesNotCountAMissingAnchor; the mutation "no provider gate" fails it (counted 1 missing anchor(s)).
  • Not changed: on OpenAI-shaped traffic the retreat still keeps the last tool exchange verbatim, with no anchor possible. That costs one tool output of compaction there. The summarizer cannot see the provider (no field on Ctx). Gating the retreat too needs a provider hint on Ctx; I would do it as a follow-up if you want it.

Both reviewers, non-blocking: the stale ToolCalls comment: fixed. Both retreatPastLastToolExchange's doc and requestedToolCalls' doc now say that apply's normalize lifts tool_use into ToolCalls (attachToolUse). The retreat finds the exchange from its results, so it does not depend on either.

Reviewer 2, non-blocking: dash undercounts breakpoints by one: left as is, on purpose. tr.Breakpoints is the INBOUND count, an input to cache attribution ("what the client sent"). Adding our anchor there would mix inbound and wire counts. The anchor itself is counted in /stats cache_anchor_written.

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 docs/data-dependence.md row change is needed.

Reviewer 1, non-blocking: the 3 new /stats keys are not in docs/reference/reference.md. As you note, their siblings are not listed either; left as existing practice.

Not changed: expand/response.go:158 still holds the === History Summary === literal. It is summarize's Responses-route restore path, and expand does not import schema; I did not add that import for one string in this PR.

How it was tested (eval box):

Run Result
the 2 new tests, plus the 4 earlier anchor tests PASS
M5: the equal-count check ignores the cache-aware header FAIL
M6: no provider gate FAIL
go test -race ./apply/... ./schema/... ./components/... PASS
go test -race ./proxy/... PASS (458 s)
go vet, gofmt -l clean

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Reviewer 2, finding 1 (an equal-count splice gets no anchor) — fixed. I verified the fix
    by hand on the new test's fixture:
    • summaryStructureChanged now matches both headers. In TestAnEqualCountSpliceStillWritesTheAnchor
      the fixture gives a one-message span (summarizeSpan end 3 → advance 4 → retreat to 2 over
      7 normalized messages), so tryReuse splices to 7 messages — equal count. The summary
      message's text now starts with schema.CacheAwareSummaryHeader, so the rebuild branch runs,
      rebuildCountChanged re-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.
  2. Both reviewers, non-blocking (OpenAI-shaped traffic counts cache_anchor_not_found on
    every splice) — fixed.
    The anchor now runs only when explicitBreakpointProvider(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 from prefixsplit's notion.
  3. Both reviewers, non-blocking (stale ToolCalls comments) — fixed. The new text in
    summarize_pairing.go matches what attachToolUse actually does, and says the retreat does
    not depend on it. Correct.
  4. Reviewer 2, non-blocking (dash undercounts breakpoints by one) — rejected by the author,
    and the reason is right.
    tr.Breakpoints is 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 in cache_anchor_written. I accept the rejection.
  5. My non-blocking (the 3 /stats keys not in reference.md) — rejected with reason. The
    sibling counters are unlisted there too. I verified that again; existing practice. Accepted.
  6. Author's declared "not changed": expand/response.go:158 keeps the
    === History Summary === literal.
    Its value equals schema.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 (the cachePoint spelling CountBreakpoints handles) carries no
    tool_result blocks, so a splice there still counts cache_anchor_not_found. It can never
    write a wrong key there (the write path requires a tool_result block), 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 on Ctx; 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 tree 5f501e03 against the rebased
      pre-fix tip 17a15f9c. The only differences are the #725 base changes
      (cheapmodel, extract_sweep, keepalive, docs). No PR-owned file differs — the rebase made no
      resolution changes. 56f59a7f itself touches no file this PR changes.
    • 9b838fd1 non-test diff: read in full (apply/apply.go gate, summaryshape.go,
      schema/summaryheader.go, both wrapper builders, responses.go, the two comment
      corrections in summarize_pairing.go).
    • 9b838fd1 tests: TestAnEqualCountSpliceStillWritesTheAnchor and
      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 (dash tr.Breakpoints is the inbound count; reference.md practice) and the
      "not changed" items (expand/response.go:158).
  • 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 insertAskMessage moves 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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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_summarizer in 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. rebuildResponsesCountChanged locates the summary by scanning for schema.SummaryHeader only (line 293). It finds none, head stays -1, and it returns ok=false. Line 603 then returns the original body, and the equal-count writeback loop below (lines 606-623) never runs. Before commit 9b838fd, summaryStructureChanged returned 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: summaryStructureChanged accepts 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_summarizer does reach this route: it checks neither DisallowCountChange nor AllowSummarySpan (only plain summarize does, summarize.go:329,390), and Opts.PrefixAsk is wired there (responses.go:586).
    • Fix: accept schema.CacheAwareSummaryHeader in the head scan at responses.go:293, next to schema.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.

Earlier findings, and this round's replies

  • My round-1 finding 1 (an equal-count splice gets no anchor): fixed on the Chat route. summaryStructureChanged now knows both headers (constants in schema/summaryheader.go), the builders use the constants byte-identically, and TestAnEqualCountSpliceStillWritesTheAnchor asserts 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 finds toolu_eq with 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 behind explicitBreakpointProvider (apply.go:786), the pre-existing helper that covers Anthropic, Bedrock, BedrockMantle and Vertex. TestAnOpenAISpliceDoesNotCountAMissingAnchor covers 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.go now say that attachToolUse lifts tool_use into ToolCalls.
  • Dash breakpoint undercount: declined with a reason, and the reason is right. tr.Breakpoints is 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_control key, metadata only." No docs/data-dependence.md row is needed.
  • Reviewer 1's round-1 notes (OpenAI counter, stale comment, reference.md keys, equal-count note) all match what I found in round 1; the first two are fixed as above, the reference.md keys 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 Ctx provider hint is a fair separate change.

Non-blocking

  • expand/response.go:158 still 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..HEAD lists 4 commits: 56f59a7f (the new base, #725's merge, not part of this PR), e4fdb79f and 17a15f9c (this PR's two original commits, re-authored), and 9b838fd1 (the new fix). A tree diff of 5f501e03 against 17a15f9c differs only in #725's files, so the re-authored pair is content-identical to what I reviewed in round 1. I read 9b838fd1'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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 2, at head 48a53e652f1a.

Reviewer 2, finding 1 (the Responses rebuild drops an equal-count cache-aware splice): fixed.

  • apply now has one test for a spliced summary, isSummaryHeader (apply/summaryshape.go): summarize's header or cache_aware_summarizer's. Both the equal-count gate and rebuildResponsesCountChanged use it, so the gate can never send a splice to a rebuild that cannot find it.
  • Every other place that scanned for a summary header: expand/response.go's in-place restore on the Responses route matched summarize's header only, so a cache-aware summary there was never restored in place (that gap predates this PR, but it is the same class, so it is fixed here too). It now accepts both, through local constants: expand imports no context-guru package. TestSummaryHeadersMatchSchema pins them equal to schema's.
  • The chat/Anthropic/Bedrock/Vertex rebuild (rebuildCountChanged) does not look for a header at all: it matches survivors by bytes and tool_call_id. A grep shows no other header scan.
  • New test TestResponsesCacheAwareOneMessageSpliceIsWritten: cache_aware_summarizer on the Responses route, a one-message span, input count asserted equal, and the summary must be written. It fails on 9b838fd1 (the round-1 head, which has the regression) and passes here.
  • Mutations: M7, the Responses rebuild knows summarize only: the test fails. M8, expand's restore knows summarize only: TestSummaryHeadersMatchSchema fails.
  • Note on the fixture: a short span is correctly reverted by the pipeline's never-worse guard, because the cache-aware wrapper is longer than a short message. The test's span is long enough that the summary saves tokens.

How it was tested (eval box):

Run Result
TestResponsesCacheAwareOneMessageSpliceIsWritten on 9b838fd1 FAIL
the same, this branch PASS
M7 / M8 FAIL each
go test -race ./apply/... ./schema/... ./expand/... ./components/... PASS
go test -race ./proxy/... PASS (466 s)
go vet, gofmt -l clean

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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=user with the header first (emitCheckpoint at summarize.go:749, the fresh path, and cacheAwareSummaryWrapper at cache_aware_summarizer.go:1186).
    • responsesSummarySpanSafe accepts 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 plain summarize already 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.go literal): fixed beyond what I asked. The in-place restore now accepts both headers (isSummaryText), from local constants. TestSummaryHeadersMatchSchema pins them to schema's, so they cannot drift. The Marker(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 behind explicitBreakpointProvider. No change since round 2.
  • Stale ToolCalls comments: stays fixed.
  • Dash breakpoint undercount: declined with a reason I accept (round 2): tr.Breakpoints is 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 that isSummaryHeader is 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 that rebuildResponsesCountChanged'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). rebuildCountChanged matches 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; helpers pipe, recordingModel, WaitForAllSummariesForTest all exist in the test package) and TestSummaryHeadersMatchSchema (pins both constants and exercises isSummaryText). 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 of schema is test-only, so the leaf package's own import graph is unchanged.
  • 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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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
      calls expand on the marker. The stash under that marker key is json.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 isSummaryText match sends that stash into the in-place restore. That restore's
      precondition is written at expand/response.go:122: "A Responses summary stash is an array of the
      exact input items it replaced." True for summarize, which stashes wire items through the
      SummaryStashPayload hook (apply/responses.go:580, summarize.go:333). False for
      cache_aware_summarizer, which never uses the hook.
    • The valid check (lines 146-152) does not stop it. It only asks that each element is an object
      with a role or a type. Normalized messages have role. So a span that covers a tool exchange
      splices {"role":"tool",...} messages (built by toolMessage, apply/apply.go:1764 — "synthetic
      OpenAI-shaped tool message") and assistant messages with tool_calls into input. The Responses
      API accepts message roles user, assistant, system and developer only. Calls are separate
      function_call items. 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 the function_call_output string. 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 through writeSurvivor;
      only the new expand path splices the normalized form directly.
    • Fix: in the valid check, also require each item to be a message this route accepts — role user,
      assistant, system or developer, and no tool_calls field. Items that fail fall through to the
      string answer, which is the old, valid behavior. Or limit the in-place path to summarize'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.

Earlier findings, and the author's replies

  1. 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 in rebuildResponsesCountChanged, so the gate cannot send a splice to a rebuild that
    cannot find it. I hand-traced TestResponsesCacheAwareOneMessageSpliceIsWritten end to end: 4
    input items, keep_last_turns 2, span [1,2), tryReuse splices to 4 messages (equal count),
    isSummaryHeader finds head=1, tail=2, spanEnd=2, first=last=1, and the splice is written with
    the count equal. On 9b838fd1 the 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.
  2. 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.
  3. 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.
  4. Reviewer 2's round-2 non-blocking (expand/response.go held a header literal) — fixed by this
    commit.
    The constants are mirrored locally and pinned by TestSummaryHeadersMatchSchema.
    Correct approach for a leaf package that imports no context-guru package.
  5. The author's reply claims, checked:
    • "One test for a spliced summary" — verified. isSummaryHeader is the only scan the gate and the
      Responses rebuild use.
    • "rebuildCountChanged needs 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.

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 (48a53e65 fix(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: rebuildResponsesCountChanged in 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
      builds resolved. That chain produced finding 1.
  • 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 3, at head d61c3bd57c14.

Reviewer 1, finding 1 (expand restores a cache-aware stash in place as non-wire items, a 400 on Responses): fixed.

  • New responsesInputItem in expand/response.go. In-place restore takes a stashed element only if it is a real Responses input item: a type item, or a role of user/assistant/system/developer with no tool_calls and no tool_call_id. Anything else (a normalized role: tool message, an assistant message with tool_calls) sends the stash as the flattened string answer, as before this PR.
  • summarize's stashes are wire items, so its in-place restore is unchanged (TestResponsesSummaryExpandRestoresImageAsImage still passes).
  • New test TestResponsesExpandOfACacheAwareToolStashStaysValid: a cache-aware stash holding a tool exchange, expanded on Responses. No role: tool and no tool_calls may reach input, and the stash travels as the function output.
  • Mutation M9, the old any-role-or-type check: the test fails (a normalized tool message was spliced into the Responses input).

CI failure, TestCacheAwareRealContentChangeInsideSpanStillDeclines (proxy): the cause, and the fix.

  • Cause: a race in the test-visible handoff from fix(offload): start a prefix-ask summary after this turn is stashed #724, not a loss of the stale-prefix guard. ResolveDeferredCacheAwareSummary took a deferral out of its registry and then called startAsyncSummary. In between it was neither registered nor in flight, so WaitForSummaryForTest, called right after the request, could see nothing pending and return. The test then read its counters before the call ran: no ask made, stale 0 -> 0, no_prefix 0 -> 0, exactly the CI line. Locally the test always passed (the call ran and asked over turn 3's own stash, one of its 3 accepted outcomes), and the turn has no tool exchange, so Summarizer: after a splice, every turn re-writes the kept history until the next tool call #723's retreat does not change its span.
  • Fix: a taken deferral is marked dispatching under the registry's own lock, before it leaves the registry, and the mark is cleared after startAsyncSummary returns (in the hook, both fallbacks, and the replaced-deferral path). WaitForSummaryForTest waits for that mark too, so there is no window where the job is invisible. No production behaviour changes.
  • New test TestWaitForSummaryCoversTheGapBetweenTakeAndStart: a test seam pauses the hook between take and start; the wait must not return in that window. Mutation M10 (no mark on take): the test fails (returned while a taken deferral had not started yet).
  • The CI test then passes 20 of 20 under -race on the box.

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

Run Result
the 2 new tests, plus every expand, anchor and deferral test PASS
M9 (expand any-role check) / M10 (no dispatching mark) / #724 mutation FAIL each
go test -race ./apply/... ./schema/... ./expand/... ./components/... PASS
go test -race ./proxy/... PASS (457 s)
TestCacheAwareRealContentChangeInsideSpanStillDeclines ×20 under -race PASS 20/20
go vet, gofmt -l clean

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. My round-3 finding 1 (expand restores a cache-aware stash in place as non-wire items, a 400 on
    Responses) — fixed.
    New responsesInputItem (expand/response.go) gates the in-place restore:
    • A role=tool message fails the role switch (no case for it) and falls to the flattened string
      answer. An assistant message with tool_calls or tool_call_id fails the field check. Both are
      the normalized shapes toolMessage and attachToolUse build — 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. So summarize's
      wire stashes keep the in-place restore, and a text-only cache-aware span keeps the improvement
      from round 3.
    • I traced TestResponsesExpandOfACacheAwareToolStashStaysValid by hand: a stash of one
      assistant-with-tool_calls and one role=tool message, a cache-aware summary carrying
      Marker("HASH"). The first element fails responsesInputItem, valid stays false, no
      replacement happens, and the stash travels as the function_call_output string. On the old
      any-role-or-type check the same trace splices the role=tool item and the test's ForEach fails
      — the M9 claim is consistent with the code.
  2. 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.
  3. 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.
  4. Reviewer 2's round-3 review — read in full this round. It approved 48a53e65 and 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. ResolveDeferredCacheAwareSummary took a deferral out of its registry and
    called startAsyncSummary only afterwards. In between, deferralPending was false and the job
    was not yet in inFlight, so WaitForSummaryForTest could 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. markDispatching runs before the deferral leaves
    its registry, under that registry's lock; doneDispatching runs after startAsyncSummary
    returns. deferralPending reads 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 call doneDispatching). 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
    WaitForSummaryForTest returns true, which requires dispatching to 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 — deferralPending sees the mark.
  • The fixture updates are right. The three #724 tests now stash end-1 of 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 (d61c3bd5 fix(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 the isSummaryHeader fix 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 —
      the responsesInputItem gate, 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.go in full, and all four touched tests in full.
  • Confirmed the base is unchanged (56f59a7f) and the commit adds no new production behavior beyond
    the expand gate (the dispatching map serves the test hook only).
  • Live tests were not run (not approved); code review only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_summarizer stashes json.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 that summarize uses.
  • normalizeResponses builds those messages: a function_call item becomes an assistant message with tool_calls; a function_call_output becomes a role=tool message with tool_call_id (toolMessage). At the round-3 head, the restore's valid check asked only for an object with a role or a type. Both shapes passed. Spliced into input, 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 no tool_calls and no tool_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 the function_call_output string — the behaviour before this PR. I read the whole Continuation responses branch to confirm this.
  • summarize's stashes are wire items, so its restore is unchanged. I checked each wire shape against responsesInputItem: message items, function_call, reasoning, function_call_output all pass, as before.
  • The normalized stash cannot contain other shapes that pass the check but are invalid input: normalizeResponses flattens 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, no role:tool or tool_calls reaches input, and the stash travels as the flattened answer. Correct.

The CI failure fix, checked

  • The gap was real at the round-3 head: ResolveDeferredCacheAwareSummary took a deferral out of its registry and called startAsyncSummary after. In between, the deferral was neither registered nor in flight, so WaitForSummaryForTest could return before the call ran.
  • The fix marks a taken deferral dispatching under the registry's own lock, before it leaves, and clears the mark after the dispatch returns. deferralPending reads that mark too. I checked every take/mark site pairs with a doneDispatching: 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 call takeWarmDeferral directly now clear the mark too.
  • Lock order is registry → dispatching only. No path takes them in the other order. No deadlock.
  • dispatching is read only by deferralPending, which only WaitForSummaryForTest uses. Production behaviour is unchanged, as the author claims.
  • The new test TestWaitForSummaryCoversTheGapBetweenTakeAndStart is sound: a prefix_ask commission 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 of end-start messages with start >= 1 refuses 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 in summarize_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. responsesInputItem against every stash shape both summarizers can produce (normalizeResponses in full, toolMessage, the function_call and reasoning branches); the whole Continuation responses branch for the flattened fallback; every take/mark/done pairing in cache_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.

@amiddavid
amiddavid merged commit 2b20ef2 into main Oct 26, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 26, 2026
amiddavid added a commit that referenced this pull request Oct 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Summarizer: after a splice, every turn re-writes the kept history until the next tool call

1 participant