From e7a4ba54132241d80f7c8440318ad10c6c1aafb7 Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Fri, 22 May 2026 22:07:59 +0200 Subject: [PATCH 1/2] fix(agent-server): re-run input stranded in a finished run's cleanup tail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A user message delivered over the events WebSocket while the previous run is still in its _run_and_publish wait_for_pending tail had its run() rejected as conversation_already_running and suppressed, and nothing re-ran it once the tail cleared — so the message sat unprocessed until the next send (no agent response; resend appears to work). The in-flight case is already handled by LocalConversation.run(); this closes the post-run executor-tail gap. Re-arm a run at the end of _run_and_publish when the conversation is left IDLE, which only happens when send_message reset a terminal FINISHED/STUCK status during the tail (pending input, no run scheduled). Zero overhead on the normal path, where status is FINISHED. Refs #3363 --- .../openhands/agent_server/event_service.py | 19 +++++ tests/agent_server/test_event_service.py | 85 +++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index 70e329a1d4c..9f1fe4193c7 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -795,6 +795,25 @@ async def _run_and_publish(): self._run_task = None await self._publish_state_update() + # Re-arm a run for input that landed while this one was + # wrapping up. LocalConversation.run() deliberately keeps + # looping on FINISHED so a message arriving *mid-run* is + # absorbed; but once the loop has fully exited there is a + # gap — this task's wait_for_pending() tail above — in which + # an incoming send_message(run=True) has its run() rejected + # as "conversation_already_running" and suppressed (see + # send_message). send_message() resets the terminal + # FINISHED/STUCK status to IDLE, so an IDLE status here means + # exactly that: unprocessed input with no run scheduled. + # Kick one off so the message isn't stranded until the user + # sends again. + if ( + await self._get_execution_status() + == ConversationExecutionStatus.IDLE + ): + with suppress(ValueError): + await self.run() + # Create task but don't await it - runs in background self._run_task = asyncio.create_task(_run_and_publish()) diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 20ac59329b7..ceda565bfc7 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -2468,3 +2468,88 @@ def run(): ) emit_mock = cast(MagicMock, service._emit_event_from_thread) emit_mock.assert_called_once() + + +@pytest.mark.timeout(30) +async def test_message_in_run_cleanup_tail_is_not_stranded( + real_conversation_service, tmp_path, monkeypatch +): + """A message that lands while a *finished* run is still in its + ``wait_for_pending()`` cleanup tail must still be processed. + + Regression test for a stranded-message race: ``send_message(run=True)`` + suppresses run()'s ``conversation_already_running`` while ``_run_task`` is + wrapping up, and without the re-arm in ``_run_and_publish`` nothing re-runs + once the tail clears — so the message sits unprocessed until the next send. + + Not the in-flight case: ``LocalConversation.run`` deliberately keeps looping + on FINISHED so a message arriving *during* a step is absorbed. The unguarded + gap is strictly the post-run executor tail owned by ``_run_and_publish``. + """ + (tmp_path / "ws").mkdir() + # One scripted reply per user message; each is plain text (no tool calls) + # so the agent finishes the turn immediately. ``_call_count`` tells us how + # many turns actually ran. + parent_llm = SlowTestLLM.from_messages( + [text_message("reply one"), text_message("reply two")], + latency_s=0.0, + ) + info = await start_conversation_with_test_llm( + real_conversation_service, + parent_llm=parent_llm, + workspace_dir=str(tmp_path / "ws"), + usage_id="tail-strand", + initial_text=None, + ) + es = await real_conversation_service.get_event_service(info.id) + assert es is not None and es._callback_wrapper is not None + + # Park every run in its wait_for_pending() tail until released. It runs in + # a thread-pool worker, so block on a threading.Event there and signal + # entry back to the test. + entered_tail = threading.Event() + release_tail = threading.Event() + + def _blocking_wait(timeout: float) -> None: + entered_tail.set() + release_tail.wait(timeout) + + monkeypatch.setattr(es._callback_wrapper, "wait_for_pending", _blocking_wait) + + # Turn 1: the agent answers "first", finishes (FINISHED), then the run + # task parks in our blocking wait_for_pending(). + await es.send_message( + Message(role="user", content=[TextContent(text="first")]), run=True + ) + assert await asyncio.to_thread(entered_tail.wait, 10.0), ( + "first run never reached its wait_for_pending tail" + ) + first_run_task = es._run_task + assert first_run_task is not None + assert parent_llm._call_count == 1 + assert await es._get_execution_status() == ConversationExecutionStatus.FINISHED + + # Turn 2 arrives DURING the tail: send_message appends it and resets the + # terminal status to IDLE, then run() is rejected (task not done) and + # suppressed. Nothing runs yet. + await es.send_message( + Message(role="user", content=[TextContent(text="second")]), run=True + ) + assert parent_llm._call_count == 1, "second turn ran before the tail cleared?!" + assert es._run_task is first_run_task, "a second run started concurrently" + + # Release the tail; the first run task finishes and clears _run_task. + release_tail.set() + await first_run_task + + # The second message must now get processed. Without the _run_and_publish + # re-arm it is stranded (call_count stays 1, status stuck IDLE). + deadline = time.monotonic() + 5.0 + while parent_llm._call_count < 2 and time.monotonic() < deadline: + await asyncio.sleep(0.05) + + assert parent_llm._call_count == 2, ( + "second message was stranded — the agent never ran for it after the " + f"first run's cleanup tail cleared (call_count={parent_llm._call_count}, " + f"status={await es._get_execution_status()})" + ) From c51e48829d5f065100102485e56b528132f07a6b Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Fri, 22 May 2026 22:20:17 +0200 Subject: [PATCH 2/2] address review: track explicit run intent for the cleanup-tail re-arm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Using IDLE as the proxy for a suppressed send_message(run=True) was too broad: a deliberate run=False append (a real HTTP path via event_router) or an IDLE reached another way (e.g. confirmation rejection) would wrongly trigger a run. Track request intent instead — set _rerun_requested only when a run=True is rejected as conversation_already_running, and consume it in _run_and_publish (still gated on IDLE so an already-absorbed message doesn't re-run). Add a run=False-during-tail regression test. Refs #3363 --- .../openhands/agent_server/event_service.py | 54 +++++++++------ tests/agent_server/test_event_service.py | 66 +++++++++++++++++++ 2 files changed, 100 insertions(+), 20 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index 9f1fe4193c7..0a5a501008c 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -68,6 +68,9 @@ class EventService: default_factory=lambda: PubSub[Event](max_subscribers=50), init=False ) _run_task: asyncio.Task | None = field(default=None, init=False) + # Set when a send_message(run=True) is rejected because a run is still + # wrapping up; consumed by _run_and_publish to re-run the stranded message. + _rerun_requested: bool = field(default=False, init=False) _run_lock: asyncio.Lock = field(default_factory=asyncio.Lock, init=False) _callback_wrapper: AsyncCallbackWrapper | None = field(default=None, init=False) _lease: ConversationLease | None = field(default=None, init=False) @@ -419,9 +422,19 @@ async def send_message(self, message: Message, run: bool = False): loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.send_message, message) if run: - # Already running or inactive — message was sent, skip run. - with suppress(ValueError): + try: await self.run() + except ValueError as e: + # run() refused. If a run is still wrapping up (its + # wait_for_pending tail), the message we just appended won't be + # picked up by it, so record explicit run intent for + # _run_and_publish to honor once that task clears. Tracking the + # request — rather than inferring it later from an IDLE status — + # is what keeps a deliberate run=False append, or an IDLE reached + # via another path, from triggering an unwanted run. + # "inactive_service" is terminal and must not re-arm. + if str(e) == "conversation_already_running": + self._rerun_requested = True async def subscribe_to_events(self, subscriber: Subscriber[Event]) -> UUID: subscriber_id = self._pub_sub.subscribe(subscriber) @@ -795,24 +808,25 @@ async def _run_and_publish(): self._run_task = None await self._publish_state_update() - # Re-arm a run for input that landed while this one was - # wrapping up. LocalConversation.run() deliberately keeps - # looping on FINISHED so a message arriving *mid-run* is - # absorbed; but once the loop has fully exited there is a - # gap — this task's wait_for_pending() tail above — in which - # an incoming send_message(run=True) has its run() rejected - # as "conversation_already_running" and suppressed (see - # send_message). send_message() resets the terminal - # FINISHED/STUCK status to IDLE, so an IDLE status here means - # exactly that: unprocessed input with no run scheduled. - # Kick one off so the message isn't stranded until the user - # sends again. - if ( - await self._get_execution_status() - == ConversationExecutionStatus.IDLE - ): - with suppress(ValueError): - await self.run() + # Re-arm a run for input stranded while this task was + # wrapping up. A send_message(run=True) that arrived during + # the wait_for_pending() tail above had its run() rejected as + # "conversation_already_running" and suppressed, setting + # _rerun_requested. Honor it only while the conversation is + # still IDLE — i.e. that message is genuinely pending. If the + # run loop was still alive it already absorbed the message + # (LocalConversation.run() keeps looping on FINISHED) and we + # are FINISHED here, so the IDLE guard avoids a redundant run. + # A deliberate run=False append, or an IDLE reached via + # another path, never sets the flag. + if self._rerun_requested: + self._rerun_requested = False + if ( + await self._get_execution_status() + == ConversationExecutionStatus.IDLE + ): + with suppress(ValueError): + await self.run() # Create task but don't await it - runs in background self._run_task = asyncio.create_task(_run_and_publish()) diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index ceda565bfc7..2058052c10f 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -2553,3 +2553,69 @@ def _blocking_wait(timeout: float) -> None: f"first run's cleanup tail cleared (call_count={parent_llm._call_count}, " f"status={await es._get_execution_status()})" ) + + +@pytest.mark.timeout(30) +async def test_run_false_message_in_cleanup_tail_is_not_run( + real_conversation_service, tmp_path, monkeypatch +): + """A run=False append landing in the cleanup tail must NOT be auto-run. + + Guards the explicit-intent contract behind the re-arm: send_message( + run=False) appends without running, and _run_and_publish must not + resurrect it just because send_message reset the terminal status to IDLE. + """ + (tmp_path / "ws").mkdir() + # Two scripted replies, but only the first turn should ever run. + parent_llm = SlowTestLLM.from_messages( + [text_message("reply one"), text_message("must not run")], + latency_s=0.0, + ) + info = await start_conversation_with_test_llm( + real_conversation_service, + parent_llm=parent_llm, + workspace_dir=str(tmp_path / "ws"), + usage_id="tail-run-false", + initial_text=None, + ) + es = await real_conversation_service.get_event_service(info.id) + assert es is not None and es._callback_wrapper is not None + + entered_tail = threading.Event() + release_tail = threading.Event() + + def _blocking_wait(timeout: float) -> None: + entered_tail.set() + release_tail.wait(timeout) + + monkeypatch.setattr(es._callback_wrapper, "wait_for_pending", _blocking_wait) + + # Turn 1 runs and parks in the wait_for_pending tail. + await es.send_message( + Message(role="user", content=[TextContent(text="first")]), run=True + ) + assert await asyncio.to_thread(entered_tail.wait, 10.0), ( + "first run never reached its wait_for_pending tail" + ) + first_run_task = es._run_task + assert first_run_task is not None + assert parent_llm._call_count == 1 + + # Append a message with run=False during the tail: the caller explicitly + # does NOT want a run. It resets the terminal status to IDLE but must not + # set the re-run flag. + await es.send_message( + Message(role="user", content=[TextContent(text="just append")]), run=False + ) + assert es._rerun_requested is False + + # Release the tail and let the run task settle; nothing should re-run. + release_tail.set() + await first_run_task + await asyncio.sleep(0.3) # give any erroneous re-arm a chance to fire + + assert parent_llm._call_count == 1, ( + "run=False append in the cleanup tail was unexpectedly run " + f"(call_count={parent_llm._call_count})" + ) + assert es._run_task is None