Skip to content

Fix #550: Add error rule for tool_use missing tool_result#551

Merged
ding113 merged 1 commit intodevfrom
fix/issue-550-tool-use-missing-tool-result
Jan 6, 2026
Merged

Fix #550: Add error rule for tool_use missing tool_result#551
ding113 merged 1 commit intodevfrom
fix/issue-550-tool-use-missing-tool-result

Conversation

@ding113
Copy link
Owner

@ding113 ding113 commented Jan 6, 2026

Summary

  • Add new error rule to handle tool_use blocks missing corresponding tool_result in next message
  • This is the reverse direction of the existing rule for tool_result missing tool_use

Problem

Fixes #550

When a request contains a tool_use block without a corresponding tool_result in the immediately following message, Claude API returns:

`tool_use` ids were found without `tool_result` blocks immediately after: tooluse_xxx. 
Each `tool_use` block must have a corresponding `tool_result` block in the next message.

This error was not covered by existing rules, causing unnecessary retries and provider switching.

Solution

Added a new regex error rule with pattern:

tool_use.*ids were found without.*tool_result.*immediately after|tool_use.*block must have.*corresponding.*tool_result.*block in the next message

This rule:

  • Categorizes the error as validation_error
  • Returns a user-friendly Chinese message explaining the issue
  • Has priority 88 (same as other tool validation errors)
  • Prevents retry/provider switching since this is a client-side error

Changes

Testing

  • Verified regex pattern is valid
  • Tested pattern matches the actual error message from issue
  • Auto-sync on startup will add this rule to database

Created by Claude AI in response to @claude mention

Greptile Summary

This PR adds a new error rule to handle validation errors when a tool_use block is missing its corresponding tool_result in the next message. The implementation is clean and follows the existing patterns in the codebase:

  • Pattern matching: The regex pattern correctly matches both variations of the Claude API error message
  • Categorization: Properly categorized as validation_error (non-retryable client error)
  • Priority: Set to 88, matching the related tool_result validation rule on line 518
  • Message: Provides clear Chinese error message explaining the issue
  • Placement: Well-positioned alongside other tool validation rules (lines 423-526)

The implementation is consistent with the reverse error case (line 510-526) and properly prevents unnecessary retries for this client-side validation error.

Confidence Score: 5/5

  • This PR is safe to merge with no concerns
  • The change is minimal, well-tested, and follows established patterns. The regex pattern correctly matches the error message from the issue, and the implementation is consistent with similar validation rules in the codebase.
  • No files require special attention

Important Files Changed

Filename Overview
src/repository/error-rules.ts Added new error rule for tool_use missing tool_result validation - pattern is correct and consistent with existing rules

Sequence Diagram

sequenceDiagram
    participant Client
    participant ErrorDetector
    participant ClaudeAPI
    participant Database
    
    Note over Client,Database: Error Rule Synchronization on Startup
    Client->>Database: syncDefaultErrorRules()
    Database-->>Client: Insert/Update new rule #550
    
    Note over Client,Database: Request Processing Flow
    Client->>ClaudeAPI: Send request with tool_use block
    ClaudeAPI-->>Client: Error: tool_use missing tool_result
    
    Client->>ErrorDetector: Match error message
    ErrorDetector->>Database: Query active error rules (priority 88)
    Database-->>ErrorDetector: Return rule #550 pattern
    
    ErrorDetector->>ErrorDetector: Regex match: tool_use.*ids were found without.*tool_result
    ErrorDetector-->>Client: Override response (validation_error)
    
    Note over Client: No retry - client-side validation error
    Client-->>Client: Return user-friendly Chinese message
Loading

Add new error rule to handle the case where a `tool_use` block is missing
its corresponding `tool_result` in the next message. This is the reverse
direction of the existing rule for `tool_result` missing `tool_use`.

The new pattern matches:
- `tool_use` ids were found without `tool_result` blocks immediately after
- Each `tool_use` block must have a corresponding `tool_result` block

Closes #550

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ding113, 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 introduces a crucial enhancement to the error handling mechanism by adding a new rule to detect and manage a specific Claude API error. Previously, the system would not correctly identify when a 'tool_use' block lacked its required 'tool_result' in the subsequent message, leading to inefficient retries. The new rule ensures that such validation errors are properly categorized, communicated to the user in a clear message, and prevent further incorrect processing.

Highlights

  • New Error Rule: Added a new error rule to specifically handle cases where a 'tool_use' block is not followed by a corresponding 'tool_result' in the subsequent message from the Claude API.
  • Error Categorization: The new rule categorizes this specific issue as a 'validation_error', indicating a client-side problem rather than a server error.
  • User Feedback: A user-friendly Chinese message is now provided for this error, explaining that a 'tool_use' block requires a corresponding 'tool_result' in the next message.
  • Improved Error Handling: This change prevents unnecessary retries or provider switching, as the error is now correctly identified as a client-side validation issue.
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.

@coderabbitai
Copy link

coderabbitai bot commented Jan 6, 2026

📝 Walkthrough

总览

src/repository/error-rules.ts 中添加一条新的默认错误规则,用于检测工具使用块缺少对应的工具结果块。该规则使用正则表达式模式匹配,覆盖工具块在后续消息中缺少结果的场景。

变更内容

文件群组 / 文件路径 变更摘要
错误验证规则
src/repository/error-rules.ts
DEFAULT_ERROR_RULES 中新增错误规则,用于验证 tool_use 块是否在后续消息中具有对应的 tool_result 块。规则配置包括:正则表达式模式检测、优先级88、非重试验证错误类型、包含中文错误信息的覆盖响应

代码审查工作量评估

🎯 2 (Simple) | ⏱️ ~10 分钟

可能相关的 PR

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 标题清晰准确地描述了主要变更,即添加错误规则来处理Issue #550中tool_use缺少tool_result的情况。
Linked Issues check ✅ Passed 代码变更完全满足Issue #550的需求,添加了正确的正则表达式规则来检测tool_use缺少tool_result的错误情况。
Out of Scope Changes check ✅ Passed 所有变更都针对Issue #550的目标,仅修改了error-rules.ts文件以添加新的错误规则,没有超出范围的改动。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The pull request description clearly explains the changes: adding a new error rule to handle tool_use blocks missing corresponding tool_result in the next message, with specific regex pattern, categorization, priority, and purpose.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/issue-550-tool-use-missing-tool-result

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

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 a new error rule to handle cases where a tool_use block is missing its corresponding tool_result. This is a valuable addition that correctly categorizes a client-side error as non-retryable, preventing unnecessary provider switching. The implementation is clean and consistent with the existing error rule structure. I have one minor suggestion to refactor the regular expression for improved readability and a slight performance gain. Overall, this is a well-executed fix.

Comment on lines +529 to +530
pattern:
"tool_use.*ids were found without.*tool_result.*immediately after|tool_use.*block must have.*corresponding.*tool_result.*block in the next message",
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The regex pattern can be slightly refactored to improve readability and performance by factoring out the common tool_use.* prefix. This avoids repeating the prefix and makes the regex engine's job slightly easier by using a non-capturing group for the alternatives.

Suggested change
pattern:
"tool_use.*ids were found without.*tool_result.*immediately after|tool_use.*block must have.*corresponding.*tool_result.*block in the next message",
pattern:
"tool_use.*(?:ids were found without.*tool_result.*immediately after|block must have.*corresponding.*tool_result.*block in the next message)",

@github-actions github-actions bot added bug Something isn't working area:Error Rule size/XS Extra Small PR (< 50 lines) labels Jan 6, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Jan 6, 2026

🧪 测试结果

测试类型 状态
代码质量
单元测试
集成测试
API 测试

总体结果: ✅ 所有测试通过

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/repository/error-rules.ts (1)

527-545: 新规则实现正确,符合设计目标。

此规则正确地匹配了 Issue #550 中描述的 API 错误场景,将其归类为 validation_error(客户端错误),避免了不必要的重试和供应商切换。实现遵循了现有规则的模式,用户提示信息清晰明确。

不过,建议考虑以下优化:

  1. 正则表达式性能优化:当前模式使用贪婪匹配 .*,在极长的错误消息中可能影响性能。建议使用非贪婪匹配 .*? 或更具体的字符类(如 \s+\w+)。
  2. 优先级冲突提醒:新规则的优先级(88)与上方的 tool_result 验证规则相同,且两者都属于 validation_error 类别。虽然不影响功能(按插入顺序处理),但如果未来需要调整匹配顺序,可能需要区分优先级。
🔎 可选的正则表达式优化建议
   {
     pattern:
-      "tool_use.*ids were found without.*tool_result.*immediately after|tool_use.*block must have.*corresponding.*tool_result.*block in the next message",
+      "tool_use.*?ids were found without.*?tool_result.*?immediately after|tool_use.*?block must have.*?corresponding.*?tool_result.*?block in the next message",
     category: "validation_error",
     description: "tool_use block missing corresponding tool_result in next message (client error)",
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to Reviews > Disable Cache setting

📥 Commits

Reviewing files that changed from the base of the PR and between cd627f6 and e687a9e.

📒 Files selected for processing (1)
  • src/repository/error-rules.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx,json}

📄 CodeRabbit inference engine (CLAUDE.md)

Use 2-space indentation in all code files

Files:

  • src/repository/error-rules.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx,js,jsx}: Use double quotes for strings instead of single quotes
Use trailing commas in multi-line structures
Enforce maximum line length of 100 characters
Use path alias @/* to reference files from ./src/* directory

**/*.{ts,tsx,js,jsx}: Use Biome for linting and formatting with 2-space indent, double quotes, trailing commas, and 100 character max line length
Use path alias @/* to reference files in ./src/* directory

Files:

  • src/repository/error-rules.ts
src/repository/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use Repository pattern in src/repository/ to wrap Drizzle queries

Files:

  • src/repository/error-rules.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript strict mode for type safety
Use readonly or const assertions for immutable data structures

Files:

  • src/repository/error-rules.ts
src/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.ts: Hash API keys using SHA-256 before storing in database, never store plaintext keys
Mask API keys and sensitive data in application logs
Validate required environment variables at startup with clear error messages

Files:

  • src/repository/error-rules.ts
src/{repository,actions}/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Avoid N+1 queries by using eager loading and batch queries for statistics

Files:

  • src/repository/error-rules.ts
🧠 Learnings (1)
📚 Learning: 2026-01-05T03:01:39.354Z
Learnt from: NieiR
Repo: ding113/claude-code-hub PR: 539
File: src/types/user.ts:158-170
Timestamp: 2026-01-05T03:01:39.354Z
Learning: In TypeScript interfaces, explicitly document and enforce distinct meanings for null and undefined. Example: for numeric limits like limitTotalUsd, use 'number | null | undefined' when null signifies explicitly unlimited (e.g., matches DB schema or special UI logic) and undefined signifies 'inherit default'. This pattern should be consistently reflected in type definitions across related fields to preserve semantic clarity between database constraints and UI behavior.

Applied to files:

  • src/repository/error-rules.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Greptile Review
  • GitHub Check: pr-description
  • GitHub Check: 🌐 API Tests
  • GitHub Check: pr-review
  • GitHub Check: check-codex-status
  • GitHub Check: Docker Build Test
  • GitHub Check: dev-build-deploy
🔇 Additional comments (2)
src/repository/error-rules.ts (2)

536-536: 注意:优先级值与相邻规则重复。

新规则的优先级(88)与上方第 518 行的 tool_result 验证规则相同,且两者都属于 validation_error 类别。根据第 109 行的排序逻辑 [errorRules.priority, errorRules.category],当优先级和类别都相同时,规则的匹配顺序将取决于数据库插入顺序或 ID。

虽然这不影响当前功能(两个规则匹配不同的错误场景),但如果未来需要明确控制这两条规则的检测顺序,建议为其中一条分配不同的优先级值(例如 87 或 89)。

基于代码审查指南:这是优先级管理的最佳实践建议。


529-530: 正则表达式的特异性已验证。该模式包含多个关键词序列,在错误消息匹配中具有足够的特异性。第二个分支虽然使用 .* 进行灵活匹配,但包含了多个显著的关键词组合("block must have"、"corresponding"、"block in the next message"),这与文件中其他类似模式(如 Issue #471)的设计一致。缺乏实际错误消息示例或假阳性匹配的证据。建议保留当前模式,除非在实际使用中发现误匹配问题。

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Code Review Summary

No significant issues identified in this PR.

PR Size: XS

  • Lines changed: 19
  • Files changed: 1

Review Coverage

  • Logic and correctness - Clean
  • Security (OWASP Top 10) - Clean
  • Error handling - Clean
  • Type safety - Clean
  • Documentation accuracy - Clean
  • Test coverage - Adequate
  • Code clarity - Good

Automated review by Codex AI

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Applied the size/XS label to PR #551 and submitted a PR review summary via gh pr review.

No inline review comments were posted because no issues meeting the reporting threshold were found in the diff.

@ding113 ding113 merged commit 51ff602 into dev Jan 6, 2026
20 checks passed
@github-project-automation github-project-automation bot moved this from Backlog to Done in Claude Code Hub Roadmap Jan 6, 2026
This was referenced Jan 6, 2026
@ding113 ding113 deleted the fix/issue-550-tool-use-missing-tool-result branch January 27, 2026 09:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Error Rule bug Something isn't working size/XS Extra Small PR (< 50 lines)

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant