Skip to content

[Bug]: LLMBadRequestError from a poisoned tool_result permanently wedges conversations — no recovery path in Agent.step #5225

Closed as not planned

Description

@jpshackelford

Bug Description

A single provider-rejected tool_result message permanently wedges a conversation. When the provider returns a 400 that the SDK maps to LLMBadRequestError, Agent.step does not catch it — unlike LLMContentPolicyViolationError, LLMMalformedConversationHistoryError, or LLMContextWindowExceedError, which each have a soft-recovery branch. The exception bubbles out, the run terminates with ConversationExecutionStatus.ERROR, and because the offending event is already persisted in history, every subsequent run/resume rebuilds the same prompt and fails identically. The conversation cannot progress.

Expected Behavior

When the provider rejects a specific tool_result message (identified by index and content path, e.g. messages.148.content.0.tool_result.content.1.image.source.base64: invalid base64 data), the SDK should:

  • roll back the turn that introduced the rejected content, leaving the original events in the persisted store for audit,
  • tell the agent what failed and which tool calls in that turn had already completed,
  • and continue the run so the agent can course-correct or ask for help.

(Revised: the original wording proposed offset-precise placeholder substitution. See the "Design update" comment for why turn-level rollback was chosen instead.)

Actual Behavior

LLMBadRequestError reaches LocalConversation.run, is written to a ConversationErrorEvent, and ConversationRunError is re-raised. The poisoned event stays in state.events. Every resume rebuilds the same request and fails identically.

Reproduce with pytest against the SDK repo:

uv sync
uv run pytest tests/repro/test_bad_request_wedges_conversation.py -q

tests/repro/test_bad_request_wedges_conversation.py (sketch — the exact stub API depends on how the test suite fakes an LLM):

import pytest

from openhands.sdk.llm.exceptions import LLMBadRequestError


def test_bad_tool_result_does_not_wedge_conversation(fake_conversation_with_bad_image):
    """Given a persisted ObservationEvent that the provider rejects with a
    400 pointing at a specific messages.N.content... offset, run() must
    recover instead of raising the same error on every attempt."""
    conversation = fake_conversation_with_bad_image  # fixture builds state
                                                     # with one poisoned event
    conversation.run()   # today: raises ConversationRunError(LLMBadRequestError)
    # desired: run() returns; the offending observation is replaced with a
    # text placeholder in the LLM view; no repeated 400 on subsequent turns.
    assert conversation.state.execution_status.name != "ERROR"
    # No repeated 400 on subsequent turns:
    with pytest.raises(AssertionError):
        conversation.run()  # would raise if history were still poisoned

Real occurrence: OpenHands Cloud conversation 9ace83223e5540198bd5a74258cc2f84 — two identical ConversationErrorEvent(LLMBadRequestError) entries (e832b76a… at 20:07:25 and 1866c543… at 20:06:50) with different Anthropic request IDs. Both point at messages.108.content.0.tool_result.content.1.image.source.base64: invalid base64 data. Second, independent reproduction: conversation 9d716b170bd4424c9a9307e78a821836 (message 148, different task, different model).

Steps to Reproduce

  1. uv pip install openhands-sdk openhands-tools and set up a conversation that uses browser tools (or any tool that can produce an image tool_result).
  2. Cause a single ObservationEvent in history to carry an image whose bytes the provider rejects (e.g. via the masker-corruption path tracked in the companion issue, or by hand-editing a persisted event to contain non-base64 bytes in screenshot_data).
  3. Call conversation.run().
  4. The run raises ConversationRunError(LLMBadRequestError). The offending observation stays in the event store.
  5. Call conversation.run() again — same 400, same request path, still no recovery. The conversation is permanently unusable without hand-editing the event store.

Acceptance Criteria

Updated after design review — see the "Design update" comment below. The original offset-parsing / ObservationReplacementEvent proposal was replaced with turn-level rollback. Superseded items are struck through.

  • Provider errors that indict the message history (as opposed to request configuration) are recognized as a distinct, recoverable class rather than letting LLMBadRequestError bubble out and terminate the run.
  • A new SDK-typed exception is added for that class, classified in error_classification.py as kind=agent_action, retryable=true, user_action="retry" (parity with LLMMalformedConversationHistoryError), rather than the CONFIG/settings classification generic bad requests receive today.
  • The classifier distinguishes history-indicting rejections from genuine configuration errors (unsupported parameter, bad model name), so config errors keep their current non-retryable classification and are not met with a pointless rollback.
  • On such an error the conversation run loop rolls back one complete turn — the ActionEvents sharing an llm_response_id plus their paired results — via navigate_to, re-rooting the active branch to the event immediately preceding the turn's first action.
  • Rollback is view-only: the rolled-back events remain in the persisted event log and drop out of state.view only.
  • After rolling back, a message is injected that (a) names the provider error, with its text passed through the normal secret-masking path, and (b) enumerates the tool calls that completed in the rolled-back turn, so the agent can account for side effects (files written, commits made) that survive the rollback.
  • A one-shot guard prevents repeated rollback within a single run: if the same failure recurs after one recovery, the error surfaces as a ConversationErrorEvent rather than unwinding history further.
  • Regression tests assert that:
    • a poisoned turn does not raise ConversationRunError and the run continues,
    • the rolled-back events remain in state.events for auditability,
    • the next LLM request built from history does not contain the rejected content,
    • a turn containing parallel tool calls is rolled back as a unit, leaving no ActionEvent without a paired result,
    • the injected message names the completed tool calls from the rolled-back turn,
    • a genuine configuration error is not rolled back and retains its existing classification.
  • The recovery branch parses the failing offset from the provider message and substitutes a text-only placeholder for the offending content. Superseded: rollback discards the poisoned turn without needing to identify which event carried it.
  • If the offset can't be parsed, fall back to state.rebuild_view() + on_event(CondensationRequest()). Superseded: no condenser dependency.
  • The Exception Handling guide in docs/sdk/guides/llm-error-handling.md documents the new recovery behaviour. Not actionable: that docs tree does not exist in this repository. Documented in AGENTS.md instead.
  • uv run pytest against the SDK passes with no other regressions.

Installation Method

uv pip install openhands-sdk openhands-tools (also reproducible from a workspace uv sync).

SDK Version

Reproduced against main at the time of filing. Present in every release where Agent.step catches LLMContentPolicyViolationError / LLMMalformedConversationHistoryError / LLMContextWindowExceedError but not LLMBadRequestError.

Version Confirmation

  • I have confirmed this bug exists on the LATEST version of OpenHands SDK

Python Version

Any supported version — the halt behaviour is Python-version-independent.

Model Name (if applicable)

Reproduced against claude-sonnet-4-5-20250929 and claude-opus-4-7. The same design gap will bite any provider that can 400 on a specific tool_result offset (OpenAI, Gemini).

Operating System

Linux (OpenHands Cloud runtime). Platform-independent.

Logs and Error Messages

litellm.BadRequestError: Error code: 400 - {'error': {'message':
'litellm.BadRequestError: AnthropicException - b\'{"type":"error",
"error":{"type":"invalid_request_error",
"message":"messages.148.content.0.tool_result.content.1.image.source.base64: invalid base64 data"},
"request_id":"req_011CfK6ucacgkF3xTzNodr6g"}\'. Received Model Group=claude-opus-4-7
Available Model Group Fallbacks=None', 'type': None, 'param': None, 'code': '400'}}

Trajectory shows the same error rebuilt on every attempt (different Anthropic request IDs, identical offset). Once the poisoned observation is in history the run cannot progress.

Minimal Code Sample

The gap is structural. Illustrative excerpt from openhands-sdk/openhands/sdk/agent/agent.py showing the handlers that exist today and the missing branch:

except LLMContentPolicyViolationError as e:
    # posts a "please rephrase" user nudge and returns
    ...
except LLMMalformedConversationHistoryError as e:
    # state.rebuild_view() + on_event(CondensationRequest())
    ...
except LLMContextWindowExceedError as e:
    # on_event(CondensationRequest())
    ...
# ← no `except LLMBadRequestError` / no `LLMInvalidToolResultContentError`

openhands-sdk/openhands/sdk/event/error_classification.py:

if code in {"LLMBadRequestError", ...}:
    return _failure(FailureKind.CONFIG, user_action="settings")   # retryable=False

Screenshots and Additional Context

Proposed shape of the fix (revised — see the "Design update" comment for the reasoning and the evidence behind each point):

  1. In openhands-sdk/openhands/sdk/llm/exceptions/classifier.py, recognize provider errors that indict the message history. The durable signal is the message-offset shape the providers emit (messages.<N>.content...), which appears when the provider is pointing at history rather than at request configuration.
  2. Add a typed exception for that class in openhands-sdk/openhands/sdk/llm/exceptions/types.py and wire it into map_provider_exception above the generic LLMBadRequestError branch.
  3. Add its code to error_classification.classify_error as retryable=True, user_action="retry", so it is classified as an agent outcome rather than a configuration failure.
  4. In the conversation run loop, catch that exception and roll back one complete turn using the existing navigate_to machinery: walk back to the ActionEvents sharing the current turn's llm_response_id and re-root the active branch to the event immediately before the first of them. Rollback is view-only — abandoned events stay in the persisted log.
  5. Inject a message describing what happened: the masked provider error, plus an enumeration of the tool calls that completed in the rolled-back turn so the agent can account for surviving side effects. Guard against repeated rollback within a run so an unanticipated case degrades to today's behaviour (a clean ConversationErrorEvent) instead of unwinding history.

Superseded from the original proposal: offset parsing, a new ObservationReplacementEvent kind, condensation-based fallback, and a BrowserObservation.to_llm_content self-check. The last of these is a prevention measure specific to the base64 vector and is deferred to a follow-up PR.

Companion issue: the most common producer of this failure today is the secret-masker corrupting screenshot_data. That is tracked separately as #5224 — fixing it stops the current leak; this issue closes the trap door underneath it so future producers (bad upload, unsupported mime, oversize, MCP tool returning garbage) don't wedge the run either.


This bug report was created by an AI agent (OpenHands) on behalf of the user.

Activity

  1. added
    bug
    llm
    on Sep 22, 2026
  2. github-actions commented on Sep 22, 2026

    @github-actions
    Contributor

    ✅ ready-for-dev label applied

    This issue meets the readiness criteria and is ready for contribution.
    A contributor can now open a PR that links this issue (Fixes #<number>).

    This is an automated check — no AI was used to generate this comment.

  3. changed the title [-]LLMBadRequestError from a poisoned tool_result permanently wedges conversations — no recovery path in Agent.step[/-] [+][Bug]: LLMBadRequestError from a poisoned tool_result permanently wedges conversations — no recovery path in Agent.step[/+] on Sep 22, 2026
  4. added
    ready-for-dev
    on Sep 22, 2026
  5. added
    priority:normal
    and removed
    ready-for-dev
    on Sep 22, 2026
  6. added
    ready-for-dev
    on Sep 22, 2026
  7. removed
    ready-for-dev
    on Sep 22, 2026
  8. added
    ready-for-dev
    on Sep 22, 2026
  9. removed
    ready-for-dev
    on Sep 22, 2026
  10. added
    ready-for-dev
    on Sep 22, 2026
  11. 11 remaining items

  12. removed
    ready-for-dev
    on Sep 22, 2026
  13. added
    ready-for-dev
    on Sep 22, 2026
  14. removed
    ready-for-dev
    on Sep 22, 2026
  15. added
    ready-for-dev
    on Sep 22, 2026
  16. removed
    ready-for-dev
    on Sep 22, 2026
  17. added
    ready-for-dev
    on Sep 22, 2026
  18. removed
    ready-for-dev
    on Sep 22, 2026
  19. added
    ready-for-dev
    on Sep 22, 2026
  20. removed
    ready-for-dev
    on Sep 22, 2026
  21. added
    ready-for-dev
    on Sep 22, 2026
  22. removed
    ready-for-dev
    on Sep 22, 2026
  23. added
    ready-for-dev
    on Sep 22, 2026
  24. jpshackelford commented on Sep 23, 2026

    @jpshackelford
    MemberAuthor

    Design update — recovery mechanism chosen, scope broadened

    Answering the two open design questions raised in the triage comment above, with evidence from the code. (Note: ready-for-dev was applied by the automated readiness check before that comment; the label is on the issue.)

    1. Which recovery mechanism is canonical?

    Neither of the two options originally on the table.

    Not a new ObservationReplacementEvent — a new persisted event kind is a serialized compatibility surface that AGENTS.md requires tracing through the event store, agent-server REST/WebSocket, and clients/typescript. That is a lot of surface for this bug.

    Not the condensation path either. Condensation is size-driven and offers no guarantee it drops the specific offending event. Agent.condenser is also None by default. A condensation-based recovery can therefore request condensation against a still-poisoned history and make no progress.

    Instead: roll back one complete turn using the existing navigate_to machinery. ConversationState is already a tree with a movable HEAD (leaf_event_id), and navigate_to(event_id) re-roots the active branch. Per its docstring, "appending after navigating creates a sibling; abandoned events stay in the log but drop out of state.view." This is existing, tested machinery that already works across LocalConversation, RemoteConversation, and the base class — a new use of it, not a new mechanism.

    2. What is the fallback contract when the offset cannot be parsed?

    The question dissolves: we no longer parse offsets. Rolling back to the last known-good point discards the poisoned content without needing to identify which event carried it. There is no condenser dependency, so there is no "no condenser configured" branch.

    Evidence that shaped this design

    • No new checkpoint state needed. The run loop already emits ConversationErrorEvent into the event log and _latest_conversation_error already scans for it. More directly: intercepting the exception inside the iteration loop means the failing turn is the current turn, so the last-good point is known without any persisted marker.
    • No partial-turn hazard from parallel tool calls. ParallelToolExecutor._run_with_locking converts any tool exception into an AgentErrorEvent carrying the tool_call_id, and ConversationState.get_unmatched_actions accepts AgentErrorEvent as a valid match for an action. Every turn that reaches the next LLM call already has paired results. The poisoned-content failure happens at request-assembly time, after all tools in the turn have completed and been recorded.
    • The turn boundary is already modelled. ActionEvent.llm_response_id exists to "group related actions from same LLM response ... for parallel function calling." Rolling back a bare event could orphan a tool_use from its tool_result and convert this failure into LLMMalformedConversationHistoryError. Rolling back the whole llm_response_id group cannot.
    • Sub-agents need no special handling. A task sub-agent runs in its own LocalConversation with its own event tree, and TaskManager._run_task converts any exception into a task error surfaced to the parent as an ordinary tool result. Recovery inside a sub-agent stays inside the sub-agent.
    • Side effects survive rollback. Rolled-back tool calls may already have written files or made commits. Rollback is view-only and nothing is deleted, so the injected explanation must enumerate which tool calls completed, letting the agent account for work it can no longer see in context.

    Scope change

    This is no longer "add a fourth except branch to Agent.step." It is a general recovery mechanism in the conversation run loop, triggered by provider errors that indict the message history. It subsumes the reported symptom and other producers of the same wedge (bad upload, unsupported MIME type, oversized payload, MCP tool returning garbage).

    Acceptance criteria that cannot be met as written

    • The offset-parsing criterion is deliberately not met — see above.
    • The docs/sdk/guides/llm-error-handling.md criterion refers to a docs tree that does not exist in this repository. The behaviour is documented in AGENTS.md instead.

    The issue body has been updated to reflect the chosen design. The original proposal remains visible in the edit history.

    Deliberately deferred to a follow-up

    A prevention pass that drops undecodable base64 images before the request is sent is out of scope here. It addresses one specific failure vector (the #5224 masker corruption) rather than the general wedge, and it should be reviewed on its own merits once the general fix lands.


    This comment was posted by an AI agent (OpenHands) on behalf of @jpshackelford.

  25. all-hands-bot commented on Nov 10, 2026

    @all-hands-bot
    Collaborator

    [Automatic Post]: This issue was automatically closed due to 47 days of inactivity. We do this to help keep the issue tracker manageable and focused on active issues. If this is still relevant, feel free to reopen it.

    Generated by OpenHands automation on behalf of the user.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-executionbugllmneeds-triagepriority:normalready-for-devsdk

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions