Skip to content

🤖 fix: replay each model response as one message, judged by a provider-request oracle - #8256

Open
ThomasK33 wants to merge 2 commits into
mainfrom
oracles/provider-transform
Open

ThomasK33 wants to merge 2 commits into
mainfrom
oracles/provider-transform

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Why

The next turn's rebuild split one model response at every thinking block or text that sat between its tool calls: [P1, call A, P2, call B] went back as two assistant messages with a tool result between them, so two parallel calls replayed as two sequential ones. The request stopped repeating the bytes the turn sent (prompt-cache miss), and on prefix-bound Claude models block P2 lost its signed prefix. This hit 28 of the 49 response shapes the Anthropic docs describe (31 with adaptive thinking).

This PR adds an oracle for the stage between conversion and cache control (sanitizeAssistantModelMessages + transformModelMessages). It sends the stage's output through the real @ai-sdk/anthropic and @ai-sdk/openai with a fake fetch and judges the request body. On the unchanged code, 327 of its 1045 tests failed.

What changed

  • tests/oracles/modelMessageTransform.oracle.ts: seven laws (no throw; tool calls answered in place; no empty block; user text stays; thinking goes back unchanged; one response, one message; input stays as given). Its two owned files are added to ORACLE_SOURCES.
  • One response stays one message: splitMixedContentMessages is gone. Rows persisted without step boundaries still split where a step must have ended (legacyStepStarts in insertStepStartPartsForSdk).
  • Thinking replay is one option, anthropicThinking: "off" | "strip" | "manual" | "adaptive", resolved in messagePipeline.ts. Only manual thinking moves thinking to the front, and only in the open turn's first message. The "..." placeholder is gone: the SDK dropped it anyway.
  • One first pass, keepSendableParts, keeps the parts a request can carry and drops every message left empty. Calls and results pair by position: a result outside the tool message right after its call leaves the request, and so does its call. Before this change, the AI SDK threw MissingToolResultsError. The reasoning a provider replays is a predicate of this pass (stripUnsignedAnthropicReasoning is gone).
  • An empty user message leaves the request. A persisted user row with no text or file part converts to one (ai convert-to-model-messages.ts), and before this change Anthropic got a message with no content.
  • Streamed parts now coalesce in sanitizeAssistantModelMessages, before whitespace-only text is dropped (sanitize no longer drops messages; the first pass does), so a dropped text can no longer join two thinking blocks under one signature. A part with another OpenAI itemId opens a new item. No pass edits its input anymore.
  • task_await coalescing is rewritten: a no-progress poll pair leaves when the next pair is the same poll.
  • Comments that said Anthropic requires alternating roles now say that it combines consecutive turns (the merges stay).

Scope

Anthropic and OpenAI only. The other providers' reasoning handling is a stated limit, and the oracle does not generate provider-executed tools.

Tradeoffs

  • 66 mutation gaps remain (down from 187). 46 are in task_await coalescing and 14 in the assistant-text merge; each of those two areas needs a law the approved spec does not hold. The other 6 are stated limits: provider-executed results inside an assistant message (4) and the unknown-provider replay (2). The list is in a comment below.
  • stripAnthropicReasoning now runs only within a turn (StepPreparation.ts), so the oracle no longer owns it.

Blast Radius

The request bytes change for a history that has any of these: a step with thinking or text between its calls, a misplaced tool result, an empty user message, a no-progress poll whose message also held reasoning the provider does not replay (it now coalesces), or (with manual thinking) a finished turn whose first message started with text. Each affected chat gets one prompt-cache miss on its first request after the upgrade. Persisted history does not change, so a downgrade is safe.

Verification

  • make test-oracles: 1330 tests pass (gap report below). The documented shapes T? X? (T? C){1,3} run under every config, OpenAI with store: false (ZDR) among them.
  • Live request: INCONCLUSIVE. The gateway answered 200, but in 24 attempts on Opus and Sonnet 5.5 the model never produced a [thinking, tool_use, thinking, tool_use] step to replay.
External rules the stage encodes, tagged

