Skip to content

test(agents): regression tests for orphaned tool-use stripping in validateAnthropicTurns - #49901

Closed
100yenadmin wants to merge 4 commits into
openclaw:mainfrom
electricsheephq:fix/strip-dangling-tool-use-end-of-conversation
Closed

100yenadmin wants to merge 4 commits into
openclaw:mainfrom
electricsheephq:fix/strip-dangling-tool-use-end-of-conversation

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes (plain English)

This is a test-only PR that adds regression test coverage for edge cases in validateAnthropicTurns, specifically around how stripDanglingAnthropicToolUses() 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.ts is not modified.

File changed:

  • src/agents/pi-embedded-helpers.validate-turns.test.ts — 6 regression tests covering:
    • Tool call with a later (non-adjacent) tool result survives stripping
    • Tool call with no matching result is correctly stripped
    • Standalone toolResult role messages preserve matching calls
    • Scan-ahead stops at the next assistant turn boundary
    • Aborted mid-transcript tool-only turns are handled correctly
    • Legacy string assistant content passes through unchanged

Standalone 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

  • 33/33 tests pass
  • All 6 new regression cases validate existing behavior
  • No production code changes — zero behavioral risk

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Mar 18, 2026
@greptile-apps

greptile-apps Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two related bugs in stripDanglingAnthropicToolUses: it adds an isToolCallBlock() helper to recognise toolCall and functionCall content-block variants (not just toolUse), and adds a post-loop pass that strips orphaned tool-use blocks from a trailing assistant message that has no following user message with matching tool_result blocks.

Key changes:

  • isToolCallBlock() helper replaces the hardcoded !== "toolUse" check throughout the filter logic
  • New end-of-conversation pass operates on the already-built result array, correctly avoiding double-processing of messages handled by the main loop
  • Fallback [tool calls omitted] text block is inserted when stripping would leave an empty content array — consistent with the existing behaviour in the main loop
  • Four new test cases cover the two new code paths plus a no-regression case for a well-formed tool-use/tool-result pair

Confidence Score: 5/5

  • Safe to merge — narrowly scoped bug fixes with thorough test coverage and no regressions.
  • The changes are minimal and well-contained: a new private helper function, a one-line filter update, and a clearly delimited post-loop block. All four new test cases pass, and the existing 23 tests continue to pass. The logic correctly avoids double-processing (the main loop hands off last-message handling to the new post-loop block), the fallback text insertion mirrors existing behaviour, and the isToolCallBlock helper correctly returns false for undefined types.
  • No files require special attention.

Last reviewed commit: "fix(agents): strip e..."

@Chenglin97 Chenglin97 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.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 extend AnthropicContentBlock to recognize toolUse, toolCall, and functionCall.
  • 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 .gitignore to 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.
 */

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Review feedback addressed in commit d47c5d93b4:

Codex P1: OpenAI-compatible tool call stripping → Fixed. validateAnthropicTurns() now accepts both toolUseId and toolCallId when matching tool results, and recognizes toolUse, toolCall, and functionCall blocks consistently. OpenAI-style pairings are no longer incorrectly stripped.

Codex P2: fallback text for aborted tool-only turns → Verified no synthetic assistant text is generated. Tightened with isAbortedAssistantTurn() extraction and added regression test for aborted terminal tool-only turns to ensure no fallback tool result gets synthesized.

Copilot: test fixtures using input vs arguments → Fixed. Updated malformed-fixture test to use toolUse with input (Anthropic-native shape) instead of mixing formats.

Tests added:

  • OpenAI-compatible toolCall + toolCallId pairing survives sanitization
  • Aborted terminal tool-only turn does not synthesize fallback tool result

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 3 changed files in this pull request and generated 1 comment.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 3 changed files in this pull request and generated 3 comments.

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

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: 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".

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
@100yenadmin 100yenadmin changed the title fix(agents): strip end-of-conversation orphaned tool_use blocks and recognize multi-type tool calls fix(agents): scan-ahead tool result matching — fix Anthropic turn validation for OpenAI-compatible tool_use/tool_result pairs Apr 5, 2026
@100yenadmin

100yenadmin commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@steipete @vincentkoc @jalehman followup deep dive openai hardening pass to bug test the merged PR's before rollout.

@openclaw-barnacle

Copy link
Copy Markdown

Please don’t spam-ping multiple maintainers at once. Be patient, or join our community Discord for help: https://discord.gg/clawd

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Addressed the remaining review points in the latest push:

  • tool/toolResult scan-ahead now matches toolCallId / toolUseId and snake_case variants
  • scan-ahead stops at the next assistant boundary
  • aborted/error turns are filtered for dangling calls but keep empty content instead of synthetic fallback text
  • legacy non-array assistant content is preserved unchanged
  • comments/docstring updated to match the actual behavior
  • test fixtures now use arguments, and the PR description now reflects 6 added tests
  • O(n²): Acknowledged. For typical transcript lengths (<200 messages) this is fine. Added a TODO for optimization.
  • [tool calls omitted] concern: Fixed — aborted turns now get empty content instead of synthetic text.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

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.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Newly filed: #61815 tracks the O(n^2) scan-ahead performance issue in stripDanglingAnthropicToolUses that this PR's code path touches.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

…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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);
  });

@100yenadmin 100yenadmin changed the title fix(agents): scan-ahead tool result matching — fix Anthropic turn validation for OpenAI-compatible tool_use/tool_result pairs test(agents): regression tests for orphaned tool-use stripping in validateAnthropicTurns Apr 6, 2026
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Closing this as largely superseded. The behavior under test is already present on main: tool-call detection/stripping, forward scan to matching results, legacy tool-result matching, and snake_case/camelCase ID handling. If we still want extra value here, it should come back as a tiny tests-only follow-up focused only on the remaining unique terminal/end-of-conversation regression coverage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants