Skip to content

Bug: async _check_and_compact() ignores tool_use filtering, causes BadRequestError #1205

@fede-kamel

Description

@fede-kamel

Bug

When using the async tool runner with compaction enabled, _check_and_compact() sends unfiltered tool_use blocks to the API, causing a BadRequestError.

Error:

BadRequestError: messages.2: `tool_use` ids were found without 
`tool_result` blocks immediately after: toolu_test123

Root Cause

In src/anthropic/lib/tools/_beta_runner.py, the async _check_and_compact() method (line ~472) uses self._params["messages"] instead of the filtered local messages variable when building the summarization request.

The filtering logic (lines ~457-469) correctly removes assistant messages containing only tool_use blocks, but the result is discarded because self._params["messages"] is used instead:

# Line ~472 (async version - BUGGY):
messages = [
    *self._params["messages"],  # ignores the filtering done above
    ...
]

# Line ~211 (sync version - CORRECT):
messages = [
    *messages,  # uses the filtered variable
    ...
]

Reproduction

Gist with standalone reproduction (no API key needed):
https://gist.github.com/fede-kamel/175f0e99abdb53a380ded3f41236e7dd

Fix

PR #1124 — one-line change: replace self._params["messages"] with messages on line ~472.

The PR also fixes a similar issue in append_messages (line ~120) where a lambda captures self._params["messages"] at definition time instead of using params["messages"] at call time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions