Repository navigation
fix(apply): keep sibling text blocks beside a tool_result in the normalized view - #460
Merged
Merged
Conversation
…alized view apply.normalize turned each Anthropic tool_result block into a synthetic role=tool message and then skipped every other block in that user message, so mid-turn user text, system reminders, and task/teammate notifications sharing the message with a tool_result never reached the normalized view any component reads. The wire body was unaffected; only the view was. Walk every block of a user message that holds a tool_result (not just the tool_result blocks), and turn a sibling text block into its own synthetic, read-only role=user message in the same body order. A plain text user message with no tool_result is untouched, exactly as before. The new slot kind (anthropicSiblingText) is deliberately read-only: a component's edit to it is never written back, so a no-op pipeline still gives byte-identical output and no new write-back path can corrupt the body. Four related gaps the same change exposed, all fixed here: - Split boundary: summarizeSpan (shared by summarize and cache_aware_summarizer) could choose a span boundary that fell BETWEEN a tool_result and its sibling, asking the count-changing rebuild to keep half of one wire message and summarize the other half. It now aligns to the nearest wire-message edge via a new WireGroup Ctx field, in the same direction (advance/retreat) the existing tool-exchange-atomicity logic already uses. - A second, related gap: a group whose members are [sibling, tool_result] (sibling first, matching Claude Code's own block order) could put the tail boundary exactly on the sibling, which looks like role=user to the plain adjacency check while the tool_result one slot later orphans its tool_use. Fixed by scanning the whole group, not just the boundary message, for a role=tool member. - Ctx.RawInput, Ctx.WireGroup, Ctx.MaxCachedIdx (the Tracker's turn length) and the stale-prefix SpanHash/CoversSpan all derive from the SAME apply.normalize call on both sides of each guard, so they stay consistent with each other after this change. A session already in flight at deploy sees its cached-prefix boundary briefly out of step with the new indexing (self-correcting the next turn); see the PR body. - extract and extract_llm already select their targets via offload.toolIndices (role == tool), so a sibling (role == user) was never a candidate. Added a regression test for the invariant. Fixes #457. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
emitCheckpoint (summarize's replay path, used by both tryReuse and replayStale) had its own copy of the OLD role-only "advance past a tail that would begin mid-exchange" rule, separate from summarizeSpan's. #457's fix only updated summarizeSpan, so emitCheckpoint kept the exact gap that fix closed there: a replayed checkpoint's boundary can land on a sibling-first group's own start (role=user), which passes the plain `msgs[boundary].Role == Tool` check while the tool_result one slot later, in the SAME wire group, orphans a tool_use the checkpoint is about to drop. Extracted the shared rule into advanceSpanBoundary (summarize_pairing.go) and had both summarizeSpan and emitCheckpoint call it, so there is one implementation rather than two that can drift again. emitCheckpoint now takes the WireGroup slice from its callers (both already have components.Ctx in scope). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
force-pushed
the
fix/normalizer-siblings
branch
from
October 11, 2026 16:18
33fb73f to
015b476
Compare
…tale Reviewer notes ahead of #460's review, all four addressed: - summarize and cache_aware_summarizer now decline (gate wire_groups_stale, rep.Skipped) when Ctx.WireGroup is non-nil but no longer matches req.Input's length. That shape means wire groups DO exist on this request (Anthropic traffic normalized a shared message) but an earlier component changed the message count, so the groups' current positions are unknown. summarizeSpan's own defensive check already disabled alignment in that case, collapsing it to the SAME behavior as "no groups ever existed" (nil WireGroup, e.g. OpenAI-shaped traffic) and computing an unaligned boundary -- which can split a wire message that is really there, just not where WireGroup says. Declining is the safe, fail-open answer. New tests for both components. - Added a CoversSpan test (proxy/stale_prefix_sibling_test.go) proving the stale-prefix guard's stash re-normalizes a sibling-text group through the current apply.normalize, not a stale copy: a hardcoded expectation (4 normalized messages, not 3) fails first if that ever regresses, and a hash computed without the sibling is confirmed NOT to satisfy coverage of the sibling-inclusive span. - Verified the deploy-turn open question cannot happen through the proxy: store.NewMemory/store.Nop are the only two store.Store implementations in this repo, and proxy.New constructs modes.NewTracker(0) fresh on every process start -- nothing persists a boundary, a checkpoint or a stash entry across a restart. A deploy therefore starts every session with no boundary at all, the same as a brand-new session, never a mismatched- indexing turn. Closed in the PR body. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Collaborator
Author
Review of
|
| Point | Status |
|---|---|
| A turn on the old indexing right after deploy | Not reachable: store.NewMemory and store.Nop are the only stores, and the tracker starts fresh. A restart starts every session with no boundary, checkpoint or stash. |
CoversSpan must use the new normalizer |
Done: it calls apply.NormalizeMessages (prefixask.go:203). |
A stale WireGroup must decline, not act unaligned |
Done: gate wire_groups_stale in both summarizers. |
A cache_aware_summarizer splice test with a split group |
Present: TestCacheAwareSummarizerRebuildWithASplitGroup. |
Non-blocking note
The wire_groups_stale gate returns before the existing summary is replayed (summarize.go:380, cache_aware_summarizer.go:651). So on a turn where it fires, a session that already has a summary forwards its full history. The provider then re-writes the whole prefix (the same cache flip that replayStale exists to prevent).
- When it fires: only when a component before the summarizer changes the message count. Every preset puts the summarizer first, so the presets never reach it. A user pipeline can.
- Possible fix (follow-up): decline only the fresh commission there, and still let the replay path run, since a checkpoint's own boundary was aligned when it was made. Or state the limit in the docs.
No round 2 needed from my side.
amiddavid
added a commit
that referenced
this pull request
Oct 11, 2026
…lings #460 (fix/normalizer-siblings) merged, closing #457: apply.normalize now keeps a sibling block beside a tool_result in the normalized view, as its own synthetic role=user message in wire order, instead of dropping it. apply's own normalizer_siblings_test.go (TestNormalizeKeepsSiblingTextBlocksInOrder and friends) already covers the normalizer directly, so the pinning test this PR added before #460 existed (apply/normalize_siblingblock_test.go, which asserted the OLD, dropped behaviour) is deleted rather than flipped — keeping it would either duplicate #460's own coverage or assert the wrong thing. internal/waitcause gets three new tests instead, for what THIS package needs to get right now that the sibling reaches it: a tool_result plus mid-turn user text gives wake_cause=human, a tool_result plus a <task-notification> sibling gives wake_cause=background (both read off the LAST normalized entry, which is now the sibling, not the tool_result), and a sibling that is ONLY a <system-reminder> block does NOT read as human — apply.normalize's synthetic sibling message is always role=user, so isNoiseEntry's role check does not catch it; classifyWake's content-based hasSystemMarker check already does, and this pins that it keeps doing so. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
This was referenced Oct 11, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #457
Summary
apply.normalizedropped text next to a tool_result. It turned eachtool_resultblock into a message for components to read, then skipped every other block in
that same wire message. The wire body was fine. The view every component reads
was not.
This fix keeps those blocks. It adds 1 new slot kind, 1 new Ctx field, and
closes 4 related pairing/alignment gaps the fix itself opened — found across
two rounds of review.
What changed
The normalized view now keeps sibling text.
apply.normalizewalks everyblock of a user message that holds a
tool_result, not just thetool_resultblocks. A text block beside it — mid-turn user text, a system reminder, a task
or teammate notification — becomes its own synthetic
role=usermessage, inthe same order as the wire body. A plain text message with no
tool_resultisuntouched.
That new message is read-only. It has no safe single-field write-back
shape (several of these can share one wire message with a
tool_result), soa component's edit to it is discarded, never spliced into the body. A no-op
pipeline still gives byte-identical output.
The span boundary never splits a wire message.
summarizeSpan(shared bysummarizeandcache_aware_summarizer) could pick a cut that fell between atool_resultand its sibling. The count-changing rebuild has no way to keephalf of one wire message verbatim while summarizing the other half. A new
components.Ctx.WireGroupfield names, for each normalized message, the wiremessage it came from; the boundary now moves to the nearest wire-message edge,
in the same direction (advance/retreat) the existing tool-exchange-atomicity
logic already uses.
A second pairing gap in the same fresh path. A group shaped
[sibling, tool_result](sibling first — Claude Code's own block order) canput the tail boundary exactly on the sibling. The plain adjacency check sees
role=userthere and finds nothing wrong, while thetool_resultone slotlater orphans its
tool_use. Fixed by scanning the whole group for arole=toolmember, not just the message at the boundary.A third pairing gap, in the replay path.
emitCheckpoint(summarize'sreplay path — both
tryReuseandreplayStalecall it) had its own,separate copy of just the role-only half of the boundary rule. It is
reachable only through this PR's own sibling-first groups, so this PR
introduced the gap and this PR closes it: the rule is now one function,
advanceSpanBoundary, thatsummarizeSpanandemitCheckpointboth call,instead of two copies that can drift again.
A fourth gap: alignment silently turning itself off.
summarizeSpandisables the WireGroup check when its length doesn't match the message
count (an earlier component changed the count). That is the right call for
a request where groups never existed (nil WireGroup, e.g. OpenAI-shaped
traffic) — but a non-nil, merely STALE WireGroup means real wire groups
exist on this Anthropic request, just not at the positions the component
can still see. Proceeding unaligned there risks splitting a wire message
that is really there. Both
summarizeandcache_aware_summarizernowdecline (
wire_groups_stale, fail open) instead of guessing.extract / extract_llm: unaffected. Both already select targets through
offload.toolIndices(role == tool), which excludes a sibling byconstruction. Added a regression test for the invariant.
How it was tested
apply: text before, between and aftertool_resultblocks, both as a string and as an array. The normalized view holds all of
it in order; a no-op pipeline gives byte-identical output.
tool_result) isunaffected.
reaches the body (the read-only slot).
summarizetest confirms a mid-turn sibling's text reaches thesummarizer's prompt.
components/offloadfor the span-boundary fix: a cutthat would land inside a split wire message moves to its edge, and the
sibling-first orphan case (in
summarizeSpan) is covered on its own.emitCheckpointdirectly with a boundary that isonly unsafe through the sibling-first/replay path (not reachable from a
fresh
summarizeSpancall), so it is the one test that can catchemitCheckpointfailing to apply the shared rule itself.summarizeandcache_aware_summarizerdecline (
wire_groups_stale,req.Inputuntouched) on a mismatched,non-nil WireGroup, rather than acting unaligned.
proxyunit test (TestCoversSpanRenormalizesSiblingTextGroups)proves the stale-prefix guard's
CoversSpanre-normalizes a sibling-textgroup through the CURRENT
apply.normalize(a hardcoded 4-messageexpectation fails first if that regresses), and that a hash computed
without the sibling does not satisfy coverage of the sibling-inclusive
span.
applyrun the full commission-then-splice cyclefor both
summarizeandcache_aware_summarizer, with the split grouppositioned inside the summarized span AND inside the kept tail. Both check
the wire-level
tool_use/tool_resultpairing directly (not there-normalized view — see Technical notes and schema.ValidateShapeFor's tool-pairing check assumes normalized-view adjacency, false-positives on a sibling-first group #461).
extract/extract_llmregression test confirms a sibling text blockis never treated as a tool output to reduce.
TestXHighPresetCommitsACacheAwareSummary,TestHighPresetCommitsACacheAwareSummary,TestMediumPresetDoesNotSummarizeOnAWarmTurn,TestCacheAwarePipelineOrderMinimalTextCleanCase,TestSweepGuardUsesRawCoordinatesNotPipelinePosition,TestCacheAwareStalePrefixThroughARealOversizedTurn,TestResponsesSetsRawInputBeforeThePipelineRewrites— run on this branchrebased onto current
main(feat(config): switch the xhigh preset to cache_aware_summarizer #414 and feat(config): run cache_aware_summarizer in medium (pre_expiry) and high (any) #456 are merged, so no temporarymerge is needed any more).
go test -race -count=1on./apply/...,./components/...,./proxy/...,./dash/...: all green, run separately per package set.Open questions
None outstanding. The one from the previous round (a session mid-conversation
at deploy reading its cached-prefix boundary against new indexing) is closed:
store.NewMemory/store.Nopare the only twostore.Storeimplementations inthis repo, and
proxy.Newconstructsmodes.NewTracker(0)fresh on everyprocess start. Nothing persists a boundary, a
summarize/cache_aware_summarizercheckpoint, or a
sentStashentry across a restart — a deploy starts everysession with no boundary at all, exactly like a brand-new session. The
mixed-indexing turn I was worried about cannot happen through the proxy.
Technical notes
schema.ValidateShapeFor'sanswered-tool-use/paired-tool-resultchecksassume a
tool_useand itstool_resultare ADJACENT in the normalizedview. That assumption breaks for a
[sibling, tool_result]group (siblingfirst), because the normalized view now puts the sibling between them. It
is not used anywhere on the request path (grep confirms test-only), so
this is not a production bug, but it IS a blind spot for any future test
that re-normalizes apply.normalize drops text blocks that share a user message with a tool_result #457-shaped output and validates the result that way.
My new integration tests check wire-level pairing directly instead
(
assertAnthropicWirePairinginapply/normalizer_siblings_test.go).Filed as schema.ValidateShapeFor's tool-pairing check assumes normalized-view adjacency, false-positives on a sibling-first group #461, with a proposal, rather than fixed here.
wireGroups(apply/apply.go) derives the group id straight from eachslot's existing body-message index (
splitSlotPath), so no new bookkeepingwas needed in
normalizeitself — awholeMessageslot's index is alwaysdistinct from its neighbors by construction, and an
anthropicToolText/anthropicSiblingTextslot's index is exactly the thing that must notsplit.
advanceSpanBoundary(components/offload/summarize_pairing.go) is nowthe single place that decides "is it safe for a kept tail, or a replayed
checkpoint's tail, to begin here" —
summarizeSpan's end-advance andemitCheckpoint's boundary-advance both call it, so the rule cannot driftinto two different implementations again.
wireGroupsStale(same file) is the single place that decides "isWireGroup usable at all" — both
summarize.Offloadandcache_aware_summarizer.Offloadcheck it right after their unconditionaltakeDeferredUsagecall and before doing anything else with the span, sothe stale-decline never skips the deferred-usage accounting that must run
on every turn regardless of what this turn decides.
🤖 Generated with Claude Code