diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index d4c85c16aba..9b2dd037990 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -76,13 +76,17 @@ def get_conversation(self): return self._conversation def _get_event_sync(self, event_id: str) -> Event | None: - """Private sync function to get event with state lock.""" + """Private sync function to get a single event. + + Reads directly from the EventLog without acquiring the state lock. + EventLog reads are safe without the FIFOLock because events are + append-only and immutable once written. + """ if not self._conversation: raise ValueError("inactive_service") - with self._conversation._state as state: - index = state.events.get_index(event_id) - event = state.events[index] - return event + events = self._conversation._state.events + index = events.get_index(event_id) + return events[index] async def get_event(self, event_id: str) -> Event | None: if not self._conversation: @@ -101,7 +105,12 @@ def _search_events_sync( timestamp__gte: datetime | None = None, timestamp__lt: datetime | None = None, ) -> EventPage: - """Private sync function to search events with state lock.""" + """Private sync function to search events. + + Reads directly from the EventLog without acquiring the state lock. + EventLog reads are safe without the FIFOLock because events are + append-only and immutable once written. + """ if not self._conversation: raise ValueError("inactive_service") @@ -111,35 +120,30 @@ def _search_events_sync( # Collect all events all_events = [] - with self._conversation._state as state: - for event in state.events: - # Apply kind filter if provided - if ( - kind is not None - and f"{event.__class__.__module__}.{event.__class__.__name__}" - != kind - ): - continue - - # Apply source filter if provided - if source is not None and event.source != source: - continue + for event in self._conversation._state.events: + # Apply kind filter if provided + if ( + kind is not None + and f"{event.__class__.__module__}.{event.__class__.__name__}" != kind + ): + continue - # Apply body filter if provided (case-insensitive substring match) - if body is not None: - if not self._event_matches_body(event, body): - continue + # Apply source filter if provided + if source is not None and event.source != source: + continue - # Apply timestamp filters if provided (ISO string comparison) - if ( - timestamp_gte_str is not None - and event.timestamp < timestamp_gte_str - ): - continue - if timestamp_lt_str is not None and event.timestamp >= timestamp_lt_str: + # Apply body filter if provided (case-insensitive substring match) + if body is not None: + if not self._event_matches_body(event, body): continue - all_events.append(event) + # Apply timestamp filters if provided (ISO string comparison) + if timestamp_gte_str is not None and event.timestamp < timestamp_gte_str: + continue + if timestamp_lt_str is not None and event.timestamp >= timestamp_lt_str: + continue + + all_events.append(event) # Sort events based on sort_order if sort_order == EventSortOrder.TIMESTAMP: @@ -205,7 +209,12 @@ def _count_events_sync( timestamp__gte: datetime | None = None, timestamp__lt: datetime | None = None, ) -> int: - """Private sync function to count events with state lock.""" + """Private sync function to count events. + + Reads directly from the EventLog without acquiring the state lock. + EventLog reads are safe without the FIFOLock because events are + append-only and immutable once written. + """ if not self._conversation: raise ValueError("inactive_service") @@ -214,35 +223,30 @@ def _count_events_sync( timestamp_lt_str = timestamp__lt.isoformat() if timestamp__lt else None count = 0 - with self._conversation._state as state: - for event in state.events: - # Apply kind filter if provided - if ( - kind is not None - and f"{event.__class__.__module__}.{event.__class__.__name__}" - != kind - ): - continue - - # Apply source filter if provided - if source is not None and event.source != source: - continue + for event in self._conversation._state.events: + # Apply kind filter if provided + if ( + kind is not None + and f"{event.__class__.__module__}.{event.__class__.__name__}" != kind + ): + continue - # Apply body filter if provided (case-insensitive substring match) - if body is not None: - if not self._event_matches_body(event, body): - continue + # Apply source filter if provided + if source is not None and event.source != source: + continue - # Apply timestamp filters if provided (ISO string comparison) - if ( - timestamp_gte_str is not None - and event.timestamp < timestamp_gte_str - ): - continue - if timestamp_lt_str is not None and event.timestamp >= timestamp_lt_str: + # Apply body filter if provided (case-insensitive substring match) + if body is not None: + if not self._event_matches_body(event, body): continue - count += 1 + # Apply timestamp filters if provided (ISO string comparison) + if timestamp_gte_str is not None and event.timestamp < timestamp_gte_str: + continue + if timestamp_lt_str is not None and event.timestamp >= timestamp_lt_str: + continue + + count += 1 return count diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 0ec59fb033f..a861d34edcb 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -1,4 +1,6 @@ import asyncio +import threading +import time from datetime import UTC, datetime from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch @@ -1577,3 +1579,85 @@ async def rapid_updates(): assert len(events_received) == 5, ( f"Expected 5 events, got {len(events_received)}" ) + + +class TestSearchEventsBlockedByRunLoop: + """Reproduce: search_events blocks for the entire duration of agent.step(). + + The run loop in LocalConversation.run() holds the FIFOLock on + ConversationState for each iteration (including the LLM call and tool + execution). EventService._search_events_sync() acquires the *same* lock + to iterate events, so it blocks until the step finishes. + + See HANG_REPRO.md for the full write-up. + """ + + @pytest.mark.asyncio + async def test_search_events_not_blocked_by_state_lock( + self, sample_stored_conversation + ): + """search_events must return promptly even while the run loop holds the lock. + + This simulates the real scenario: LocalConversation.run() holds + ``_state`` (FIFOLock) for the entire agent step, while + ``_search_events_sync`` tries to acquire the same lock in a + thread-pool executor. + + The expected (fixed) behaviour is that the read path does NOT + contend on the write lock, so search_events returns in well + under a second regardless of how long the step takes. + """ + service = EventService( + stored=sample_stored_conversation, + conversations_dir=Path("test_conversation_dir"), + ) + + conversation = MagicMock(spec=Conversation) + state = MagicMock(spec=ConversationState) + + real_lock = FIFOLock() + state._lock = real_lock + state.__enter__ = lambda self: (real_lock.acquire(), self)[1] + state.__exit__ = lambda self, *args: real_lock.release() + state.events = [ + MessageEvent(id=f"evt-{i}", source="user", llm_message=Message(role="user")) + for i in range(3) + ] + state.execution_status = ConversationExecutionStatus.RUNNING + conversation._state = state + service._conversation = conversation + + hold_seconds = 2.0 + lock_acquired = threading.Event() + + def hold_lock_like_run_loop(): + """Simulate LocalConversation.run() holding the lock during step.""" + with state: + lock_acquired.set() + time.sleep(hold_seconds) + + # Start the "run loop" thread that holds the lock + run_thread = threading.Thread(target=hold_lock_like_run_loop, daemon=True) + run_thread.start() + lock_acquired.wait(timeout=5.0) + + # search_events should return quickly even though the lock is held + t0 = time.monotonic() + result = await service.search_events() + elapsed = time.monotonic() - t0 + + run_thread.join(timeout=5.0) + + # search_events returned correct data + assert len(result.items) == 3 + + # The critical assertion: search_events must NOT be blocked by the + # run-loop's lock. If it takes anywhere near hold_seconds, the read + # path is still contending on the write lock (the bug in HANG_REPRO.md). + max_acceptable = 0.5 + assert elapsed < max_acceptable, ( + f"search_events took {elapsed:.3f}s, but should return in " + f"<{max_acceptable}s even while the run loop holds the state lock " + f"for {hold_seconds}s. The read path is blocked by the write lock " + f"(see HANG_REPRO.md)." + )