Repository navigation
fix(sdk): release conversation state lock during the async LLM call - #4009
Conversation
`arun()` holds the conversation state lock (`ConversationState`'s FIFOLock) across the entire agent step, including the `await agent.astep()` LLM round-trip. Because the lock is held on the event-loop thread across that await, every operation that needs the same conversation's state lock — `send_message()` (queuing/interjecting a user message), new WebSocket state snapshots, execution-status reads — blocks in a worker thread until the model responds. Under load those blocked worker threads can saturate the shared default ThreadPoolExecutor, at which point even lock-free reads queue and the agent-server appears to "stop responding to all requests" while waiting on the LLM. The event loop itself is not blocked (the LLM transport is genuinely async via `litellm.acompletion`); the problem is the per-conversation lock scope. The ACP run path already releases the lock during its prompt round-trip for exactly this reason — this brings the regular LLM path in line, but narrowly: only the network wait runs unlocked, so `astep`'s in-memory prep and response-processing still run under the lock unchanged. - FIFOLock: add `release_all()`/`reacquire(depth)` to hand a reentrantly-held lock across an awaited call and restore it at the same depth. - LocalConversation._released_state_lock_during_io(): async CM that drops the run loop's lock for the LLM call and restores it; no-op unless the current thread owns the lock (direct astep() in tests is unaffected). Also flips `_step_holds_state_lock` to False for the window so a concurrent switch_llm (which runs on the event-loop thread) takes the now-free lock instead of skipping it and racing worker-thread mutators. - BaseConversation: no-op default of the CM so non-local conversations and sync-only subclasses are unaffected. - Agent.astep: wrap only `amake_llm_completion` in the CM. Safe against deadlock: `arun` is the only coroutine that holds this lock across an await, so after this change nothing does; every other holder (worker threads via run_in_executor, short synchronous event-loop sections) takes it only briefly, so re-acquire cannot block for long.
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||||||||||||||||||||||
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The async SDK conversation path now accepts a follow-up send_message() immediately while the LLM call is still in flight.
Does this PR achieve its stated goal?
Yes. The stated goal is to stop the conversation state lock from blocking same-conversation operations during an async LLM round trip. I reproduced the old behavior on origin/main, where send_message() did not complete within 0.5s while the slow LLM call was in progress, then reran the same real SDK conversation flow on ce7ced5, where send_message() completed in 0.001s before releasing the LLM call.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed and installed the uv-managed dev environment. |
| CI Status | 🟡 gh pr checks reported 28 successful, 2 skipped, 0 failing, and 1 pending check at observation time. |
| Functional Verification | ✅ Before/after SDK execution confirmed the lock no longer blocks follow-up messages during async LLM I/O. |
Functional Verification
Test 1: Send a follow-up message while an async LLM call is in flight
I used a temporary SDK script that creates a real Conversation, starts conversation.arun() with a custom slow LLM.acompletion(), waits until the LLM call is active, then calls conversation.send_message() from a worker thread while the LLM call is still waiting. This exercises the user-facing SDK path rather than the test suite.
Step 1 — Reproduce / establish baseline without the fix:
Checked out origin/main (91f8b940) and ran:
git checkout --detach origin/main
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_conversation_lock_responsiveness.py 2>&1 \
| grep -E '^(llm_call|send_message|arun|llm_calls)'Observed:
llm_call_entered=True
send_message_completed_within_0.5s=False
send_message_elapsed_before_release=0.501s
send_message_total_elapsed=0.507s
send_message_error=None
send_message_result_type=NoneType
arun_error=None
llm_calls=1
This confirms the bug: once the LLM call was in flight, the follow-up send_message() could not complete within the 0.5s responsiveness window. It only returned after the script released the slow LLM call.
Step 2 — Apply the PR's changes:
Checked out the PR branch at ce7ced587f6c068667889f8bfdad2d7b58215340.
Step 3 — Re-run with the fix in place:
Ran the same command:
git checkout vasco/release-state-lock-during-llm-call
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_conversation_lock_responsiveness.py 2>&1 \
| grep -E '^(llm_call|send_message|arun|llm_calls)'Observed:
llm_call_entered=True
send_message_completed_within_0.5s=True
send_message_elapsed_before_release=0.001s
send_message_total_elapsed=0.001s
send_message_error=None
send_message_result_type=NoneType
arun_error=None
llm_calls=1
This confirms the fix works for the PR's core behavior: while the model call was still blocked, send_message() completed immediately and the conversation run still completed without error after the slow LLM returned.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
HUMAN:
Fixing problem with lock in
agent.step()AGENT:
Why
The agent-server appears to stop responding to requests while it is waiting for an LLM response.
Root cause is lock scope: in the regular (non-ACP) run path,
arun()holds the per-conversationConversationStateFIFOLock across the entireawait agent.astep(), i.e. across the whole LLM round-trip. Because that lock is held on the event-loop thread across the await, every operation that needs the same conversation's lock blocks (in a worker thread) until the model responds:send_message()— you cannot queue/interject a follow-up during a model turn.Those blocked ops run on the shared default
ThreadPoolExecutor; under concurrency they saturate it, at which point even lock-free reads queue behind them and the server looks fully unresponsive. The ACP run path already releases the lock during its round-trip for exactly this reason — this PR brings the regular LLM path in line.Summary
FIFOLock: addrelease_all()/reacquire(depth)to hand a reentrantly-held lock across an awaited call and restore it at the same depth.LocalConversation._released_state_lock_during_io(): async context manager that drops the run loop's lock for just the network wait and restores it. No-op unless the current thread owns the lock, so directastep()calls (tests/custom drivers) are unaffected. Flips_step_holds_state_locktoFalsefor the window so a concurrentswitch_llmtakes the now-free lock instead of racing worker-thread mutators.BaseConversation: no-op default of the CM (non-local / sync-only subclasses unaffected).Agent.astep: wrap onlyamake_llm_completionin the CM.Issue Number
N/A (reported in Slack, no GitHub issue filed).
How to Test
Automated — the two test files added in this PR:
uv run pytest tests/sdk/conversation/test_fifo_lock.py tests/sdk/agent/test_astep_releases_state_lock.py -q # 14 passed in 2.52stest_fifo_lock.py—release_all/reacquire: depth reporting, ownership enforcement, reentrancy restoration, and FIFO hand-off to a waiter across the released window.test_astep_releases_state_lock.py— drivesastepinside a simulatedaruncritical section with an LLM whoseacompletionprobes the lock mid-call; asserts the lock is not held during the call, a separate thread can acquire it, and_step_holds_state_lockreadsFalse. This regression test fails onmain(lock held → worker thread times out) and passes with the fix (verified by reverting onlyagent.py).Manual / integration:
POST .../eventsor the events WebSocket) — it should be accepted immediately instead of hanging until the response returns.Video/Screenshots
N/A (backend concurrency fix, no UI surface).
Type
Notes
step/runfallback still holds the lock acrossmake_llm_completion. It runs in a worker thread so it can't freeze the event loop, but it does block worker-threadsend_message. A sync twin of the CM would give parity; the async path is the default.aprepare_llm_messagesis still awaited under the lock, but it defers condensation viaCondensationRequestrather than making an inline LLM call, so it's fine.litellm.modify_paramslock) — complementary to this change, not overlapping.Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:ce7ced5-pythonRun
All tags pushed for this build
About Multi-Architecture Support
ce7ced5-python) is a multi-arch manifest supporting both amd64 and arm64ce7ced5-python-amd64) are also available if needed