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
18 changes: 11 additions & 7 deletions openhands-sdk/openhands/sdk/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,13 +876,17 @@ async def astep(
)

try:
llm_response = await amake_llm_completion(
self.llm,
_messages,
tools=list(self.tools_map.values()),
on_token=on_token,
call_context=call_context,
)
# Release the state lock for just the network wait so send_message()
# and state snapshots aren't blocked for the whole response. No-op
# unless the run loop holds the lock (e.g. direct astep() in tests).
async with conversation._released_state_lock_during_io():
llm_response = await amake_llm_completion(
self.llm,
_messages,
tools=list(self.tools_map.values()),
on_token=on_token,
call_context=call_context,
)
except FunctionCallValidationError as e:
logger.warning(f"LLM generated malformed function call: {e}")
error_message = MessageEvent(
Expand Down
11 changes: 10 additions & 1 deletion openhands-sdk/openhands/sdk/conversation/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import contextlib
from abc import ABC, abstractmethod
from collections.abc import Iterable, Mapping
from collections.abc import AsyncIterator, Iterable, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, TypeVar, cast

Expand Down Expand Up @@ -226,6 +227,14 @@ async def arun(self) -> None:
"""
self.run()

@contextlib.asynccontextmanager
async def _released_state_lock_during_io(self) -> AsyncIterator[None]:
"""Release any run-loop state lock across an awaited LLM call.

No-op by default; :class:`LocalConversation` overrides it.
"""
yield

@abstractmethod
def set_confirmation_policy(self, policy: ConfirmationPolicyBase) -> None:
"""Set the confirmation policy for the conversation."""
Expand Down
25 changes: 25 additions & 0 deletions openhands-sdk/openhands/sdk/conversation/fifo_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,31 @@ def release(self) -> None:
if self._waiters:
self._waiters[0].notify()

def release_all(self) -> int:
"""Drop all reentrant levels at once, returning the prior depth.

Hands the lock to the next FIFO waiter, so it can be restored later with
:meth:`reacquire`. Raises RuntimeError if not owned by the current thread.
"""
ident = threading.get_ident()
with self._mutex:
if self._owner != ident:
raise RuntimeError("Cannot release lock not owned by current thread")
depth = self._count
self._count = 0
self._owner = None
if self._waiters:
self._waiters[0].notify()
return depth

def reacquire(self, depth: int) -> None:
"""Re-acquire (FIFO-fair) and restore the ``depth`` from release_all()."""
if depth <= 0:
return
self.acquire()
with self._mutex:
self._count = depth

def __enter__(self: Self) -> Self:
"""Context manager entry."""
self.acquire()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1609,6 +1609,31 @@ def _on_event_with_state_lock(self, event: Event) -> None:
with self._state:
self._on_event(event)

@contextlib.asynccontextmanager
async def _released_state_lock_during_io(self):
"""Release the run loop's state lock across an awaited LLM network call.

``arun()`` holds the state lock across the whole step; releasing it for
just the network wait keeps ``send_message()`` and state snapshots
responsive. No-op unless this thread holds the lock, so direct ``astep``
calls are unaffected. Deadlock-safe: ``arun`` is the only holder across
an ``await``; every other holder takes it only briefly.
"""
lock = self._state._lock
if not lock.owned():
yield
return
held_flag = self._step_holds_state_lock
depth = lock.release_all()
# Keep the flag honest while released so a concurrent switch_llm (on the
# event-loop thread) takes the now-free lock instead of racing mutators.
self._step_holds_state_lock = False
try:
yield
finally:
lock.reacquire(depth)
self._step_holds_state_lock = held_flag

@observe(name="conversation.run")
def run(self) -> None:
"""Runs the conversation until the agent finishes.
Expand Down
110 changes: 110 additions & 0 deletions tests/sdk/agent/test_astep_releases_state_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""The conversation state lock must not be held across the LLM network call.

Regression: ``arun()`` holds the conversation state lock across the whole agent
step. Holding it during the LLM round-trip blocked ``send_message()`` and state
snapshots for the full provider response time, so the agent-server appeared to
"stop responding" while waiting for the model. ``Agent.astep`` now releases the
lock for just the network call via
``LocalConversation._released_state_lock_during_io``.
"""

import asyncio
import threading

import pytest
from pydantic import PrivateAttr

from openhands.sdk.agent import Agent
from openhands.sdk.conversation import Conversation
from openhands.sdk.conversation.impl.local_conversation import LocalConversation
from openhands.sdk.llm import LLM
from openhands.sdk.llm.exceptions import LLMContentPolicyViolationError


class _LockProbingLLM(LLM):
"""Records the conversation-lock state observed mid-``acompletion``.

Raises a *recoverable* content-policy error so ``astep`` returns cleanly
without us having to synthesize a full ``LLMResponse``.
"""

_convo_box: list = PrivateAttr(default_factory=list)
_probe: dict = PrivateAttr(default_factory=dict)

def __init__(self):
super().__init__(model="test-model", usage_id="test-llm")

def uses_responses_api(self) -> bool: # override gating
return False

async def acompletion(self, *, messages, tools=None, **kwargs): # type: ignore[override]
convo = self._convo_box[0]
lock = convo._state._lock
# 1) No thread should own the state lock during the network call.
self._probe["locked_during_call"] = lock.locked()
# 2) The run-loop flag must reflect reality (lock is free right now).
self._probe["step_flag_during_call"] = convo._step_holds_state_lock

# 3) A different thread (as send_message runs, via run_in_executor)
# must be able to actually grab the lock while the call is in flight.
acquired: dict = {}

def _try_acquire():
got = lock.acquire(blocking=True, timeout=2.0)
acquired["ok"] = got
if got:
lock.release()

t = threading.Thread(target=_try_acquire)
t.start()
await asyncio.to_thread(t.join)
self._probe["worker_acquired_during_call"] = acquired.get("ok", False)

raise LLMContentPolicyViolationError()


@pytest.mark.asyncio
async def test_astep_releases_state_lock_during_llm_call():
llm = _LockProbingLLM()
agent = Agent(llm=llm, tools=[])
convo = Conversation(agent=agent)
assert isinstance(convo, LocalConversation)
convo._ensure_agent_ready()
llm._convo_box.append(convo)
convo.send_message("hello")

# Mimic arun()'s per-step critical section: hold the state lock across the
# step and set the flag arun sets before calling astep.
convo._step_holds_state_lock = True
with convo._state:
assert convo._state._lock.locked()
await agent.astep(convo, on_event=[].append)
# The context manager restored the lock (same thread) and the flag.
assert convo._state._lock.owned()
assert convo._step_holds_state_lock is True

# The lock was NOT held during the provider round-trip...
assert llm._probe["locked_during_call"] is False
# ...another thread could take it mid-call...
assert llm._probe["worker_acquired_during_call"] is True
# ...and the run-loop flag told the truth while it was released.
assert llm._probe["step_flag_during_call"] is False


@pytest.mark.asyncio
async def test_direct_astep_without_lock_is_unaffected():
"""A direct astep() (no run loop, lock not held) must still work: the
context manager is a no-op when the current thread doesn't own the lock."""
llm = _LockProbingLLM()
agent = Agent(llm=llm, tools=[])
convo = Conversation(agent=agent)
assert isinstance(convo, LocalConversation)
convo._ensure_agent_ready()
llm._convo_box.append(convo)
convo.send_message("hello")

# No `with convo._state:` here — the lock is not held on entry.
await agent.astep(convo, on_event=[].append)

assert llm._probe["locked_during_call"] is False
assert llm._probe["worker_acquired_during_call"] is True
91 changes: 91 additions & 0 deletions tests/sdk/conversation/test_fifo_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,97 @@ def worker(thread_id: int):
return results


def test_release_all_drops_all_reentrant_levels_and_returns_depth():
"""release_all() fully frees a reentrantly-held lock and reports the depth."""
lock = FIFOLock()
lock.acquire()
lock.acquire()
lock.acquire()
assert lock.owned()

depth = lock.release_all()

assert depth == 3
assert not lock.locked()
assert not lock.owned()


def test_release_all_requires_ownership():
"""release_all() from a non-owning thread raises, like release()."""
lock = FIFOLock()

def _grab_and_hold(started: threading.Event, release: threading.Event):
lock.acquire()
started.set()
release.wait()
lock.release()

started, release = threading.Event(), threading.Event()
holder = threading.Thread(target=_grab_and_hold, args=(started, release))
holder.start()
started.wait()
try:
with pytest.raises(RuntimeError):
lock.release_all()
finally:
release.set()
holder.join()


def test_reacquire_restores_reentrancy_depth():
"""reacquire(depth) restores the counter so releases balance out."""
lock = FIFOLock()
lock.acquire()
lock.acquire()
depth = lock.release_all()
assert depth == 2

lock.reacquire(depth)
assert lock.owned()

# Exactly `depth` releases return the lock to fully free.
lock.release()
assert lock.owned() # still held (was reentrant)
lock.release()
assert not lock.owned()


def test_reacquire_zero_depth_is_noop():
lock = FIFOLock()
lock.reacquire(0)
assert not lock.owned()


def test_release_all_then_reacquire_hands_off_to_waiter_first():
"""A thread waiting during the released window gets the lock before the
releaser reacquires (FIFO fairness is preserved across the hand-off)."""
lock = FIFOLock()
lock.acquire()

order: list[str] = []
waiter_ready = threading.Event()

def _waiter():
waiter_ready.set()
with lock:
order.append("waiter")

t = threading.Thread(target=_waiter)
t.start()
waiter_ready.wait()
# Give the waiter a moment to actually enqueue on the lock.
time.sleep(0.05)

depth = lock.release_all()
# Waiter should now be able to take it; reacquire queues behind it.
lock.reacquire(depth)
order.append("releaser")
lock.release()
t.join()

assert order == ["waiter", "releaser"]


if __name__ == "__main__":
print("Running FIFO lock fairness test 100 times sequentially...")

Expand Down
Loading