Skip to content

fix(worker): prevent orphaned tool_results and fix parallel merging - #1069

Merged
zmanian merged 2 commits into
stagingfrom
fix/635-orphaned-tool-results
Mar 16, 2026
Merged

zmanian merged 2 commits into
stagingfrom
fix/635-orphaned-tool-results

Conversation

@zmanian

@zmanian zmanian commented Mar 12, 2026

Copy link
Copy Markdown
Collaborator

Summary

Clean reimplementation of the core fixes from #635, scoped to only the two bugs identified in the PR title. The Telegram, scheduler, state machine, and empty-response changes from #635 are excluded per maintainer feedback about PR scope.

  • Reasoning text preserved: JobDelegate::call_llm() now extracts the reasoning text from select_tools() results and passes it as content in RespondResult::ToolCalls. This ensures the assistant_with_tool_calls message includes the LLM's reasoning, preventing context loss on subsequent turns.

  • Parallel tool results merged: rig_adapter::convert_messages() now merges consecutive Role::Tool messages into a single RigMessage::User with multiple ToolResult content items. Without this, parallel tool execution produced consecutive User messages that Anthropic's API rejects.

Addresses review feedback from #635:

  • Regression tests included for both bug fixes
  • Minimal, focused scope (2 files changed)
  • No .unwrap() or .expect() in production code
  • Zero clippy warnings

Supersedes #635 (core bug fixes only).

Test plan

  • cargo check passes
  • cargo test --lib worker -- all 47 tests pass including new regression tests
  • cargo test --lib rig_adapter -- all 29 tests pass including new regression tests
  • cargo clippy --all --tests -- zero warnings
  • Manual verification with Anthropic API that parallel tool calls no longer produce empty responses

Generated with Claude Code

@github-actions github-actions Bot added scope: llm LLM integration scope: worker Container worker size: M 50-199 changed lines labels Mar 12, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the handling of LLM tool interactions by addressing two critical bugs. It ensures that the LLM's reasoning is consistently preserved across turns and correctly merges parallel tool execution results to maintain compatibility with external APIs. The changes are a focused re-implementation of core fixes from a previous, broader pull request, emphasizing stability and correctness.

Highlights

  • Orphaned Tool Results Prevention: The JobDelegate::call_llm() function now extracts reasoning text from select_tools() results and includes it as content in RespondResult::ToolCalls. This ensures the assistant_with_tool_calls message retains the LLM's reasoning, preventing context loss in subsequent turns and addressing issues with orphaned tool results.
  • Parallel Tool Results Merging: The rig_adapter::convert_messages() function has been updated to merge consecutive Role::Tool messages into a single RigMessage::User containing multiple ToolResult content items. This resolves an issue where Anthropic's API would reject requests due to consecutive User messages resulting from parallel tool execution.
  • Regression Tests: New regression tests have been added for both bug fixes to ensure the stability and correctness of the implemented changes.
  • Code Quality: The changes maintain a minimal and focused scope, avoid the use of .unwrap() or .expect() in production code, and introduce zero clippy warnings, adhering to high code quality standards.
Changelog
  • src/llm/rig_adapter.rs
    • Modified convert_messages to merge consecutive Role::Tool messages into a single RigMessage::User when converting chat messages.
    • Added test_consecutive_tool_results_merged_into_single_user_message to verify the merging logic for parallel tool results.
    • Added test_tool_result_after_user_text_not_merged to ensure tool results are not merged after non-tool user messages.
  • src/worker/job.rs
    • Updated JobDelegate::call_llm to extract and preserve the LLM's reasoning text from ToolSelection results, passing it as content in RespondResult::ToolCalls.
    • Added test_selections_to_tool_calls_preserves_ids to confirm that tool call IDs are correctly preserved during conversion, preventing orphaned tool results.
    • Added test_reasoning_text_extraction_from_selections to validate the extraction of reasoning text from tool selections and handle empty reasoning appropriately.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@github-actions github-actions Bot added risk: medium Business logic, config, or moderate-risk modules contributor: core 20+ merged PRs labels Mar 12, 2026
@zmanian
zmanian enabled auto-merge (squash) March 12, 2026 19:47

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces two important fixes for tool handling: merging consecutive tool results to support APIs like Anthropic, and preserving the LLM's reasoning text when tool calls are made. The changes are well-implemented and include corresponding regression tests. I've identified a potential issue where reasoning context could be lost if the first of several parallel tool selections has empty reasoning, and I've provided a suggestion to make this more robust. Additionally, tests should be updated to reflect this improved logic and ensure comprehensive coverage, aligning with best practices for test maintenance.

Comment thread src/worker/job.rs Outdated
Comment on lines +1164 to +1167
let reasoning_text = s
.first()
.map(|sel| sel.reasoning.clone())
.filter(|r| !r.is_empty());

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.

medium

The current implementation only considers the reasoning from the first ToolSelection. If the first selection has empty reasoning but a subsequent one has non-empty reasoning, this context will be lost. To make this more robust, you should iterate through all selections and use the first non-empty reasoning string found.

Suggested change
let reasoning_text = s
.first()
.map(|sel| sel.reasoning.clone())
.filter(|r| !r.is_empty());
let reasoning_text = s
.iter()
.find_map(|sel| (!sel.reasoning.is_empty()).then_some(sel.reasoning.clone()));

Comment thread src/worker/job.rs
Comment on lines +1884 to +1932
fn test_reasoning_text_extraction_from_selections() {
// Simulate what call_llm does: extract reasoning from first selection
let selections = [
ToolSelection {
tool_name: "search".into(),
parameters: serde_json::json!({}),
reasoning: "I need to search for relevant information".into(),
alternatives: vec![],
tool_call_id: "call_1".into(),
},
ToolSelection {
tool_name: "fetch".into(),
parameters: serde_json::json!({}),
reasoning: "I need to search for relevant information".into(),
alternatives: vec![],
tool_call_id: "call_2".into(),
},
];

let reasoning_text = selections
.first()
.map(|sel| sel.reasoning.clone())
.filter(|r| !r.is_empty());

assert_eq!(
reasoning_text.as_deref(),
Some("I need to search for relevant information"),
"Reasoning text should be extracted from first selection"
);

// Empty reasoning should result in None
let empty_selections = [ToolSelection {
tool_name: "echo".into(),
parameters: serde_json::json!({}),
reasoning: String::new(),
alternatives: vec![],
tool_call_id: "call_3".into(),
}];

let empty_reasoning = empty_selections
.first()
.map(|sel| sel.reasoning.clone())
.filter(|r| !r.is_empty());

assert!(
empty_reasoning.is_none(),
"Empty reasoning should not be included as content"
);
}

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.

medium

This test currently simulates the logic of only taking reasoning from the first selection. To align with the suggested improvement of finding the first non-empty reasoning from any selection, this test should be updated.

Specifically:

  1. Update the logic inside the test to use find_map as suggested for the implementation.
  2. Add a new test case to verify that reasoning is correctly extracted when the first selection has empty reasoning but a subsequent one has non-empty reasoning.

Example of the new test case:

        let selections_with_first_empty = [
            ToolSelection {
                tool_name: "search".into(),
                parameters: serde_json::json!({}),
                reasoning: "".into(),
                alternatives: vec![],
                tool_call_id: "call_1".into(),
            },
            ToolSelection {
                tool_name: "fetch".into(),
                parameters: serde_json::json!({}),
                reasoning: "This reasoning should be picked up".into(),
                alternatives: vec![],
                tool_call_id: "call_2".into(),
            },
        ];

        let reasoning_text = selections_with_first_empty
            .iter()
            .find_map(|sel| (!sel.reasoning.is_empty()).then_some(sel.reasoning.clone()));

        assert_eq!(
            reasoning_text.as_deref(),
            Some("This reasoning should be picked up")
        );
References
  1. When refactoring, ensure that tests for generic functionality are updated to cover the new data structures, preventing loss of test coverage.

Two fixes for tool result handling in the Worker:

1. Preserve reasoning text from select_tools() in the RespondResult
   content field so it appears in the assistant_with_tool_calls message
   pushed by execute_tool_calls. Without this, the LLM's reasoning
   context was lost when using the select_tools path.

2. Merge consecutive tool_result messages into a single User message
   in rig_adapter's convert_messages(). When parallel tools execute,
   each produces a separate ChatMessage with role: Tool. Without
   merging, these become consecutive User messages which Anthropic
   rejects. Now consecutive tool results are merged into one User
   message with multiple ToolResult content items.

Includes regression tests for both fixes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zmanian
zmanian force-pushed the fix/635-orphaned-tool-results branch from c27245f to c0c95ec Compare March 12, 2026 20:26
The previous code only checked the first ToolSelection's reasoning,
missing cases where the first selection has empty reasoning but
subsequent ones do not. Switch to find_map to get the first non-empty
reasoning across all selections.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@github-actions github-actions Bot added size: L 200-499 changed lines and removed size: M 50-199 changed lines labels Mar 15, 2026
@zmanian
zmanian merged commit 58a3eb1 into staging Mar 16, 2026
14 checks passed
@zmanian
zmanian deleted the fix/635-orphaned-tool-results branch March 16, 2026 07:51
@ironclaw-ci ironclaw-ci Bot mentioned this pull request Mar 17, 2026
bkutasi pushed a commit to bkutasi/ironclaw that referenced this pull request Mar 28, 2026
…earai#1069)

* fix(worker): prevent orphaned tool_results and fix parallel merging

Two fixes for tool result handling in the Worker:

1. Preserve reasoning text from select_tools() in the RespondResult
   content field so it appears in the assistant_with_tool_calls message
   pushed by execute_tool_calls. Without this, the LLM's reasoning
   context was lost when using the select_tools path.

2. Merge consecutive tool_result messages into a single User message
   in rig_adapter's convert_messages(). When parallel tools execute,
   each produces a separate ChatMessage with role: Tool. Without
   merging, these become consecutive User messages which Anthropic
   rejects. Now consecutive tool results are merged into one User
   message with multiple ToolResult content items.

Includes regression tests for both fixes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(worker): use find_map for first non-empty reasoning extraction

The previous code only checked the first ToolSelection's reasoning,
missing cases where the first selection has empty reasoning but
subsequent ones do not. Switch to find_map to get the first non-empty
reasoning across all selections.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
drchirag1991 pushed a commit to drchirag1991/ironclaw that referenced this pull request Apr 8, 2026
…earai#1069)

* fix(worker): prevent orphaned tool_results and fix parallel merging

Two fixes for tool result handling in the Worker:

1. Preserve reasoning text from select_tools() in the RespondResult
   content field so it appears in the assistant_with_tool_calls message
   pushed by execute_tool_calls. Without this, the LLM's reasoning
   context was lost when using the select_tools path.

2. Merge consecutive tool_result messages into a single User message
   in rig_adapter's convert_messages(). When parallel tools execute,
   each produces a separate ChatMessage with role: Tool. Without
   merging, these become consecutive User messages which Anthropic
   rejects. Now consecutive tool results are merged into one User
   message with multiple ToolResult content items.

Includes regression tests for both fixes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(worker): use find_map for first non-empty reasoning extraction

The previous code only checked the first ToolSelection's reasoning,
missing cases where the first selection has empty reasoning but
subsequent ones do not. Switch to find_map to get the first non-empty
reasoning across all selections.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor: core 20+ merged PRs risk: medium Business logic, config, or moderate-risk modules scope: llm LLM integration scope: worker Container worker size: L 200-499 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants