Repository navigation
fix(repair): strip tool_use blocks from error/aborted messages instead of skipping - #48888
mike2024-dev wants to merge 2 commits into
Conversation
Greptile SummaryThis PR changes However there are several bugs introduced that would cause the test suite to fail and could break callers at runtime:
Confidence Score: 2/5
|
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse", | ||
| ); | ||
| const strippedIds = errorToolCalls.map((t) => t.id); | ||
| added.push(...strippedIds.map((id) => `stripped-error-${id}`)); |
There was a problem hiding this comment.
Type-incorrect values pushed into
added array
added is declared as Array<Extract<AgentMessage, { role: "toolResult" }>> but this line pushes plain strings ("stripped-error-<id>") into it, breaking the return type contract of ToolUseRepairReport. Any downstream caller that iterates result.added and accesses properties like .toolCallId, .content, or .role will get undefined (or throw) at runtime.
Additionally, the existing test at line 265 (expect(result.added).toHaveLength(0)) will now fail, because one string is pushed into added for each stripped tool call.
The added field semantics are "synthetic toolResult messages that were inserted". Stripped-but-not-replaced entries don't belong here. The tracking should be done separately (e.g. a new strippedErrorToolCallIds field on the report, or simply omit the tracking and rely on changed === true).
| added.push(...strippedIds.map((id) => `stripped-error-${id}`)); | |
| changed = true; |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/session-transcript-repair.ts
Line: 410
Comment:
**Type-incorrect values pushed into `added` array**
`added` is declared as `Array<Extract<AgentMessage, { role: "toolResult" }>>` but this line pushes plain strings (`"stripped-error-<id>"`) into it, breaking the return type contract of `ToolUseRepairReport`. Any downstream caller that iterates `result.added` and accesses properties like `.toolCallId`, `.content`, or `.role` will get `undefined` (or throw) at runtime.
Additionally, the existing test at line 265 (`expect(result.added).toHaveLength(0)`) will now fail, because one string is pushed into `added` for each stripped tool call.
The `added` field semantics are "synthetic `toolResult` messages that were inserted". Stripped-but-not-replaced entries don't belong here. The tracking should be done separately (e.g. a new `strippedErrorToolCallIds` field on the report, or simply omit the tracking and rely on `changed === true`).
```suggestion
changed = true;
```
How can I resolve this? If you propose a fix, please make it concise.| expect(result.messages[1]?.role).toBe("user"); | ||
| expect(result.messages).toHaveLength(2); | ||
| expect(result.changed).toBe(true); |
There was a problem hiding this comment.
result.changed does not exist on ToolUseRepairReport
ToolUseRepairReport (defined at line 334–340 of session-transcript-repair.ts) has no changed property — only messages, added, droppedDuplicateCount, droppedOrphanCount, and moved. The internal changed variable is never included in the returned object.
As a result result.changed evaluates to undefined, so this assertion will always fail:
expect(result.changed).toBe(true)
// TypeError-equivalent: undefined !== true
The same problem applies at line 193 (expect(result.changed).toBe(true) in the "aborted" test).
To make these assertions meaningful, either:
- Add
changed: booleantoToolUseRepairReportand return it, or - Replace these assertions with the existing
movedfield, which is set tochangedOrMoved(which includeschanged), or - Assert indirectly: e.g. verify the returned
messagesarray is a different reference than the input.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/session-transcript-repair.test.ts
Line: 170
Comment:
**`result.changed` does not exist on `ToolUseRepairReport`**
`ToolUseRepairReport` (defined at line 334–340 of `session-transcript-repair.ts`) has no `changed` property — only `messages`, `added`, `droppedDuplicateCount`, `droppedOrphanCount`, and `moved`. The internal `changed` variable is never included in the returned object.
As a result `result.changed` evaluates to `undefined`, so this assertion will always fail:
```
expect(result.changed).toBe(true)
// TypeError-equivalent: undefined !== true
```
The same problem applies at line 193 (`expect(result.changed).toBe(true)` in the "aborted" test).
To make these assertions meaningful, either:
1. Add `changed: boolean` to `ToolUseRepairReport` and return it, or
2. Replace these assertions with the existing `moved` field, which is set to `changedOrMoved` (which includes `changed`), or
3. Assert indirectly: e.g. verify the returned `messages` array is a different reference than the input.
How can I resolve this? If you propose a fix, please make it concise.| const stripped = content.filter( | ||
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse", | ||
| ); |
There was a problem hiding this comment.
functionCall blocks not stripped
The filter only excludes "toolCall" and "toolUse", but extractToolCallsFromAssistant (and isRawToolCallBlock) also recognises "functionCall" blocks as tool-call blocks. If a message's orphaned block has type: "functionCall", errorToolCalls.length > 0 will be true, but the filter will leave that block in stripped, so it won't be removed.
| const stripped = content.filter( | |
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse", | |
| ); | |
| const stripped = content.filter( | |
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse" && b.type !== "functionCall", | |
| ); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/session-transcript-repair.ts
Line: 406-408
Comment:
**`functionCall` blocks not stripped**
The filter only excludes `"toolCall"` and `"toolUse"`, but `extractToolCallsFromAssistant` (and `isRawToolCallBlock`) also recognises `"functionCall"` blocks as tool-call blocks. If a message's orphaned block has `type: "functionCall"`, `errorToolCalls.length > 0` will be `true`, but the filter will leave that block in `stripped`, so it won't be removed.
```suggestion
const stripped = content.filter(
(b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse" && b.type !== "functionCall",
);
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7928e015c9
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const stripped = content.filter( | ||
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse", | ||
| ); |
There was a problem hiding this comment.
Strip functionCall blocks in errored assistant turns
This filter only removes toolCall/toolUse, but extractToolCallsFromAssistant also treats functionCall blocks as tool calls. If an errored/aborted assistant turn contains a functionCall (which can occur in OpenAI-style transcripts), the orphaned call is left in content with no matching tool result, so the transcript can still fail strict provider validation on the next request. Include functionCall in the stripped block types here.
Useful? React with 👍 / 👎.
| const strippedIds = errorToolCalls.map((t) => t.id); | ||
| added.push(...strippedIds.map((id) => `stripped-error-${id}`)); |
There was a problem hiding this comment.
Do not record stripped IDs as synthetic tool results
ToolUseRepairReport.added is supposed to contain inserted toolResult messages, but this branch appends string sentinels like stripped-error-... even though no tool result was created. Consumers that rely on added as inserted message objects (or as a count of synthetic tool results) will get incorrect data for error/aborted repairs. Track stripped IDs separately instead of pushing them into added.
Useful? React with 👍 / 👎.
5c306e8 to
111fd04
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 111fd04ab6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const errorToolCalls = extractToolCallsFromAssistant(assistant); | ||
| if (errorToolCalls.length > 0) { |
There was a problem hiding this comment.
Strip partial error-turn tool blocks even when the id is missing
This branch only strips an errored/aborted assistant turn when extractToolCallsFromAssistant() finds at least one call, but that helper ignores toolCall/toolUse blocks without a non-empty id (src/agents/tool-call-id.ts:44-62). In the partial streamed turns this fix is targeting, the block is often missing id/name, so out.push(msg) preserves the malformed tool block unchanged. The post-truncation repair paths rerun sanitizeToolUseResultPairing without another sanitizeToolCallInputs pass (src/agents/pi-embedded-runner/run/attempt.ts:2152-2156, src/agents/pi-embedded-runner/compact.ts:873-877), so those corrupted sessions still go back to strict providers with the invalid tool block and keep failing.
Useful? React with 👍 / 👎.
f60d715 to
6570cae
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6570caedeb
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (stopReason === "error" || stopReason === "aborted") { | ||
| const errorToolCalls = extractToolCallsFromAssistant(assistant); | ||
| if (errorToolCalls.length > 0) { | ||
| const content = Array.isArray(assistant.content) ? assistant.content : []; | ||
| const stripped = content.filter( |
There was a problem hiding this comment.
Honor preserveErroredAssistantResults before stripping error turns
This early branch now strips every errored/aborted assistant turn that still has a valid tool call, so the later preserveErroredAssistantResults path in repairToolUseResultPairing() is unreachable. That regresses the replay-sanitization flow in src/agents/pi-embedded-runner/run/attempt.ts:1006-1014, which explicitly passes preserveErroredAssistantResults: true, and it breaks the existing scenario covered by src/agents/pi-embedded-runner/run/attempt.test.ts:1137-1188: after malformed siblings are removed, the surviving tool call and its real toolResult are both discarded instead of being kept for the retry context.
Useful? React with 👍 / 👎.
| const stripped = content.filter( | ||
| (b: { type?: string }) => b && b.type !== "toolCall" && b.type !== "toolUse", | ||
| ); | ||
| changed = true; | ||
| out.push({ |
There was a problem hiding this comment.
Re-drop Anthropic user tool_results after stripping toolUse
When this branch runs on Anthropic-style history, it removes the assistant toolUse blocks but leaves any matching user toolResult content untouched, because repairToolUseResultPairing() only drops role=toolResult messages. In the truncation paths (src/agents/pi-embedded-runner/run/attempt.ts:2387-2399 and src/agents/pi-embedded-runner/compact.ts:861-879) we call this after validateAnthropicTurns() and do not rerun sanitizeAnthropicReplayToolResults(), so an errored turn that previously had a valid toolUse/toolResult pair is turned back into an invalid Anthropic transcript.
Useful? React with 👍 / 👎.
26b4d6e to
8c25ba3
Compare
…penclaw#48354) Instead of passing orphaned tool_use/toolCall/functionCall blocks through unchanged in error/aborted assistant messages (causing permanent session corruption), strip them entirely. Also adds 'changed' field to ToolUseRepairReport. Co-Authored-By: Claude Opus 4.6 <[email protected]>
🔧 Suggested fix (rebased + 4 bugs addressed)We reviewed this PR and the core approach is correct. Here is a clean rebased version on current What was fixed
How to apply# From your fork, on the PR branch:
git fetch upstream main
git checkout fix/repair-tool-use-error-aborted
git reset --hard upstream/main
git apply <(curl -sL <patch-url>) # or apply the patch below manuallyOr you can cherry-pick the commit from this patch: Full patch (apply with
|
8c25ba3 to
063b2df
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 063b2dfd93
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| _options?: ToolUseResultPairingOptions, | ||
| ): ToolUseRepairReport { |
There was a problem hiding this comment.
Honor errored-assistant result policy during repair
The erroredAssistantResultPolicy option is now effectively ignored, because the function signature changed to _options and the branch for stopReason === "error" || "aborted" always strips tool-call blocks and never preserves matching toolResult entries. This regresses callers that rely on preserve semantics during replay sanitization, so valid tool context can be dropped from retry requests even when the caller explicitly wants to keep it. Fresh evidence: this commit removed shouldDropErroredAssistantResults(...) usage and no option checks remain in the errored-turn path.
Useful? React with 👍 / 👎.
…blocks Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 414278a358
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
| } | ||
| } | ||
| i = j - 1; |
There was a problem hiding this comment.
Keep intervening turns when preserving errored results
In the erroredAssistantResultPolicy: "preserve" path, the scan consumes messages until the next assistant turn and then advances i, but only matching toolResult entries are pushed to out; user/system/other turns in that span are never re-emitted. If any other repair in the same transcript sets changed = true, the function returns out and those consumed turns are silently dropped, corrupting session history.
Useful? React with 👍 / 👎.
|
Closing this as implemented after Codex automated review. Current main already fixes the observable replay failure this PR targets: dangling assistant tool-call blocks are stripped or dropped in the centralized replay hygiene path before strict provider submission, with regression coverage for Anthropic-style tool_use/tool_result cases. The PR branch is no longer the right vehicle and still carries unresolved review risk plus unrelated churn. Best possible solution: Close this PR as obsolete and keep the shipped centralized transcript hygiene implementation. Any future change to What I checked:
So I’m closing this as already implemented rather than keeping a duplicate issue open. Codex Review notes: model gpt-5.5, reasoning high; reviewed against 54f8e4145e43; fix evidence: release v2026.4.24, commit cbcfdf62c729. |
fix: strip tool_use blocks from error/aborted assistant messages in repairToolUseResultPairing
Problem
repairToolUseResultPairing()currently skips assistant messages withstopReason === "error" || "aborted":These are exactly the messages most likely to contain orphaned
tool_useblocks — the tool call started but the result was never generated due to the error/abort. By skipping them entirely, the function preserves the orphaned blocks, which then cause Anthropic API rejections on every subsequent request.Fix
Instead of skipping error/aborted messages, extract any
tool_use/toolCallblocks from them. If found, strip the tool call blocks and preserve any remaining text content. If the message becomes empty after stripping, insert a placeholder[tool calls from errored turn stripped].Testing
Verified locally against sessions with known orphaned tool_use blocks from:
After applying this fix + #46866 (type mismatch fix), previously corrupted sessions recover automatically on next interaction instead of entering infinite retry loops.
Related Issues
stripDanglingAnthropicToolUsestype mismatch fix (prerequisite)