Repository navigation
Description
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 -qtests/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 poisonedReal 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
uv pip install openhands-sdk openhands-toolsand set up a conversation that uses browser tools (or any tool that can produce an imagetool_result).- Cause a single
ObservationEventin 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 inscreenshot_data). - Call
conversation.run(). - The run raises
ConversationRunError(LLMBadRequestError). The offending observation stays in the event store. - 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 /
ObservationReplacementEventproposal 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
LLMBadRequestErrorbubble out and terminate the run. - A new SDK-typed exception is added for that class, classified in
error_classification.pyaskind=agent_action, retryable=true, user_action="retry"(parity withLLMMalformedConversationHistoryError), rather than theCONFIG/settingsclassification 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 anllm_response_idplus their paired results — vianavigate_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.viewonly. - 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
ConversationErrorEventrather than unwinding history further. - Regression tests assert that:
- a poisoned turn does not raise
ConversationRunErrorand the run continues, - the rolled-back events remain in
state.eventsfor auditability, - the next
LLMrequest built from history does not contain the rejected content, - a turn containing parallel tool calls is rolled back as a unit, leaving no
ActionEventwithout 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.
- a poisoned turn does not raise
-
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 toSuperseded: no condenser dependency.state.rebuild_view()+on_event(CondensationRequest()). -
TheNot actionable: that docs tree does not exist in this repository. Documented inException Handlingguide indocs/sdk/guides/llm-error-handling.mddocuments the new recovery behaviour.AGENTS.mdinstead. -
uv run pytestagainst 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=FalseScreenshots and Additional Context
Proposed shape of the fix (revised — see the "Design update" comment for the reasoning and the evidence behind each point):
- 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. - Add a typed exception for that class in
openhands-sdk/openhands/sdk/llm/exceptions/types.pyand wire it intomap_provider_exceptionabove the genericLLMBadRequestErrorbranch. - Add its code to
error_classification.classify_errorasretryable=True, user_action="retry", so it is classified as an agent outcome rather than a configuration failure. - In the conversation run loop, catch that exception and roll back one complete turn using the existing
navigate_tomachinery: walk back to theActionEvents sharing the current turn'sllm_response_idand 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. - 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
github-actions commentedon Sep 22, 2026
✅
ready-for-devlabel appliedThis 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.
[-]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[/+]11 remaining items
jpshackelford commentedon Sep 23, 2026
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-devwas 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 thatAGENTS.mdrequires tracing through the event store, agent-server REST/WebSocket, andclients/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.condenseris alsoNoneby 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_tomachinery.ConversationStateis already a tree with a movable HEAD (leaf_event_id), andnavigate_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 ofstate.view." This is existing, tested machinery that already works acrossLocalConversation,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
ConversationErrorEventinto the event log and_latest_conversation_erroralready 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.ParallelToolExecutor._run_with_lockingconverts any tool exception into anAgentErrorEventcarrying thetool_call_id, andConversationState.get_unmatched_actionsacceptsAgentErrorEventas 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.ActionEvent.llm_response_idexists to "group related actions from same LLM response ... for parallel function calling." Rolling back a bare event could orphan atool_usefrom itstool_resultand convert this failure intoLLMMalformedConversationHistoryError. Rolling back the wholellm_response_idgroup cannot.LocalConversationwith its own event tree, andTaskManager._run_taskconverts 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.Scope change
This is no longer "add a fourth
exceptbranch toAgent.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
docs/sdk/guides/llm-error-handling.mdcriterion refers to a docs tree that does not exist in this repository. The behaviour is documented inAGENTS.mdinstead.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.
all-hands-bot commentedon Nov 10, 2026
[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.