Docs fetched 2026-12-05. D1 Messages API, D2 handle-tool-calls, D3 extended-thinking, D4 thinking, D5 OpenAI function-calling.

Rule Tag
An assistant message with no content is rejected observed (tests/ipc/streaming/emptyAssistantMessage.test.ts, commit ecc2e22)
An empty text block is rejected documented (D1, TextBlockParam.text minLength 1)
A whitespace-only text block is rejected observed (commit eaada41)
tool_result comes right after its tool_use, results first documented (D2)
Consecutive same-role turns are combined documented (D1); the SDK groups them too (observed)
Thinking needs its signature; redacted data goes back unchanged documented (D1)
The SDK drops reasoning without a signature observed (SDK source, probe)
The signature arrives on a block's last streamed part documented (D4)
OpenAI item ID and encrypted content sit on a run's first part assumed
Only manual mode needs the final turn to start with thinking documented (D3, D4)
Thinking blocks keep their order and text documented (D1, D4)
Anthropic and OpenAI reject a reasoning-only assistant message assumed
A function call needs its output documented (D5); the SDK refuses it before sending (observed)
Reasoning returned with tool calls goes back with them documented (D5)
Other providers need no reasoning handling assumed (limit)
Tool call IDs are unique assumed (limit)

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: xhigh • Cost: $33.59

…r-request oracle

Add tests/oracles/modelMessageTransform.oracle.ts: it sends the output of
sanitizeAssistantModelMessages + transformModelMessages through the real
@ai-sdk/anthropic and @ai-sdk/openai (fake fetch) and judges the request
body against seven approved laws. On the unchanged code 327 of 1045 tests
failed.

Fixes, oracle first:
- One response stays one message: splitMixedContentMessages is gone; rows
  without step boundaries split in insertStepStartPartsForSdk.
- Thinking replay is one option (off, strip, manual, adaptive); only manual
  thinking moves the open turn's first message's thinking to its front, and
  the "..." placeholder is gone.
- Tool calls and results pair by position; a misplaced pair leaves.
- Streamed parts coalesce in sanitize before whitespace text is dropped; an
  OpenAI part with another itemId opens a new item; no pass edits its input.
- task_await coalescing keeps each run's last no-progress pair.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-05T19:05:23.660432Z 8a1e852 Manual request
🔒 Security Review ✅ Completed 2026-12-05T19:08:22.981134Z 8a1e852 Manual request
ℹ️ 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.

@ThomasK33

ThomasK33 commented Dec 5, 2026 •

Copy link
Copy Markdown
Member Author

Oracle evidence

Round 2 (head 8a1e852): 66 gaps

The oracle now also drives OpenAI with store: false (ZDR), an empty user message, and a tool message before the first prompt: 1330 tests, all passing. Run against the previous head (18674d6), 2 of them failed: no empty block, "an empty user row between two steps" (Anthropic got a message with no content). The ZDR config showed no red.

Area Gaps Reason
task_await no-progress coalescing 46 Not judged: needs the poll-coalescing law (below).
Assistant-text merge, with its provider switch 14 Not visible on the wire: needs the merge law (below).
Provider-executed results inside an assistant message (sendablePartsOf) 4 Stated limit: the grammar builds no provider-executed tool.
Unknown-provider replay (OTHER_REASONING_REPLAY) 2 Stated limit (P-DQ4).

