Skip to content

fix(apply): keep sibling text blocks beside a tool_result in the normalized view - #460

Merged
amiddavid merged 3 commits into
mainfrom
fix/normalizer-siblings
Oct 11, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/normalizer-siblings

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #457

Summary

apply.normalize dropped text next to a tool_result. It turned each tool_result
block 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.normalize walks every
block of a user message that holds a tool_result, not just the tool_result
blocks. A text block beside it — mid-turn user text, a system reminder, a task
or teammate notification — becomes its own synthetic role=user message, in
the same order as the wire body. A plain text message with no tool_result is
untouched.

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), so
a 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 by
summarize and cache_aware_summarizer) could pick a cut that fell between a
tool_result and its sibling. The count-changing rebuild has no way to keep
half of one wire message verbatim while summarizing the other half. A new
components.Ctx.WireGroup field names, for each normalized message, the wire
message 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) can
put the tail boundary exactly on the sibling. The plain adjacency check sees
role=user there and finds nothing wrong, while the tool_result one slot
later orphans its tool_use. Fixed by scanning the whole group for a
role=tool member, not just the message at the boundary.

A third pairing gap, in the replay path. emitCheckpoint (summarize's
replay path — both tryReuse and replayStale call 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, that summarizeSpan and emitCheckpoint both call,
instead of two copies that can drift again.

A fourth gap: alignment silently turning itself off. summarizeSpan
disables 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 summarize and cache_aware_summarizer now
decline (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 by
construction. Added a regression test for the invariant.

How it was tested

  • New unit tests in apply: text before, between and after tool_result
    blocks, 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.
  • A new unit test confirms a plain text message (no tool_result) is
    unaffected.
  • A new unit test confirms a component's edit to the sibling message never
    reaches the body (the read-only slot).
  • A new summarize test confirms a mid-turn sibling's text reaches the
    summarizer's prompt.
  • New unit tests in components/offload for the span-boundary fix: a cut
    that would land inside a split wire message moves to its edge, and the
    sibling-first orphan case (in summarizeSpan) is covered on its own.
  • A new unit test calls emitCheckpoint directly with a boundary that is
    only unsafe through the sibling-first/replay path (not reachable from a
    fresh summarizeSpan call), so it is the one test that can catch
    emitCheckpoint failing to apply the shared rule itself.
  • New unit tests confirm both summarize and cache_aware_summarizer
    decline (wire_groups_stale, req.Input untouched) on a mismatched,
    non-nil WireGroup, rather than acting unaligned.
  • A new proxy unit test (TestCoversSpanRenormalizesSiblingTextGroups)
    proves the stale-prefix guard's CoversSpan re-normalizes a sibling-text
    group through the CURRENT apply.normalize (a hardcoded 4-message
    expectation fails first if that regresses), and that a hash computed
    without the sibling does not satisfy coverage of the sibling-inclusive
    span.
  • New integration tests in apply run the full commission-then-splice cycle
    for both summarize and cache_aware_summarizer, with the split group
    positioned inside the summarized span AND inside the kept tail. Both check
    the wire-level tool_use/tool_result pairing directly (not the
    re-normalized view — see Technical notes and schema.ValidateShapeFor's tool-pairing check assumes normalized-view adjacency, false-positives on a sibling-first group #461).
  • A new extract/extract_llm regression test confirms a sibling text block
    is never treated as a tool output to reduce.
  • These existing tests still pass, with their ask-call counts unchanged:
    TestXHighPresetCommitsACacheAwareSummary, TestHighPresetCommitsACacheAwareSummary,
    TestMediumPresetDoesNotSummarizeOnAWarmTurn,
    TestCacheAwarePipelineOrderMinimalTextCleanCase,
    TestSweepGuardUsesRawCoordinatesNotPipelinePosition,
    TestCacheAwareStalePrefixThroughARealOversizedTurn,
    TestResponsesSetsRawInputBeforeThePipelineRewrites — run on this branch
    rebased 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 temporary
    merge is needed any more).
  • go test -race -count=1 on ./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.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 summarize/cache_aware_summarizer
checkpoint, or a sentStash entry across a restart — a deploy starts every
session 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's answered-tool-use/paired-tool-result checks
    assume a tool_use and its tool_result are ADJACENT in the normalized
    view. That assumption breaks for a [sibling, tool_result] group (sibling
    first), 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
    (assertAnthropicWirePairing in apply/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 each
    slot's existing body-message index (splitSlotPath), so no new bookkeeping
    was needed in normalize itself — a wholeMessage slot's index is always
    distinct from its neighbors by construction, and an anthropicToolText/
    anthropicSiblingText slot's index is exactly the thing that must not
    split.
  • advanceSpanBoundary (components/offload/summarize_pairing.go) is now
    the single place that decides "is it safe for a kept tail, or a replayed
    checkpoint's tail, to begin here" — summarizeSpan's end-advance and
    emitCheckpoint's boundary-advance both call it, so the rule cannot drift
    into two different implementations again.
  • wireGroupsStale (same file) is the single place that decides "is
    WireGroup usable at all" — both summarize.Offload and
    cache_aware_summarizer.Offload check it right after their unconditional
    takeDeferredUsage call and before doing anything else with the span, so
    the stale-decline never skips the deferred-usage accounting that must run
    on every turn regardless of what this turn decides.

🤖 Generated with Claude Code

…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
amiddavid force-pushed the fix/normalizer-siblings branch from 33fb73f to 015b476 Compare October 11, 2026 16:18
…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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Review of 3f069e8 (summarizer line): OK to merge, 1 non-blocking note

Result: the four points I raised are all handled. I found no blocking problem for summarize, cache_aware_summarizer, the stale-prefix guards or the presets.

What I ran (eval box, CGO_ENABLED=1, PR head 3f069e8)

  • go build ./..., go vet, gofmt -l: clean.
  • go test ./apply/... ./components/... ./proxy/... ./config/...: pass.
  • The new and related tests pass, among them: TestSummarizeSpanNeverCutsAWireGroup, TestSummarizeSpanDoesNotOrphanAToolResultBehindASibling, TestEmitCheckpointDoesNotOrphanAToolResultBehindASibling, TestSummarizeSeesMidTurnSiblingText, TestCacheAwareSummarizerRebuildWithASplitGroup, TestSummarizeDeclinesOnStaleWireGroups, TestCacheAwareSummarizerDeclinesOnStaleWireGroups, TestCoversSpanRenormalizesSiblingTextGroups, TestExtractNeverTreatsASiblingTextBlockAsAToolOutput, and the preset tests (TestXHighPresetCommitsACacheAwareSummary, TestHighPresetCommitsACacheAwareSummary, TestMediumPresetDoesNotSummarizeOnAWarmTurn, TestPresetLadderSummarizerModes).

My four points

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
amiddavid merged commit acbe5e1 into main Oct 11, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 11, 2026
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]>
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.

apply.normalize drops text blocks that share a user message with a tool_result

1 participant