Skip to content

🤖 tests: pin prompt-cache prefix breaks across turns as repro tests - #6234

Merged
ThomasK33 merged 4 commits into
mainfrom
tk/cache-prefix-repro-tests
Oct 12, 2026
Merged

ThomasK33 merged 4 commits into
mainfrom
tk/cache-prefix-repro-tests

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds eight deterministic repro tests for prompt-cache prefix breaks across a turn boundary, plus a passing control. Each repro passes while its break exists and fails with "repro passed" once a fix removes it, so every Phase 1 fix PR must turn its repro into a plain test. No production code changes.

Background

Inside a turn, the AI SDK builds each step's request by appending the previous step's results from memory. The next turn rebuilds the whole conversation from chat.jsonl. When the rebuild produces different bytes, the first difference lands inside the previous turn, and Anthropic writes everything after it to the cache again.

On one dogfood host, about one in three agent turns started with a cold cache even though the previous request was well inside the TTL. The existing prefix matrix (#5296, #5407) compares two rebuilt requests, so it cannot see this class of break.

This is the first PR of a stack that makes prompt-cache cost measurable (pricing, Costs-tab cache health, a runtime prefix-break detector, and a replay check of every step).

Implementation

promptCachePrefix.inTurnVsRebuild.test.ts runs one real turn through the real StreamManager, the AI SDK Anthropic provider and Xum's wire cache-control wrapper, against a scripted local SSE fetch. It persists the turn to a real HistoryService, appends a monitor-style wake, rebuilds the next request the production way (assemblePromptPayload), and compares the wire bodies with cache_control removed.

Each repro uses expectReproFailure and pins the index of the first diverging message. A repro that breaks for another reason fails instead of passing.

Repro Mechanism
model-only tool notifications __mux_notifications is sent in-turn, then stripped before persisting
MCP-style toModelOutput In-turn text blocks, rebuilt as a JSON string (no tools passed to convertToModelMessages)
tool result over 12,000 chars The rebuild alone truncates it (providerOutputSanitization.ts)
repeated no-progress task_await polls The rebuild alone coalesces them
a step that opens with a tool call The rebuild drops step boundaries, so two sequential calls replay as one parallel call
a tool that throws In-turn is_error result, rebuilt as a normal JSON result
attach_file media The rebuild moves the image behind the turn's last text
hot-memory change in the volatile system tail The tail is a system block, so a change rewrites all history after it

Validation

  • With the 12,000-char limit raised in a scratch edit, the truncation repro fails with "repro passed". All other cases kept passing. I reverted the edit.
  • Earlier, while investigating, the notification and truncation mechanisms were disabled one at a time, and each repro turned green.

Follow-ups

  • When the Phase 1 fix for the volatile system tail turns the hot-memory repro into a plain test, it must also check that the previous turn's final answer precedes the trigger (endsWithAnswerThenTrigger), as the helper-based cases do. Owner: the PR that fixes the volatile tail (review round 4 of this PR).

Risks

Test-only. The file is 574 lines, most of it the scripted SSE harness the cases share.


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

Eight repros (expectReproFailure, pinned divergence index) plus a passing
control. Each passes while its break exists and fails with 'repro passed'
once fixed. No production code changes.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 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-12T13:05:34.788615Z c443091 New commits
🔒 Security Review ✅ Completed 2026-10-12T13:01:31.001091Z c443091 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: fc9ff3eb98

ℹ️ 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".

@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: 56e8b8c4b6

ℹ️ 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".

@ThomasK33
ThomasK33 added this pull request to stack #6240 October 12, 2026 12:40

@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: b97662fbdc

ℹ️ 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".

@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: c443091f59

ℹ️ 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".

@ThomasK33

Copy link
Copy Markdown
Member Author

Stopping the review loop on this PR. The reviews have stopped converging, so the remaining choice needs a person.

  • Head: c443091f59. Review rounds: 4.
  • All required checks pass on the current head, and every review thread is resolved. Codex reviewed this head and posted one finding, which I declined as non-blocking (tracked).
  • Rounds 1 to 3 fixed every valid in-scope finding. From round 4 on, only blockers were fixed. The remaining findings are P2 diagnostic or display edge cases, each with a reasoned reply on its thread.
  • Deferred fixes are tracked in 🤖 Prompt-cache measurement stack: deferred review follow-ups #6247.

Decision needed from a maintainer: merge this stack with the tracked follow-ups, or request another review round.

@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 12, 2026
Merged via the queue into main with commit a19ff3b Oct 12, 2026
59 of 62 checks passed
@ThomasK33
ThomasK33 deleted the tk/cache-prefix-repro-tests branch October 12, 2026 16:12
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Oct 13, 2026
)

## Summary

The next turn's request now keeps each step of the previous turn as its
own assistant message. Before, a step that opened with a tool call was
merged into the step before it, so two sequential tool calls replayed as
one parallel call. That changed the bytes inside the previous turn, and
the next turn wrote most of the conversation to the Anthropic prompt
cache again.

## Background

This is the first Phase 1 fix of the prompt-cache program (stack #6240
added the measurements). Inside a turn, each AI SDK step extends the
previous step's request. The next turn rebuilds the conversation from
`chat.jsonl`. StreamManager saves step boundaries as
`metadata.stepStartPartIndices` but no `step-start` parts, and nothing
in the request path read the indices. `convertToModelMessages` starts a
new assistant message only at a `step-start` part, or where text or
reasoning follows a tool part.

About 65% of assistant rows are multi-step. In the transcript study, a
turn after this pattern starts cold 29% of the time, against 10% without
it. The repro test from coder#6234 pinned the break at block 1.

## Implementation

- `insertStepStartPartsForSdk` (new, `src/node/utils/messages/`) adds
request-only `step-start` parts at the saved indices.
`messagePipeline.ts` calls it right before `convertToModelMessages`.
Nothing new is saved.
- It runs last because every earlier transform keeps assistant parts
one-to-one, so the saved indices still point at the right parts.
- It applies to every provider. Each provider's in-turn steps already
send this split, so the rebuild repeats a shape each provider accepted.
- Self-healing: rows without indices, and index lists that are not
strictly ascending non-negative integers, keep the old shape. Indices
past the row's parts are skipped.

## Validation

- The repro "a step that opens with a tool call keeps its own assistant
message" is now a plain test. With the `messagePipeline.ts` change
reverted, it fails at block 1.
- The other six repros in `promptCachePrefix.inTurnVsRebuild.test.ts`
still see their breaks at their pinned blocks.
- New pipeline tests cover Anthropic and OpenAI, rows without indices,
bad and out-of-range indices, steps that open with text or reasoning
(unchanged output), and parallel calls in one step (still one message).

## Risks

Medium-low. The change touches every provider request that replays a
multi-step turn.
- Two continuous-compaction tests asserted the old merged shape as a
precondition. They now use rows without indices, the case that still
merges. With the indices kept, all 59 tests in that file still pass.
- A step that holds only a provider-executed tool (such as Anthropic web
search) now becomes its own assistant message. In-turn steps already
sent this shape. No test covers it.
- `replay-verify` will report a difference for turns recorded before
this change. That is expected: replay matches only the same build.

---

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

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=75.69 -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Oct 15, 2026
…istory cached (coder#6687)

## 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** (coder#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 coder#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`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=398.12 -->
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