Closed in this round: the 2 OpenAI itemId gaps (the ZDR wire carries each item's summary and encrypted content) and the 8 "inputs the grammar does not build":

  • empty user message (merge ?. x2, the role guards in filterReasoningOnlyMessages and stripUnsignedAnthropicReasoning): the grammar now builds one (ai convert-to-model-messages.ts:146-163 makes one from a user row with no text or file part). The new first pass, keepSendableParts, drops every empty message; then the guards were redundant (deleted), and stripUnsignedAnthropicReasoning became a reasoning predicate of that pass.
  • empty message list and a first message that is an assistant (openTurnStart): rewritten as one scan with no index arithmetic or optional reads. It relies on every tool message following the assistant whose calls it answers, which the first pass ensures. Xum has no tool approvals, and convert-to-model-messages.ts:325-337,432-436 emits each tool message right after its assistant message.
  • a first message that is a tool message (toolPartIds ?.): the grammar now builds one.
  • an assistant message left empty by sanitize: sanitize no longer drops messages, because the first pass drops every empty one.

Round 1 below.

RED on the unchanged code (base 676c698)

327 of 1045 oracle tests failed. Failed tests by law:

Law Failed Counterexample class
one response, one message 305 the rebuild splits a step at a thinking block or text after a call. This fails 28 of the 49 documented shapes under each Anthropic config and 31 of 49 under adaptive and OpenAI (292 tests over fixed and random seeds), plus 13 generated and constructed histories
input stays as given 7 coalescing appended deltas into the caller's parts
thinking goes back unchanged 4 a dropped whitespace text joined an unsigned run to the next signed block
tool calls answered in place 4 a result in a later tool message kept its call
no throw 3 that same call made the AI SDK throw MissingToolResultsError
no empty block 2 an empty or whitespace text block reached the wire
user text stays 2 (the same histories: the stage threw first)

Gaps: 74 remain (187 at the first green run)

Run make test-oracles ORACLE_SOURCES=src/browser/utils/messages/modelMessageTransform.ts,src/node/services/messagePipeline.ts: 598 mutants, 277 killed, 0 crashed, 74 gaps.

Area Gaps Reason
task_await no-progress coalescing (isNoProgressTaskAwaitOutput, noProgressPollAt, coalesceConsecutiveNoProgressTaskAwaitPairs) 46 Not judged. The approved laws let any no-progress poll pair leave as a whole pair (a limit), so keeping too many pairs breaks no law. Potential law: for every run of identical no-progress polls, the request keeps exactly the run's last pair (authority: the function's doc).
Assistant-text merge (mergeConsecutiveAssistantTextMessages, isTextOnlyAssistantContent, its provider switch) 14 Not judged on the wire: the Anthropic SDK groups consecutive assistant messages into one, and OpenAI sends one item per text part, so merged and unmerged outputs send the same request. Potential law: with Anthropic, the stage's output has no text-only assistant message right after an assistant message without a tool call (authority: decision P-DQ6 B, "the merges stay").
OpenAI item coalescing (continuesReasoningBlock, itemId) 2 With the SDK's default store, reasoning goes out as item_reference by ID, so a split or merged run sends the same request. A ZDR config (store: false) would make them visible.
Inputs the grammar does not build 8 An empty user message (2 in mergeConsecutiveUserMessages; 2 role guards in filterReasoningOnlyMessages and stripUnsignedAnthropicReasoning, which are otherwise JSON-equal), an empty message list (openTurnStart ?.), a first message that is an assistant or tool message (openTurnStart >=, toolPartIds ?.), and an empty assistant message that survives sanitize (sanitizeAssistantModelMessages >=; every known provider's pass drops it later).
Stated limits 4 Provider-executed results inside an assistant message (3 in stripOrphanedToolCalls). The unknown-provider branch of transformModelMessages (P-DQ4 limit).

The 247 unowned mutants sit outside the stage: injectAgentTransition, prepareMessagesForProvider, validateAnthropicCompliance, injectPostCompactionAttachments, filterEmptyAssistantMessages, anthropicThinkingReplay (the level-to-mode mapping) and addInterruptedSentinel.

Live request

INCONCLUSIVE. The direct key got a 401; the gateway answered 200. In 24 attempts on Opus and Sonnet 5.5, the model never produced a [thinking, tool_use, thinking, tool_use] step, so the shape could not be replayed live. About 10.5k input and 1.3k output tokens.

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 18674d671a

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

@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

🟢 e2e stories (Haiku): 14 passed

21 agent steps · 5 replayed from cache · 18 model calls · 77.1k tokens (37% cached)
Spend: $0.10 of the $1.00 cap (proxy ledger)

All 14 tests in 9 files
Test Agent Time
🟢 chatRestart.e2e.ts · 1 passed 1 step · 1 call 5.9s
🟢 a chat survives a restart of the server 1 step · 1 call 5.9s
🟢 compaction.e2e.ts · 1 passed 1 step · 1 call 4.8s
🟢 /compact replaces the old chat with a summary 1 step · 1 call 4.8s
🟢 pluginTrustRestart.e2e.ts · 1 passed 3 steps · 2 calls 9.6s
🟢 a trusted plugin hook stays trusted after the server restarts 3 steps · 2 calls 9.6s
🟢 settingsRoundTrip.e2e.ts · 1 passed 2 steps · 1 call 8.9s
🟢 a chat survives trips through Settings 2 steps · 1 call 8.9s
🟢 sidebarPerWorkspace.e2e.ts · 1 passed 4 steps · 1 call 4.4s
🟢 a new workspace starts with its right sidebar collapsed while another keeps it open 4 steps · 1 call 4.4s
🟢 smoke.e2e.ts · 1 passed 2 steps · 4 calls 5.7s
🟢 the agent opens the playground workspace 2 steps · 4 calls 5.7s
🟢 streamErrors.e2e.ts · 1 passed 1 step · 1 call 7.1s
🟢 stream errors show in the chat, and the chat recovers 1 step · 1 call 7.1s
🟢 todoNudge.e2e.ts · 1 passed 1 step · 1 call 3.1s
🟢 the agent finishes open TODO items after the turn-end nudge 1 step · 1 call 3.1s
🟢 touchAlignment.e2e.ts · 6 passed 6 steps · 6 calls 23.0s
🟢 the Settings close button is level with the title on a touch screen 390px wide 1 step · 1 call 3.7s
🟢 the Settings close button is level with the title on a touch screen 768px wide 1 step · 1 call 3.9s
🟢 Backup settings checkboxes are small and level with their labels on a touch phone 1 step · 1 call 4.5s
🟢 the heartbeat checkbox is small and level with its label on a touch phone 1 step · 1 call 3.4s
🟢 a reply's model and time stay on one line on a touch phone 1 step · 1 call 4.4s
🟢 the workspace actions menu stays on the title row on a touch phone 1 step · 1 call 3.0s

e2e 0.20.0 · 1m 16s · web · run artifacts

🟢 e2e Electron stories (Haiku): 3 passed

3 agent steps · 3 model calls · 7.9k tokens (22% cached)
Spend: $0.02 of the $1.00 cap (proxy ledger)

All 3 tests in 3 files
Test Agent Time
🟢 electron/deepLink.e2e.ts · 1 passed 1 step · 1 call 5.5s
🟢 a deep link of a second launch starts a chat in the running app 1 step · 1 call 5.5s
🟢 electron/menuBar.e2e.ts · 1 passed 1 step · 1 call 7.6s
🟢 the workspace menu bar is the desktop title bar 1 step · 1 call 7.6s
🟢 electron/smoke.e2e.ts · 1 passed 1 step · 1 call 5.4s
🟢 Xum Electron opens the playground workspace 1 step · 1 call 5.4s

e2e 0.20.0 · 21.0s · electron · run artifacts

🟢 e2e agent repros (Haiku): no tests selected

Spend: $0.00 of the $1.00 cap (proxy ledger)

e2e 0.20.0 · 6.3s · 2 targets (web, phone) · run artifacts

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 18674d671a

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

The oracle gains a config and two corrupt histories:
- OpenAI with store: false (ZDR) sends reasoning items with their
  encrypted content and summary, so item coalescing shows on the wire.
- An empty user message (a persisted user row with no text or file part
  converts to one). On the previous head it reached Anthropic as a
  message with no content: 2 of 1330 tests failed (no empty block).
- A tool message before the first prompt.

One first pass, keepSendableParts, now keeps the parts a request can
carry (answered calls, the reasoning the provider replays) and drops
every message left empty, of any role. That removes the branches whose
mutants no history could tell apart: the role guards in
filterReasoningOnlyMessages and stripUnsignedAnthropicReasoning (gone),
the empty-content reads in the user merge and openTurnStart, and the
empty-message drop in sanitize.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 8a1e8528c1

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

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 8a1e8528c1

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

This branch has not been deployed

No deployments
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