Repository navigation
🤖 tests: pin prompt-cache prefix breaks across turns as repro tests - #6234
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
|
Stopping the review loop on this PR. The reviews have stopped converging, so the remaining choice needs a person.
Decision needed from a maintainer: merge this stack with the tracked follow-ups, or request another review round. |
) ## 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 -->
…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 -->
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.tsruns one real turn through the realStreamManager, the AI SDK Anthropic provider and Xum's wire cache-control wrapper, against a scripted local SSE fetch. It persists the turn to a realHistoryService, appends a monitor-style wake, rebuilds the next request the production way (assemblePromptPayload), and compares the wire bodies withcache_controlremoved.Each repro uses
expectReproFailureand pins the index of the first diverging message. A repro that breaks for another reason fails instead of passing.__mux_notificationsis sent in-turn, then stripped before persistingtoModelOutputconvertToModelMessages)providerOutputSanitization.ts)task_awaitpollsis_errorresult, rebuilt as a normal JSON resultattach_filemediaValidation
Follow-ups
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