Repository navigation
test(agents): regression tests for orphaned tool-use stripping in validateAnthropicTurns - #49901
100yenadmin wants to merge 4 commits into
Conversation
Greptile SummaryThis PR fixes two related bugs in Key changes:
Confidence Score: 5/5
Last reviewed commit: "fix(agents): strip e..." |
Chenglin97
left a comment
There was a problem hiding this comment.
Review: fix(agents): strip end-of-conversation orphaned tool_use blocks and recognize multi-type tool calls
Both problems are real and the fixes are correct. The isToolCallBlock() helper is the right abstraction for handling type variations across core versions, and the end-of-conversation case was genuinely missing from the existing loop. The regression test for the normal case (matching tool_result preserved) is a good guard. A few things worth considering:
Why does the main loop not already catch the end-of-conversation case?
Looking at the loop structure: when the last message is assistant with no following user message, the loop pushes it to result unmodified. The new post-loop block then strips tool_use from it. This two-pass structure is correct but creates a subtle invariant: the end-of-conversation stripping runs after the main loop, on the already-transformed result, not on the original messages.
This should be fine for the current code, but the separation means a future maintainer might refactor the main loop without realizing the post-loop pass exists. A comment linking the two passes (e.g., // See also: end-of-conversation orphan handling below) would help.
isToolCallBlock in the existing loop filter changes behavior for toolCall/functionCall in mid-conversation
Previously, a mid-conversation toolCall or functionCall block (not toolUse) would have been kept by the block.type !== "toolUse" check even if it had no matching tool_result. Now isToolCallBlock() causes it to be stripped if unmatched. Is this the correct behavior for all three type variants in a mid-conversation context? The PR implies yes (they're all semantically equivalent), but it's worth explicitly confirming that toolCall/functionCall types are always expected to have a corresponding toolResult-typed result block. If functionCall results come back with a different type (e.g., functionResult), the valid-id matching would fail and the function call would be incorrectly stripped.
The fallback text "[tool calls omitted]"
When the last assistant has ONLY tool calls and they're all stripped, the fallback [tool calls omitted] is inserted. This placeholder will appear in the user-facing conversation and may be confusing if the user sees it. Consider whether this message should be: (a) a more descriptive [assistant response truncated], (b) marked as a hidden/system message if the message format supports it, or (c) not inserted at all if downstream code handles empty-content assistant messages gracefully.
Type-widening in AnthropicContentBlock
Adding "toolCall" | "functionCall" to the type union is correct and necessary. However, since this type is used for casting via as, TypeScript won't catch a case where pi-agent-core adds a fourth variant. A comment like "extend this union when pi-agent-core adds new tool-call block types" would prompt future maintainers to update isToolCallBlock in step.
Test: toolCall/functionCall mid-conversation test
The test for mid-conversation toolCall/functionCall stripping passes a user message with { type: "text", text: "Hello" } after the assistant, confirming the blocks are stripped when no matching result exists. Worth adding a companion test with { type: "functionResult", ... } to verify that the valid-id matching correctly handles the result type for functionCall blocks — or confirm that pi-agent-core always uses toolResult for all call types.
.gitnexus/ in .gitignore: Minor inclusion, no concerns.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 08443682c2
ℹ️ 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: d407815628
ℹ️ 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.
Pull request overview
Fixes Anthropic request failures caused by orphaned tool-call blocks by broadening tool-call type recognition and stripping dangling tool calls, including at the end of a conversation.
Changes:
- Add
isToolCallBlock()and extendAnthropicContentBlockto recognizetoolUse,toolCall, andfunctionCall. - Strip end-of-conversation orphaned tool-call blocks from the final assistant message (with fallback text when needed).
- Add test coverage for end-of-conversation orphan stripping and multi-type tool-call handling; update
.gitignoreto exclude.gitnexus/.
Reviewed changes
Copilot reviewed 2 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
src/agents/pi-embedded-helpers/turns.ts |
Expands tool-call type detection and strips dangling tool-call blocks, including trailing assistant orphans. |
src/agents/pi-embedded-helpers.validate-turns.test.ts |
Adds regression tests for orphan stripping and multi-type tool-call recognition. |
.gitignore |
Ignores local .gitnexus/ directory. |
Comments suppressed due to low confidence (1)
src/agents/pi-embedded-helpers/turns.ts:21
- The docstring says this function strips dangling "tool_use" blocks, but the implementation now also treats "toolCall" and "functionCall" blocks as tool calls (via isToolCallBlock). Please update the docstring wording to reflect the broader set of tool-call block types being stripped so the documentation matches behavior.
/**
* Strips dangling tool_use blocks from assistant messages when the immediately
* following user message does not contain a matching tool_result block.
* This fixes the "tool_use ids found without tool_result blocks" error from Anthropic.
*/
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a944da2e35
ℹ️ 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".
|
Review feedback addressed in commit Codex P1: OpenAI-compatible tool call stripping → Fixed. Codex P2: fallback text for aborted tool-only turns → Verified no synthetic assistant text is generated. Tightened with Copilot: test fixtures using Tests added:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8a0eb7eabf
ℹ️ 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: 37fbf311b6
ℹ️ 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: 3b4b376b28
ℹ️ 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".
|
@steipete @vincentkoc @jalehman followup deep dive openai hardening pass to bug test the merged PR's before rollout. |
|
Please don’t spam-ping multiple maintainers at once. Be patient, or join our community Discord for help: https://discord.gg/clawd |
|
Addressed the remaining review points in the latest push:
|
|
Related issues: This PR also relates to #33621 (Anthropic rejects history with dangling tool_use blocks after compaction), #41571 (stripDanglingAnthropicToolUses checks wrong type and empty assistant messages stored on LLM failure cause session corruption), #38370 (limitHistoryTurns breaks tool_use/tool_result pairs after sanitization), and #46319 (context pruning can split tool_use/tool_result pairs causing API validation errors). These share the same root cause of orphaned tool_use blocks and the stripDangling/validateAnthropicTurns code paths. |
|
Newly filed: #61815 tracks the O(n^2) scan-ahead performance issue in stripDanglingAnthropicToolUses that this PR's code path touches. |
…ecognize multi-type tool calls When the last message in a conversation is an assistant message with tool_use blocks, there is no following user message to validate against. The orphaned tool_use blocks survive, causing Anthropic to reject the next request with 'tool_use ids found without tool_result blocks'. Additionally, pi-agent-core stores content blocks with type 'toolCall' or 'functionCall' in some code paths, but the filter only checked for 'toolUse'. Changes: - Add isToolCallBlock() helper to recognize toolUse, toolCall, and functionCall - Update existing loop filter to use isToolCallBlock() instead of hardcoded check - After the main loop, strip tool_use blocks from the last assistant message when no following user message exists - Update AnthropicContentBlock type to include toolCall and functionCall variants - Add test cases for end-of-conversation orphans and multi-type recognition Fixes #48354
… docs, functionCall tests - Add linking comments between main loop and post-loop orphan handling - Document that all tool-call types (toolUse/toolCall/functionCall) map to toolResult - Add comment on AnthropicContentBlock type union for extensibility - Add test: functionCall mid-conversation with mixed matching/dangling tool calls - Add test: end-of-conversation functionCall block stripping - Keep [tool calls omitted] fallback text for consistency with main loop
- stripDanglingAnthropicToolUses now scans ALL subsequent messages for matching toolResult blocks (toolUseId or toolCallId), not just the immediate next message. Fixes OpenAI-compatible transcript ordering where user messages can appear between toolCall and toolResult. - Aborted/error assistant turns now skip the strip filter entirely (end-of-conversation handler still cleans up terminal orphans). - Added regression tests for cross-message tool result matching and unmatched stripping.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
src/agents/pi-embedded-helpers.validate-turns.test.ts:726
- The "does not crash when assistant content is non-array" test currently only asserts no-throw and length, but it doesn’t verify the PR’s stated behavior that legacy/non-array assistant content is preserved unchanged. Adding an assertion that the assistant message still has the original string content after validation would make this a meaningful regression test (and would catch the previously-reported data-loss bug if it reappears).
it("does not crash when assistant content is non-array", () => {
const msgs = [
{ role: "user", content: [{ type: "text", text: "Use tool" }] },
{
role: "assistant",
content: "legacy-content",
},
{ role: "user", content: [{ type: "text", text: "Thanks" }] },
] as unknown as AgentMessage[];
expect(() => validateAnthropicTurns(msgs)).not.toThrow();
const result = validateAnthropicTurns(msgs);
expect(result).toHaveLength(3);
});
|
Closing this as largely superseded. The behavior under test is already present on |
What this fixes (plain English)
This is a test-only PR that adds regression test coverage for edge cases in
validateAnthropicTurns, specifically around howstripDanglingAnthropicToolUses()handles orphaned tool calls. These tests document and lock down the existing stripping behavior to prevent future regressions.Technical details
Scope: Test-only — no production code changes. The implementation file
src/agents/pi-embedded-helpers/turns.tsis not modified.File changed:
src/agents/pi-embedded-helpers.validate-turns.test.ts— 6 regression tests covering:toolResultrole messages preserve matching callsStandalone value: These tests have standalone value for preventing regressions in the existing stripping logic, independent of any future scan-ahead implementation work.
Related
Test plan