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
37 changes: 35 additions & 2 deletions openhands-agent-server/openhands/agent_server/event_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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":
Comment thread
VascoSch92 marked this conversation as resolved.
Resolved
self._rerun_requested = True

async def subscribe_to_events(self, subscriber: Subscriber[Event]) -> UUID:
subscriber_id = self._pub_sub.subscribe(subscriber)
Expand Down Expand Up @@ -795,6 +808,26 @@ async def _run_and_publish():
self._run_task = None
await self._publish_state_update()

# 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())

Expand Down
151 changes: 151 additions & 0 deletions tests/agent_server/test_event_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2468,3 +2468,154 @@ 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()})"
)


@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
Comment thread
VascoSch92 marked this conversation as resolved.
Resolved
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
Loading