Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from openhands.sdk.context.view.properties.base import ViewPropertyBase
from openhands.sdk.context.view.properties.batch_atomicity import BatchAtomicityProperty
from openhands.sdk.context.view.properties.observation_uniqueness import (
ObservationUniquenessProperty,
)
from openhands.sdk.context.view.properties.tool_call_matching import (
ToolCallMatchingProperty,
)
Expand All @@ -9,6 +12,7 @@


ALL_PROPERTIES: list[ViewPropertyBase] = [
ObservationUniquenessProperty(),
BatchAtomicityProperty(),
ToolCallMatchingProperty(),
ToolLoopAtomicityProperty(),
Expand All @@ -18,6 +22,7 @@
__all__ = [
"ViewPropertyBase",
"BatchAtomicityProperty",
"ObservationUniquenessProperty",
"ToolCallMatchingProperty",
"ToolLoopAtomicityProperty",
"ALL_PROPERTIES",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from collections.abc import Sequence
from logging import getLogger

from openhands.sdk.context.view.manipulation_indices import ManipulationIndices
from openhands.sdk.context.view.properties.base import ViewPropertyBase
from openhands.sdk.event import (
Event,
EventID,
LLMConvertibleEvent,
ObservationBaseEvent,
ToolCallID,
)


logger = getLogger(__name__)


class ObservationUniquenessProperty(ViewPropertyBase):
"""At most one observation-like event per tool_call_id.

Crash recovery can synthesize an ``AgentErrorEvent`` for an in-flight tool
call and then the original ``ObservationEvent`` may still arrive late, so
the view ends up with two observation-like events sharing a single
``tool_call_id``. Downstream LLM APIs (for example Anthropic tool use)
require exactly one ``tool_result`` per ``tool_use``, and the strict
pairing assumed by ``ToolCallMatchingProperty`` would otherwise raise
``KeyError`` during condensation.

This property is registered ahead of ``ToolCallMatchingProperty`` so the
duplicate is dropped before pairing logic runs.
"""

def enforce(
self,
current_view_events: list[LLMConvertibleEvent],
all_events: Sequence[Event], # noqa: ARG002
) -> set[EventID]:
"""Drop any observation-like event whose ``tool_call_id`` has already
been observed earlier in the view. The first occurrence wins because
the agent has likely already seen it.
"""
events_to_remove: set[EventID] = set()
seen_tool_call_ids: set[ToolCallID] = set()

for event in current_view_events:
if isinstance(event, ObservationBaseEvent):
if event.tool_call_id in seen_tool_call_ids:
events_to_remove.add(event.id)
else:
seen_tool_call_ids.add(event.tool_call_id)

return events_to_remove

def manipulation_indices(
self,
current_view_events: list[LLMConvertibleEvent],
) -> ManipulationIndices:
"""This property does not restrict manipulation indices. If a duplicate
observation-like event slips past ``enforce``, log a warning so the
regression is visible without crashing condensation.
"""
seen_tool_call_ids: set[ToolCallID] = set()

for event in current_view_events:
if isinstance(event, ObservationBaseEvent):
if event.tool_call_id in seen_tool_call_ids:
logger.warning(
"Duplicate observation-like event for tool_call_id=%s",
event.tool_call_id,
)
else:
seen_tool_call_ids.add(event.tool_call_id)

return ManipulationIndices.complete(current_view_events)
97 changes: 97 additions & 0 deletions tests/sdk/context/view/properties/test_observation_uniqueness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Tests for ObservationUniquenessProperty.

This property guarantees at most one observation-like event per
tool_call_id, which protects ToolCallMatchingProperty's strict pairing
assumption from crash-recovery scenarios where an AgentErrorEvent and a
late ObservationEvent share the same tool_call_id.
"""

from unittest.mock import create_autospec

from openhands.sdk.context.view.manipulation_indices import ManipulationIndices
from openhands.sdk.context.view.properties.observation_uniqueness import (
ObservationUniquenessProperty,
)
from openhands.sdk.event.base import LLMConvertibleEvent
from openhands.sdk.event.llm_convertible import (
ActionEvent,
AgentErrorEvent,
ObservationEvent,
)


def test_enforce_drops_late_observation_after_agent_error() -> None:
"""Crash-recovery scenario: AgentErrorEvent and a late ObservationEvent
share the same tool_call_id. The later observation-like event must be
dropped; the first one (the AgentErrorEvent the agent already saw) is
kept.
"""
property = ObservationUniquenessProperty()

action = create_autospec(ActionEvent, instance=True)
action.tool_call_id = "call_1"
action.id = "action_1"

agent_error = AgentErrorEvent(
error="A restart occurred while this tool was in progress.",
tool_name="terminal",
tool_call_id="call_1",
)

late_observation = create_autospec(ObservationEvent, instance=True)
late_observation.tool_call_id = "call_1"
late_observation.id = "obs_late"

events: list[LLMConvertibleEvent] = [action, agent_error, late_observation]

assert property.enforce(events, events) == {late_observation.id}


def test_enforce_no_duplicates_returns_empty() -> None:
property = ObservationUniquenessProperty()

action = create_autospec(ActionEvent, instance=True)
action.tool_call_id = "call_1"
action.id = "action_1"

observation = create_autospec(ObservationEvent, instance=True)
observation.tool_call_id = "call_1"
observation.id = "obs_1"

events: list[LLMConvertibleEvent] = [action, observation]
assert property.enforce(events, events) == set()


def test_manipulation_indices_returns_complete_for_well_formed_view() -> None:
property = ObservationUniquenessProperty()

action = create_autospec(ActionEvent, instance=True)
action.tool_call_id = "call_1"
action.id = "action_1"

observation = create_autospec(ObservationEvent, instance=True)
observation.tool_call_id = "call_1"
observation.id = "obs_1"

events: list[LLMConvertibleEvent] = [action, observation]
assert property.manipulation_indices(events) == ManipulationIndices.complete(events)


def test_manipulation_indices_warns_but_does_not_crash_on_duplicates(caplog) -> None:
property = ObservationUniquenessProperty()

observation_a = create_autospec(ObservationEvent, instance=True)
observation_a.tool_call_id = "call_1"
observation_a.id = "obs_a"

observation_b = create_autospec(ObservationEvent, instance=True)
observation_b.tool_call_id = "call_1"
observation_b.id = "obs_b"

events: list[LLMConvertibleEvent] = [observation_a, observation_b]

with caplog.at_level("WARNING"):
indices = property.manipulation_indices(events)

assert indices == ManipulationIndices.complete(events)
assert any("call_1" in rec.message for rec in caplog.records)
Loading