Skip to content

🤖 fix: send a volatile system-tail change as a system row, keep the history cached - #6687

Merged
ThomasK33 merged 5 commits into
mainfrom
tk/f11-volatile-tail-row
Oct 15, 2026
Merged

ThomasK33 merged 5 commits into
mainfrom
tk/f11-volatile-tail-row

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Summary

When the volatile part of the system prompt changes inside a context (hot memories, the MCP warning, context-window IDs), Anthropic requests now keep the cached history. Before this PR, Anthropic received the system prompt before the messages, so every such change made the whole cached history be written again. Inside a context segment, the system tail now stays frozen. A change is sent as one mid-conversation system row after the newest user message, and every rebuild puts that row back in the same place. This is prompt-cache mechanism 10 (F11 in the prompt-cache program).

Background

Live data from one Xum host over 19.8 hours and 1,555 Anthropic turns, on one build with no restart: mechanism 10 caused 32 prefix breaks. Together they rewrote 1.86 histories per 100 turns. 26 of the 32 came in two hours while agents edited shared memory files, because hot memories sit in the system tail. A tail change also makes replayed thinking fail its signature check, because Anthropic binds thinking to the prefix. In the same data, signature 400s ran at 0.125 per turn and peaked in the same hours.

Implementation

  • Frozen tail. At the start of a segment, the system prompt carries the live tail as before. The turn's assistant row records it in metadata.volatileSystemTail = { text, placement: "system" }. While the segment lasts, the system tail stays at the latest "system" record.
  • A change becomes a row. When the live tail differs from the last tail sent, Xum appends one role: "system" row after the newest user message and records placement: "row" on the turn's assistant row. Every rebuild puts the row back right before that assistant row. An unchanged tail adds nothing.
  • Why the record goes on the assistant row: a dropped assistant row (an empty aborted turn) drops its row too, so a row always comes right before its own assistant row and never after an assistant message. Xum persists no new message row, so the UI, session history and compaction see no change.
  • Supported routes and models: only the anthropic and coder wire routes, and only models on the existing anthropicBindsThinkingToPrefix list (Opus, Sonnet and Haiku 5.5, and Fable 5.1). Everything else keeps today's placement: other providers, mux-gateway, OpenRouter, ZDR, and Sonnet 4.5. The AI SDK sends the mid-conversation-system-2026-04-07 beta header by itself.
  • When the newest message is an assistant row (for example a resume), a changed tail goes into the system prompt as before, and the segment freezes there.
  • Compaction or any other context boundary resets the frozen tail.
  • Rows off: a request sends the live tail in the system prompt with no rows, and records nothing, when the tail is empty, when middleware edited the tail so it does not split off whole, and for compaction requests (their trim already fitted the history to its budget).
  • One description of the sent system content: the assembler returns sentSystem (stable part plus frozen tail, its volatile length, and the rows' text). The turn envelope, the replay verifier, the debug snapshot, MUX_DEBUG_LLM_REQUEST and systemMessageTokens all use it, so they describe the request that went out. The replay rebuild derives the live tail from the turn's record.
  • Re-freeze: only rows recorded after the latest "system" record apply, so a re-freeze drops the earlier rows.
  • Rebuilds: a thinking-level fold and a step-0 rebuild record their own tail plan, and a refusal fallback's baseline record never overwrites a newer one.
  • Thinking-replay receipts (🤖 fix: keep Anthropic thinking sent after a replay strip on later turns #6372): the rows are request messages, not parts of an assistant row, so they shift no part or step index that anthropicThinkingReplayFromStep uses.

Validation

Each test fails with its part of the fix reverted:

  • The hotMemoryChangeKeepsHistoryCached repro from 🤖 tests: pin prompt-cache prefix breaks across turns as repro tests #6234 is now a plain passing test.
  • A wire test through the real TurnRequestBuilder and pipeline builds the Anthropic SDK body. Turn 2 keeps the system prompt unchanged, extends turn 1's messages byte for byte, and ends with the system row that carries the new tail. Turn 3, with an unchanged tail, adds no row.
  • Assembler tests:
    • the tail freezes, a change becomes a row, and the rebuild puts the row back in place,
    • Sonnet 4.5, mux-gateway, Gemini and the assistant-last case keep today's placement,
    • a compaction resets the frozen tail.
  • A receipt test: with rows in the segment, the receipt's step point stays the same.
  • Review fixes, each with a test that fails when its fix is reverted: re-freeze drops earlier rows; thinking-level fold and step-0 rebuild records; fallback record ordering; unsplittable or empty tail; compaction requests send no rows; envelope, debug snapshot, replay round trip and token count match the sent request.
  • Live check through the Coder gateway (claude-aws-us-east-2) with thinking on, over three turns where turn 2 changes the tail. Every request returned 200 with no 400. Each request read the whole previous request from the cache, and the replayed thinking blocks were accepted. Models tested: Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1. The check cost about $0.34. I re-ran it on the final head 8504f6c after the review fixes: all 12 requests returned 200 with no 400, every turn read the whole previous request from the cache (system row included), and replayed thinking was accepted. That run cost about $0.26.

Risks

Medium. The change touches how every Anthropic request on the two supported routes places the volatile system sections.

  • Downgrade: an older build ignores the field and sends the live tail in the system prompt, which costs one cache rewrite. After an upgrade, the last record decides again, which costs one more rewrite and possibly one signature 400 that the existing repair handles. Nothing bricks, and a corrupt record is ignored.
  • New prompt text: each row starts with a one-line note saying that its sections replace the earlier ones, so the model treats a removed section as gone.
  • Size: about 1,180 lines added and 80 removed across 18 files, most of them tests. It is over the 500-line guideline. Splitting would separate the fix from its tests.

Known limits (not fixed here):

  • Prefix swap: a continuous-compaction prefix swap moves every system message, rows included, to the front of the swapped request. The content stays correct (rows stay in order, so the last one wins), but a row after the cut appears twice. The swap rewrites the prefix anyway, and the next turn starts a new segment.
  • Tail becomes empty mid-segment: the request sends the stable part only, which costs one cache rewrite. Main costs the same rewrite on that change.
  • A recorded row that no longer follows a user row is skipped (self-healing, because Anthropic rejects a system row after an assistant message). If that ever happened while the live tail still equals the skipped row's text, the request would carry the older tail. I found no history that puts a non-user row between a user message and its assistant reply after the filters, but no test covers it. Follow-up: a test, or compare the live tail with the last row actually restored.
  • Replay with a primary and a fallback envelope in one turn: the replay uses the turn's final record. Both requests plan the same rows from the same history, but no test covers a case where they differ.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high • Cost: $398.12

…istory cached

Prompt-cache mechanism 10 (F11): the volatile system tail (hot memories, MCP
warning, context-window ids) ends the system prompt, and Anthropic puts the
system prompt before the messages, so any tail change inside a context segment
rewrote the whole cached history (and broke prefix-bound thinking replay).

Inside a segment the system tail now stays frozen at the value the segment
first sent. A change goes into one `role: "system"` row after the newest user
message, and the turn's assistant row records it in
`metadata.volatileSystemTail`, so every rebuild puts the row back in place and
the next request extends the previous one. An unchanged tail adds nothing. A
compaction or other context boundary resets the frozen tail. Only routes and
models verified to accept the row use it (direct Anthropic and the Coder
gateway, models that bind thinking to the prefix); everything else, and a
request whose newest row is an assistant row, keeps the old placement.

The hot-memory repro in promptCachePrefix.inTurnVsRebuild.test.ts is now a
plain test.

---
_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->

(cherry picked from commit b8c72fb5c93bcc812817578c3b67d820b1f50487)
planVolatileSystemTail reads the segment's records and restores their rows in
two small helpers, and assemblePromptPayload gets the system split and tail
plan from planSystemPrompt. Behavior is unchanged.

---
_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->

(cherry picked from commit 156d047ab7cc57b09538506f16f0bded592ebaf6)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T08:52:10.333973Z 8504f6c New commits
🔒 Security Review ✅ Completed 2026-10-15T08:54:33.714941Z 8504f6c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5414d8a2b8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/node/services/turnRequestBuilder.ts Resolved
…d 1)

Three Codex findings on #6687:

- A re-freeze (a tail change on an assistant-last resume) put the new tail
  in the system prompt but kept the segment's earlier rows, which say they
  replace the earlier sections. Only rows recorded after the latest
  "system" record now apply, and a re-freeze sends none.
- A thinking-level rebuild can change which reasoning-only rows are sent,
  and with them the tail rows, but the turn kept the first assembly's
  record. The fold and the step-0 rebuild now return their own record, and
  the row stores it (StreamManager applies the step-0 one).
- A tail that request.assemble middleware edited could not be split, yet
  rows were still planned on the empty or partial rest. A partial split now
  counts as no split, and an empty tail turns the rows off for the request
  (it records nothing, so the next turn plans from the earlier records).

---
_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a7229ef559

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/node/services/turnRequestBuilder.ts Resolved
Two Codex findings on #6687:

- A fallback hop spread its initialMetadataPatch after the fallback stream
  had started, so a step-0 thinking rebuild's newer volatile-tail record was
  overwritten by the prepared baseline. StreamManager now applies the patch
  right after the fallback stream is constructed, before any await; the
  rebuild records only after an await, so its record wins.
- The compaction trim fits the history to its budget before the volatile
  tail is planned, so rebuilt tail rows could push a compaction request past
  it. Compaction requests (they carry a budget) now send the live tail in
  the system prompt with no rows and record nothing. Their system prompt is
  the Compact agent's, so no cached prefix is lost, and the summary starts a
  new segment.

---
_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b8d97711c7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…view round 3)

Two Codex findings on #6687, plus the consumers a sweep found:

- Turn envelope and debug views recorded the live system message (stable +
  B) while the request sent the frozen tail (stable + A) and a B row, so the
  replay verifier reported systemPromptMatch:false on every tail change.
  assemblePromptPayload now returns sentSystem, and TurnRequestBuilder's
  envelope, debug snapshot and MUX_DEBUG_LLM_REQUEST log use it. The replay
  rebuild derives the live tail from the turn's record (or the segment's
  last tail), so it rebuilds the same request from the sent system.
- The stored systemMessageTokens counted only the live system string, and
  the tail rows exist only in the request, so continuous-compaction sizing
  undercounted them. It now counts the sent system plus the tail rows, also
  after a thinking fold and a step-0 rebuild.

---
_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->
@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 15, 2026
Merged via the queue into main with commit 154c4b8 Oct 15, 2026
62 of 64 checks passed
@ThomasK33
ThomasK33 deleted the tk/f11-volatile-tail-row branch October 15, 2026 09:30
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Oct 15, 2026
…er#6761)

## Summary

A recorded volatile-tail row that no longer follows a user row is
skipped, and before this PR Xum then sent only the older frozen tail.
The model saw stale volatile content (for example old hot memories). Xum
now compares the live tail with the tail the request already applies
(the last row put back, else the frozen tail), so a skipped row makes
Xum append a fresh row. The PR also adds a test that shows the
continuous-compaction prefix swap keeps each tail row once and in order.

## Background

coder#6687 sends a change of the volatile system tail as a mid-conversation
system row. Its "Known limits" listed two cases without a test. This PR
settles both:

1. **Skipped row: a real bug.** The filter that drops empty assistant
rows depends on the thinking level. A reasoning-only partial (a turn
stopped while the model was thinking) is kept with thinking on and
dropped with thinking off. Steps that reach the bug:
1. Thinking is on. The user stops a turn while the model thinks, so `a2`
is a reasoning-only partial.
2. The user turns thinking off, the hot memories change to B, and the
user resumes. The filter drops `a2`, so Xum appends row B, and `a3`
records `{B, row}`.
3. The user turns thinking on again and sends `u3`. Now `a2` sits
between `u2` and `a3`, so Xum skips row B.
4. The live tail B equals the last record's text, so Xum added no row.
The model read only the frozen tail A.
2. **Prefix swap: no bug.** The swap lifts every system message to the
front and keeps the request from the anchor tool call on. The anchor is
in the live assistant message, and every tail row sits before an
assistant row, so no row lies after the cut.

## Implementation

- `withRecordedRows` returns the tail of the last row it put back.
`restoreFrozenSegment` returns the frozen segment and `appliedTail`
(that tail, else the frozen one). `planVolatileSystemTail` compares the
live tail with `appliedTail`.
- The replay rebuild uses the same rule when a turn has no record, so a
turn that an older build sent still replays as it was sent.

## Validation

- `turnContextAssembler.test.ts`: replays the steps above through
`assemblePromptPayload`. It checks that the last message is a B row,
that the request records `{B, row}`, and that a replay of the fixed
request and of the stale request an older build sent each match what was
sent. It fails without the fix (`Expected: "system-row"`, `Received:
"user"`). Reverting only the replay rule fails the replay assertion.
- `streamManager.continuousCompaction.test.ts`: builds a request with
the frozen A, a restored row B and an appended row C, applies a prefix
swap, and checks that the swapped request's system messages are exactly
`[stable, A, row B, row C]`. A mutation that cuts one message earlier
makes row C appear twice and fails the test.

## Risks

Low. Only histories that hit the skipped case change: they get one extra
row, which changes the cached prefix after that point. The cache already
broke there, because `a2` was not in the earlier request.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$434.77`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=434.77 -->
azaj01 pushed a commit to azaj01/mux that referenced this pull request Oct 25, 2026
…on (coder#7304)

## Summary

A mid-session change to a workspace's AGENTS.md no longer rewrites the
whole cached Anthropic history. Inside a context segment (between
compactions), the instruction-file blocks (`<custom-instructions>` and
the `<model-...>`/`<mode-...>` sections scoped in AGENTS.md) now stay at
the text the segment first sent, and Xum reads that text from the ledger
(chat.jsonl), not from the live files. When the live blocks differ, Xum
sends the new blocks as one system row after the newest user message, so
the model follows the new instructions on that turn. Every later rebuild
puts the row back in the same place, so the next turn's prefix still
matches. The next compaction folds the current block into the system
prompt.

## Background

Measured on one host (10-22 08:12 to 10-23 01:28 UTC, 1,548 Anthropic
turns, a build with coder#7027 and coder#7029): 26 `cache.prefix_break` events in
the system section, 1.45 rewritten histories per 100 turns, the largest
class left. Each break's length change equals a `docs/AGENTS.md` change
on main (+168 chars = coder#7117, +378 = coder#7176, about +1,214 = coder#7234). Agents
merge main into their worktree, and the next turn read the new AGENTS.md
into the stable system prompt. Turn envelopes showed the volatile-tail
length unchanged at every break, so the change was in the stable part.

The history already comes from the ledger. The system prompt did not: it
was rebuilt from live files on every turn (`turnContextAssembler.ts`,
`buildSystemMessageFromSources`). This PR makes the cached instructions
come from the ledger too.

## Implementation

- New `MuxMetadata.customInstructions = { text, placement: "system" |
"row" }` on the turn's assistant row, the same shape and rule as
`volatileSystemTail` (coder#6687). Xum writes it only at a segment start and
when the blocks change, not on every turn.
- `buildSystemMessageFromSources` now returns the system message plus
the exact instruction-file span (the text before it and the blocks). The
assembler freezes that span only while the prompt still starts with the
reported text, so it never parses the final prompt for tags.
- `volatileSystemTail.ts` generalizes its planner to "system sections"
(`planSystemSection`): the volatile tail and the instruction blocks are
two channels with their own field, row header and row id. Instructions
plan first, so their rows come first.
- A segment that starts with no instruction blocks records an empty
baseline, so a first AGENTS.md added later is a row, not a rewrite.
- If every instruction file is deleted or emptied mid-segment, the
frozen blocks stay in the system prompt and a row says the instructions
were removed.
- The row header says the blocks come from Xum, not the user, and
replace the system prompt's blocks. In a live check, Haiku 5.5 ignored a
bare "Update: ..." header in 2 of 3 runs and followed this wording in 4
of 4.
- Same gating as the volatile-tail rows (Anthropic and Coder routes,
models that bind thinking to the prefix). Other routes keep today's
behavior.

## Validation

- Real-request prefix tests (real system prompt and tools): with
AGENTS.md rewritten between turns, the tools section and cached system
block are byte-identical on turns 1 to 3, turns 2 and 3 carry the same
row, and the compaction turn has the new blocks. A `## Mode:` edit, a
removed AGENTS.md and a first AGENTS.md added mid-segment behave the
same way. A `</custom-instructions>` line in later instructions does not
widen the frozen span. Each test fails with its fix reverted.
- `tests/ipc/tokenBudgetStages.fixture.integration.test.ts` grew the
prompt by rewriting AGENTS.md. With this PR the request really carries
both the old and the new block, so the larger estimate is correct. The
fixture now grows the prompt through the workspace scratchpad, which
stays live; its expected numbers are unchanged.
- Live check on direct Anthropic (under $0.50): with a 17.2k-token block
changed between turns, turn 2 read 17,167 tokens from the cache and
wrote only the 17,182-token row; turns 3 and 4 read from the cache.

## Risks

Medium. It changes how the system prompt is assembled for Anthropic
turns.
- **Context cost:** while a changed block is live, each request carries
the old blocks in the cached system prompt plus the full new blocks in
the row. For this repo's AGENTS.md plus a global `~/.xum/AGENTS.md` that
is about 10.8k extra tokens until the next compaction. They are written
to the cache once and read after that.
- `Tool: <name>` sections from AGENTS.md go into tool descriptions and
are not frozen here: an edit to one still rewrites the cached tool block
(follow-up).
- Old histories (no record) behave as before: the first turn sends the
live block and records it. A malformed record is ignored. An older build
ignores the field.
- A follow-up PR applies the same rule to the `agent_skill_read` skill
list.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$585.33`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=585.33 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant