From 4edc9b160ef9a4af7c38c2da4d47f65c35e10416 Mon Sep 17 00:00:00 2001 From: simonrosenberg <157206163+simonrosenberg@users.noreply.github.com> Date: Fri, 1 May 2026 13:08:31 -0700 Subject: [PATCH 1/6] =?UTF-8?q?fix:=20deduplicate=20ACP=20tool=20call=20ev?= =?UTF-8?q?ents=20and=20truncate=20content=20to=20prevent=20O(n=C2=B2)=20m?= =?UTF-8?q?emory=20growth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../openhands/sdk/agent/acp_agent.py | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index ee5a31f56ee..ed30e036a6d 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -59,6 +59,7 @@ from openhands.sdk.secret import SecretSource from openhands.sdk.tool import Tool # noqa: TC002 from openhands.sdk.tool.builtins.finish import FinishAction, FinishObservation +from openhands.sdk.utils import maybe_truncate logger = get_logger(__name__) @@ -97,6 +98,10 @@ # upstream model 500s, and transient infrastructure errors. _RETRIABLE_SERVER_ERROR_CODES: frozenset[int] = frozenset({-32603}) +# Maximum characters for ACP tool call content — matches MAX_CMD_OUTPUT_SIZE +# used by the terminal tool and the default max_message_chars in LLM config. +MAX_ACP_CONTENT_CHARS: int = 30_000 + # Limit for asyncio.StreamReader buffers used by the ACP subprocess pipes. # The default (64 KiB) is too small for session_update notifications that # carry large tool-call outputs (e.g. file contents, test results). When @@ -276,9 +281,13 @@ def _serialize_tool_content(content: list[Any] | None) -> list[dict[str, Any]] | """Serialize ACP tool call content blocks to plain dicts for JSON storage.""" if not content: return None - return [ - c.model_dump(mode="json") if hasattr(c, "model_dump") else c for c in content - ] + result = [] + for c in content: + d = c.model_dump(mode="json") if hasattr(c, "model_dump") else c + if isinstance(d, dict) and d.get("type") == "text" and isinstance(d.get("text"), str): + d = {**d, "text": maybe_truncate(d["text"], truncate_after=MAX_ACP_CONTENT_CHARS)} + result.append(d) + return result async def _filter_jsonrpc_lines(source: Any, dest: Any) -> None: @@ -503,13 +512,16 @@ def _emit_tool_call_event(self, tc: dict[str, Any]) -> None: if self.on_event is None: return try: + raw_output = tc.get("raw_output") + if isinstance(raw_output, str): + raw_output = maybe_truncate(raw_output, truncate_after=MAX_ACP_CONTENT_CHARS) event = ACPToolCallEvent( tool_call_id=tc["tool_call_id"], title=tc["title"], status=tc.get("status"), tool_kind=tc.get("tool_kind"), raw_input=tc.get("raw_input"), - raw_output=tc.get("raw_output"), + raw_output=raw_output, content=tc.get("content"), is_error=tc.get("status") == "failed", ) From 7ea2d532985f60c6a92c0430a97d3291ddd1bb77 Mon Sep 17 00:00:00 2001 From: simonrosenberg <157206163+simonrosenberg@users.noreply.github.com> Date: Fri, 1 May 2026 13:08:41 -0700 Subject: [PATCH 2/6] =?UTF-8?q?fix:=20deduplicate=20ACP=20tool=20call=20ev?= =?UTF-8?q?ents=20in=20RemoteEventsList=20to=20prevent=20O(n=C2=B2)=20memo?= =?UTF-8?q?ry=20growth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conversation/impl/remote_conversation.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py index 902d34c3d24..09b108972a6 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py @@ -37,6 +37,7 @@ ConversationVisualizerBase, DefaultConversationVisualizer, ) +from openhands.sdk.event.acp_tool_call import ACPToolCallEvent from openhands.sdk.event.base import Event from openhands.sdk.event.conversation_error import ConversationErrorEvent from openhands.sdk.event.conversation_state import ( @@ -259,6 +260,7 @@ def __init__( self._events_base_path = events_base_path self._cached_events: list[Event] = [] self._cached_event_ids: set[str] = set() + self._acp_tool_call_id_to_event_id: dict[str, str] = {} self._lock = threading.RLock() # Initial fetch to sync existing events self._do_full_sync() @@ -350,6 +352,25 @@ def reconcile(self) -> int: def _add_event_unsafe(self, event: Event) -> None: """Add event to cache without acquiring lock (caller must hold lock).""" + # ACP streaming emits one ACPToolCallEvent per ToolCallProgress, each + # carrying the full cumulative stdout so far — O(n²) memory growth. + # Deduplicate by tool_call_id: replace the existing entry in-place so + # only the latest (most complete) snapshot is kept. + if isinstance(event, ACPToolCallEvent): + existing_id = self._acp_tool_call_id_to_event_id.get(event.tool_call_id) + if existing_id is not None: + for i, e in enumerate(self._cached_events): + if e.id == existing_id: + self._cached_events[i] = event + self._cached_event_ids.discard(existing_id) + self._cached_event_ids.add(event.id) + self._acp_tool_call_id_to_event_id[event.tool_call_id] = event.id + logger.debug( + f"Replaced ACP tool call event {existing_id} -> {event.id} " + f"(tool_call_id={event.tool_call_id})" + ) + return + # Use bisect with key function for O(log N) insertion # This ensures events are always ordered correctly even if # WebSocket delivers them out of order @@ -358,6 +379,8 @@ def _add_event_unsafe(self, event: Event) -> None: ) self._cached_events.insert(insert_pos, event) self._cached_event_ids.add(event.id) + if isinstance(event, ACPToolCallEvent): + self._acp_tool_call_id_to_event_id[event.tool_call_id] = event.id logger.debug(f"Added event {event.id} to local cache at position {insert_pos}") def add_event(self, event: Event) -> None: From 28437796bec3c407281c2f0af00c8b160555f28d Mon Sep 17 00:00:00 2001 From: simonrosenberg <157206163+simonrosenberg@users.noreply.github.com> Date: Fri, 1 May 2026 13:14:27 -0700 Subject: [PATCH 3/6] style: apply ruff formatting to acp_agent.py --- openhands-sdk/openhands/sdk/agent/acp_agent.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index ed30e036a6d..38d97852c33 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -284,8 +284,15 @@ def _serialize_tool_content(content: list[Any] | None) -> list[dict[str, Any]] | result = [] for c in content: d = c.model_dump(mode="json") if hasattr(c, "model_dump") else c - if isinstance(d, dict) and d.get("type") == "text" and isinstance(d.get("text"), str): - d = {**d, "text": maybe_truncate(d["text"], truncate_after=MAX_ACP_CONTENT_CHARS)} + if ( + isinstance(d, dict) + and d.get("type") == "text" + and isinstance(d.get("text"), str) + ): + d = { + **d, + "text": maybe_truncate(d["text"], truncate_after=MAX_ACP_CONTENT_CHARS), + } result.append(d) return result @@ -514,7 +521,9 @@ def _emit_tool_call_event(self, tc: dict[str, Any]) -> None: try: raw_output = tc.get("raw_output") if isinstance(raw_output, str): - raw_output = maybe_truncate(raw_output, truncate_after=MAX_ACP_CONTENT_CHARS) + raw_output = maybe_truncate( + raw_output, truncate_after=MAX_ACP_CONTENT_CHARS + ) event = ACPToolCallEvent( tool_call_id=tc["tool_call_id"], title=tc["title"], From a0b8f04c8e279714b5b6370ff604bbd8345d7dbe Mon Sep 17 00:00:00 2001 From: simonrosenberg <157206163+simonrosenberg@users.noreply.github.com> Date: Fri, 1 May 2026 13:14:38 -0700 Subject: [PATCH 4/6] style: apply ruff formatting to remote_conversation.py --- .../openhands/sdk/conversation/impl/remote_conversation.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py index 09b108972a6..afdb5418ebc 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py @@ -364,7 +364,9 @@ def _add_event_unsafe(self, event: Event) -> None: self._cached_events[i] = event self._cached_event_ids.discard(existing_id) self._cached_event_ids.add(event.id) - self._acp_tool_call_id_to_event_id[event.tool_call_id] = event.id + self._acp_tool_call_id_to_event_id[event.tool_call_id] = ( + event.id + ) logger.debug( f"Replaced ACP tool call event {existing_id} -> {event.id} " f"(tool_call_id={event.tool_call_id})" From e706860a390c77f1f1b909be25d3d00901ab36eb Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Fri, 1 May 2026 16:47:16 -0700 Subject: [PATCH 5/6] review: descriptive variable names, stale-index cleanup, and regression tests - Rename c/d to content_block/block_dict in _serialize_tool_content (neubig) - Warn and clean up stale _acp_tool_call_id_to_event_id entry when the indexed event is missing from _cached_events (all-hands-bot) - Add 13 unit tests covering dedup by tool_call_id, thread safety, stale index recovery, and content truncation via _serialize_tool_content Co-Authored-By: Claude Sonnet 4.6 --- .../openhands/sdk/agent/acp_agent.py | 24 ++- .../conversation/impl/remote_conversation.py | 9 + openhands-sdk/openhands/sdk/tests/__init__.py | 0 .../tests/test_acp_dedup_and_truncation.py | 190 ++++++++++++++++++ 4 files changed, 214 insertions(+), 9 deletions(-) create mode 100644 openhands-sdk/openhands/sdk/tests/__init__.py create mode 100644 openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index 38d97852c33..3683de5cb85 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -282,18 +282,24 @@ def _serialize_tool_content(content: list[Any] | None) -> list[dict[str, Any]] | if not content: return None result = [] - for c in content: - d = c.model_dump(mode="json") if hasattr(c, "model_dump") else c + for content_block in content: + block_dict = ( + content_block.model_dump(mode="json") + if hasattr(content_block, "model_dump") + else content_block + ) if ( - isinstance(d, dict) - and d.get("type") == "text" - and isinstance(d.get("text"), str) + isinstance(block_dict, dict) + and block_dict.get("type") == "text" + and isinstance(block_dict.get("text"), str) ): - d = { - **d, - "text": maybe_truncate(d["text"], truncate_after=MAX_ACP_CONTENT_CHARS), + block_dict = { + **block_dict, + "text": maybe_truncate( + block_dict["text"], truncate_after=MAX_ACP_CONTENT_CHARS + ), } - result.append(d) + result.append(block_dict) return result diff --git a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py index afdb5418ebc..96c8cf3c0eb 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py @@ -372,6 +372,15 @@ def _add_event_unsafe(self, event: Event) -> None: f"(tool_call_id={event.tool_call_id})" ) return + # Index pointed to an event that is no longer in _cached_events; + # clean up the stale entry so we don't carry it forward. + logger.warning( + f"Stale ACP tool-call index entry: tool_call_id={event.tool_call_id} " + f"pointed to event {existing_id} which is not in _cached_events. " + "Removing stale entry and adding event normally." + ) + self._cached_event_ids.discard(existing_id) + del self._acp_tool_call_id_to_event_id[event.tool_call_id] # Use bisect with key function for O(log N) insertion # This ensures events are always ordered correctly even if diff --git a/openhands-sdk/openhands/sdk/tests/__init__.py b/openhands-sdk/openhands/sdk/tests/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py b/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py new file mode 100644 index 00000000000..ba189b9cb9a --- /dev/null +++ b/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py @@ -0,0 +1,190 @@ +"""Regression tests for ACP tool call deduplication and content truncation. + +Covers: +- RemoteEventsList._add_event_unsafe deduplicates ACPToolCallEvent by tool_call_id +- _serialize_tool_content truncates text blocks to MAX_ACP_CONTENT_CHARS +- _emit_tool_call_event (via _serialize_tool_content) preserves non-text blocks +- Stale index entry is cleaned up and a warning is logged +""" + +from __future__ import annotations + +import logging +import threading +import unittest + +from unittest.mock import MagicMock, patch + +from openhands.sdk.agent.acp_agent import MAX_ACP_CONTENT_CHARS, _serialize_tool_content +from openhands.sdk.conversation.impl.remote_conversation import RemoteEventsList +from openhands.sdk.event.acp_tool_call import ACPToolCallEvent + + +def _make_tool_call_event(tool_call_id: str, raw_output: str = "") -> ACPToolCallEvent: + return ACPToolCallEvent( + tool_call_id=tool_call_id, + title="test tool", + raw_output=raw_output, + ) + + +def _make_events_list() -> RemoteEventsList: + """Return a RemoteEventsList with _do_full_sync stubbed out.""" + with patch.object(RemoteEventsList, "_do_full_sync"): + client = MagicMock() + return RemoteEventsList(client=client, conversation_id="conv-1") + + +class TestACPToolCallDeduplication(unittest.TestCase): + def setUp(self) -> None: + self.events = _make_events_list() + + def _add(self, event: ACPToolCallEvent) -> None: + with self.events._lock: + self.events._add_event_unsafe(event) + + def test_first_event_is_added(self) -> None: + ev = _make_tool_call_event("tc-1", "output-1") + self._add(ev) + self.assertEqual(len(self.events._cached_events), 1) + self.assertIn(ev.id, self.events._cached_event_ids) + + def test_subsequent_events_replace_not_append(self) -> None: + ev1 = _make_tool_call_event("tc-1", "output-1") + ev2 = _make_tool_call_event("tc-1", "output-1-updated") + ev3 = _make_tool_call_event("tc-1", "output-1-final") + self._add(ev1) + self._add(ev2) + self._add(ev3) + + self.assertEqual(len(self.events._cached_events), 1) + last = self.events._cached_events[0] + assert isinstance(last, ACPToolCallEvent) + self.assertEqual(last.raw_output, "output-1-final") + self.assertNotIn(ev1.id, self.events._cached_event_ids) + self.assertNotIn(ev2.id, self.events._cached_event_ids) + self.assertIn(ev3.id, self.events._cached_event_ids) + + def test_different_tool_call_ids_are_kept_separately(self) -> None: + ev_a = _make_tool_call_event("tc-a", "a-output") + ev_b = _make_tool_call_event("tc-b", "b-output") + self._add(ev_a) + self._add(ev_b) + + self.assertEqual(len(self.events._cached_events), 2) + ids = { + e.tool_call_id + for e in self.events._cached_events + if isinstance(e, ACPToolCallEvent) + } + self.assertEqual(ids, {"tc-a", "tc-b"}) + + def test_index_stays_consistent_after_replacement(self) -> None: + ev1 = _make_tool_call_event("tc-1", "v1") + ev2 = _make_tool_call_event("tc-1", "v2") + self._add(ev1) + self._add(ev2) + + self.assertEqual(self.events._acp_tool_call_id_to_event_id["tc-1"], ev2.id) + + def test_stale_index_entry_is_cleaned_up_with_warning(self) -> None: + ev1 = _make_tool_call_event("tc-1", "v1") + self._add(ev1) + + # Manually corrupt state: remove ev1 from _cached_events but leave index intact + self.events._cached_events.clear() + self.events._cached_event_ids.discard(ev1.id) + + ev2 = _make_tool_call_event("tc-1", "v2") + with self.assertLogs("openhands.sdk", level=logging.WARNING) as log_ctx: + self._add(ev2) + + self.assertTrue( + any("Stale" in line for line in log_ctx.output), + "Expected a stale-index warning to be logged", + ) + # ev2 should be inserted normally after cleanup + self.assertEqual(len(self.events._cached_events), 1) + self.assertEqual(self.events._cached_events[0].id, ev2.id) + self.assertEqual(self.events._acp_tool_call_id_to_event_id["tc-1"], ev2.id) + + def test_thread_safety_concurrent_updates(self) -> None: + """Multiple threads racing to update the same tool_call_id must not corrupt state.""" + errors: list[Exception] = [] + + def updater(i: int) -> None: + try: + ev = _make_tool_call_event("tc-shared", f"output-{i}") + self._add(ev) + except Exception as exc: + errors.append(exc) + + threads = [threading.Thread(target=updater, args=(i,)) for i in range(20)] + for t in threads: + t.start() + for t in threads: + t.join() + + self.assertEqual(errors, []) + # Only one event per tool_call_id should survive + tc_events = [ + e + for e in self.events._cached_events + if isinstance(e, ACPToolCallEvent) and e.tool_call_id == "tc-shared" + ] + self.assertEqual(len(tc_events), 1) + + +class TestSerializeToolContentTruncation(unittest.TestCase): + def test_short_text_is_not_truncated(self) -> None: + content = [{"type": "text", "text": "short"}] + result = _serialize_tool_content(content) + assert result is not None + self.assertEqual(result[0]["text"], "short") + + def test_long_text_is_truncated_to_max(self) -> None: + long_text = "x" * (MAX_ACP_CONTENT_CHARS + 5_000) + content = [{"type": "text", "text": long_text}] + result = _serialize_tool_content(content) + assert result is not None + self.assertLessEqual(len(result[0]["text"]), MAX_ACP_CONTENT_CHARS + 200) + + def test_non_text_blocks_are_not_modified(self) -> None: + big_data = "y" * (MAX_ACP_CONTENT_CHARS + 1_000) + content = [{"type": "image_url", "url": big_data}] + result = _serialize_tool_content(content) + assert result is not None + self.assertEqual(result[0]["url"], big_data) + + def test_none_content_returns_none(self) -> None: + self.assertIsNone(_serialize_tool_content(None)) + + def test_empty_content_returns_none(self) -> None: + self.assertIsNone(_serialize_tool_content([])) + + def test_mixed_blocks_only_truncates_text(self) -> None: + long_text = "a" * (MAX_ACP_CONTENT_CHARS + 1_000) + big_url = "b" * (MAX_ACP_CONTENT_CHARS + 1_000) + content = [ + {"type": "text", "text": long_text}, + {"type": "image_url", "url": big_url}, + ] + result = _serialize_tool_content(content) + assert result is not None + self.assertLessEqual(len(result[0]["text"]), MAX_ACP_CONTENT_CHARS + 200) + self.assertEqual(len(result[1]["url"]), MAX_ACP_CONTENT_CHARS + 1_000) + + def test_pydantic_model_content_is_serialized(self) -> None: + """Content blocks that have model_dump() are serialized before truncation check.""" + + class FakeBlock: + def model_dump(self, **_kwargs: object) -> dict: + return {"type": "text", "text": "hello"} + + result = _serialize_tool_content([FakeBlock()]) + assert result is not None + self.assertEqual(result[0]["text"], "hello") + + +if __name__ == "__main__": + unittest.main() From 39b1c3062579c2acf38e1949b321d3faefa43307 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Fri, 1 May 2026 16:55:52 -0700 Subject: [PATCH 6/6] style: fix ruff E501 line-too-long in warning message and docstrings Co-Authored-By: Claude Sonnet 4.6 --- .../openhands/sdk/conversation/impl/remote_conversation.py | 7 ++++--- .../openhands/sdk/tests/test_acp_dedup_and_truncation.py | 5 ++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py index 96c8cf3c0eb..f32f6ea4cd5 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py @@ -375,9 +375,10 @@ def _add_event_unsafe(self, event: Event) -> None: # Index pointed to an event that is no longer in _cached_events; # clean up the stale entry so we don't carry it forward. logger.warning( - f"Stale ACP tool-call index entry: tool_call_id={event.tool_call_id} " - f"pointed to event {existing_id} which is not in _cached_events. " - "Removing stale entry and adding event normally." + "Stale ACP tool-call index entry: " + f"tool_call_id={event.tool_call_id} " + f"pointed to event {existing_id} " + "not found in _cached_events; removing stale entry." ) self._cached_event_ids.discard(existing_id) del self._acp_tool_call_id_to_event_id[event.tool_call_id] diff --git a/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py b/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py index ba189b9cb9a..b989abb5b0c 100644 --- a/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py +++ b/openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py @@ -12,7 +12,6 @@ import logging import threading import unittest - from unittest.mock import MagicMock, patch from openhands.sdk.agent.acp_agent import MAX_ACP_CONTENT_CHARS, _serialize_tool_content @@ -109,7 +108,7 @@ def test_stale_index_entry_is_cleaned_up_with_warning(self) -> None: self.assertEqual(self.events._acp_tool_call_id_to_event_id["tc-1"], ev2.id) def test_thread_safety_concurrent_updates(self) -> None: - """Multiple threads racing to update the same tool_call_id must not corrupt state.""" + """Concurrent updates to the same tool_call_id must not corrupt state.""" errors: list[Exception] = [] def updater(i: int) -> None: @@ -175,7 +174,7 @@ def test_mixed_blocks_only_truncates_text(self) -> None: self.assertEqual(len(result[1]["url"]), MAX_ACP_CONTENT_CHARS + 1_000) def test_pydantic_model_content_is_serialized(self) -> None: - """Content blocks that have model_dump() are serialized before truncation check.""" + """Blocks with model_dump() are serialized before the truncation check.""" class FakeBlock: def model_dump(self, **_kwargs: object) -> dict: