Repository navigation
fix(agent-server): stop lost to a queued re-arm; event-socket replay races - #6577
Conversation
A send_message(run=True) that lands in a run's wait_for_pending tail is parked, and the tail re-arms with run(wait_for_capacity=True) after settle() already returned the permit. run() checked _closing and the interrupt generation before RunSlot.acquire and never after, so a pause, interrupt or close that landed while the re-arm waited for capacity was overridden once a permit freed: a paused conversation went back to RUNNING, and a closed or deleted one ran again, writing base_state.json and events into the deleted directory without lease fencing. run() now records the stop generation on entry and, after its last await, drops the request (returning any permit it just took) if a stop landed.
The run thread appends an event under the state lock and only then schedules its fan-out. The session socket reads its mark (len(events)) without the lock, so the mark can cover an event whose publish is still unscheduled. Replay sends that event from disk, and its late publish then reached the live subscriber, which only deduped the buffer flush: the client got the event twice. _SessionSubscriber now keeps through_seq after go_live and drops any durable event at or below it on the live path as well.
Five confirmed issues in how sockets receive conversation events: - /sockets/events subscribed, then replayed with no buffering or dedup, so an event published during the replay (or saved just before subscribe with its fan-out still queued) arrived ahead of older history and again from the replay. With resend_mode set, live events are now buffered until the replay is done and deduped by id; the connect snapshot still goes out first. - subscribe_to_events registered the subscriber before the snapshot and initial push; a failure there left the registration behind (the caller never got the id). 50 such failures refused every new socket and kept the conversation from idle eviction. It now unsubscribes on any failure. - Socket subscribers had no close(), so closing a conversation (delete, eviction, shutdown) left their sockets open with nothing more to deliver. Both now end the handler and close with 1001 "conversation_closed". - PubSub.close() let one failing subscriber.close() abort it before clear() (and EventService.close() before the lease release), and dropped a subscriber registered meanwhile without closing it. It now collects errors and repeats until empty. - /sockets/session read its replay mark after the connect snapshot, without the lock, so it could replay state newer than the snapshot it then sent last. The snapshot and the log length it reflects are now read under one state-lock hold (Subscriber.on_initial_state), replay stops there, and events the snapshot does not reflect are kept after it.
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
|||||||||||||||||||||||||||||||||||
…trim comments and tests
enyst
left a comment
There was a problem hiding this comment.
Hi, I'm Codex, an AI coding assistant reviewing this PR at Engel's request.
I reviewed 5362b3dd1 and found one remaining replay regression.
[P2] Buffered full-state snapshots can overwrite newer replayed state — sockets.py:569–573.
A full-state snapshot published during replay is transient, so its ID never enters _replayed_ids. If replay also includes a newer persisted status update, go_live() drops that update's buffered duplicate but sends the older snapshot afterward. Consumers applying full-state snapshots are left with stale state.
I reproduced this by connecting with resend_mode="all", holding the replay search, running the conversation to completion, then sending another message with run=False before releasing replay. On this head, the server ends IDLE but the received state ends FINISHED. Repeating the same workflow with the base implementation (e4160d118) ends IDLE / IDLE.
Please preserve the ordering between replayed state changes and buffered transient snapshots; deduplicating persisted event IDs alone loses that ordering.
Reproduction script and observed output
Run from this PR checkout after make build. Save the script below as /tmp/repro_6577.py, then run:
PYTHONPATH="$PWD" uv run python /tmp/repro_6577.pyThis uses the PR's existing test helpers, a real ConversationService and LocalConversation.arun(), and a scripted test LLM. The socket transport is the test fake, not a real network connection; CLIENT is computed by applying the received state frames, not by a connected RemoteConversation. The replay-search gate controls only the interleaving; the run and message paths generate the state changes and snapshot.
import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from openhands.agent_server import sockets
from openhands.agent_server.conversation_service import ConversationService
from openhands.sdk import Message, TextContent
from tests.agent_server.stress.scripts import (
SlowTestLLM,
start_conversation_with_test_llm,
text_message,
)
from tests.agent_server.test_event_socket_races import _FakeWS, _legacy, _wait_until
async def main():
with TemporaryDirectory() as d:
async with ConversationService(
conversations_dir=Path(d) / "conversations"
) as owner:
info = await start_conversation_with_test_llm(
owner,
parent_llm=SlowTestLLM.from_messages([text_message("done")]),
workspace_dir=str(Path(d) / "workspace"),
usage_id="repro",
)
svc = await owner.get_event_service(info.id)
gate, in_replay = asyncio.Event(), asyncio.Event()
original_search = svc.search_events
async def held_search(*args, **kwargs):
in_replay.set()
await gate.wait()
return await original_search(*args, **kwargs)
async def get_event_service(cid):
return svc
ws = _FakeWS()
with (
patch.object(svc, "search_events", held_search),
patch.object(
sockets,
"conversation_service",
SimpleNamespace(get_event_service=get_event_service),
),
):
task = asyncio.create_task(_legacy(ws, svc, resend_mode="all"))
await in_replay.wait()
await svc.run()
await svc.wait_for_run_completion(10)
await svc.send_message(
Message(role="user", content=[TextContent(text="next")]), run=False
)
await asyncio.to_thread(svc._callback_wrapper.wait_for_pending, 5)
server_status = svc.get_conversation().state.execution_status
gate.set()
await _wait_until(
lambda: any(
f.get("kind") == "MessageEvent"
and any(
c.get("text") == "next"
for c in f.get("llm_message", {}).get("content", [])
)
for f in ws.sent
)
)
await asyncio.sleep(0.1)
status = None
trace = []
for f in ws.sent:
if f.get("kind") == "ConversationStateUpdateEvent":
if f["key"] == "full_state":
status = f["value"]["execution_status"]
trace.append(("snapshot", status))
elif f["key"] == "execution_status":
status = f["value"]
trace.append(("persisted", status))
print("TRACE", trace)
print("SERVER", server_status, "CLIENT", status)
ws.disconnect.set()
await task
asyncio.run(main())Observed on 5362b3dd1:
TRACE [('snapshot', 'idle'), ('persisted', 'running'), ('persisted', 'finished'), ('persisted', 'idle'), ('snapshot', 'finished')]
SERVER ConversationExecutionStatus.IDLE CLIENT finished
The final finished snapshot is older than the replayed idle update. With the base implementation, the final line is:
SERVER ConversationExecutionStatus.IDLE CLIENT idle
Validation: 63 passed, 1 skipped across the three focused agent-server test files and the full live-server suite. Separate base/head reproductions using the actual run loop also confirmed that the queued pause/delete fixes work: pause remains PAUSED, deletion does not recreate the directory, and capacity is returned.
|
@enyst Fixed :-) |
enyst
left a comment
There was a problem hiding this comment.
Hi, I'm Codex, an AI coding assistant following up at Engel's request after a fresh review of 05dd2ac48.
The earlier FINISHED/IDLE finding is fixed; I reran that repro successfully.
These two follow-up observations are non-blocking and left to your judgment. Engel considers them minor and thinks they may not be worth the additional complexity, especially the legacy streaming path, which is already on the retirement plan in #4683. Please decide whether either merits a change here or is better left as a known limitation.
1. Session socket: an older connect snapshot can still overwrite newer state metadata.
At session_socket.py:256–259, an event absent from the durable log is classified as older. That also applies to a full-state snapshot captured after the connect snapshot.
With a real loopback WebSocket, a normal send_message(..., run=True), and a scripted LLM, holding only the connect snapshot's return produced:
newer full_state: finished, activated_knowledge_skills=['python_tips']
older connect full_state: idle, activated_knowledge_skills=[]
durable execution_status: running
durable execution_status: finished
server activated_knowledge_skills = ['python_tips']
received state activated_knowledge_skills = []
The status updates repair execution status, but the skills list is mutated in place and has no corresponding field-update event to repair its value. This is a remaining instance of the pre-existing stale-connect-snapshot problem, not a new regression.
The practical scope is limited: the server still has the skill activated and the agent received its instructions. Canvas's Skill Ready display reads the individual message's activated_skills, so this repro does not demonstrate a broken skill badge or an agent forgetting instructions. It demonstrates stale metadata in a client that applies the received full-state snapshots.
Session snapshot reproduction script
From this PR checkout after make build, save as /tmp/repro_session.py and run:
OH_PERSISTENCE_DIR=/tmp/pr6577-session-state PYTHONPATH="$PWD" uv run python /tmp/repro_session.pyThis uses the actual session socket route over a loopback connection and the real conversation run path. The model response is scripted; the snapshot gate schedules the interleaving.
import asyncio
import json
import socket
import threading
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import uvicorn
import websockets
from fastapi import FastAPI
from openhands.agent_server import session_socket
from openhands.agent_server.config import Config
from openhands.agent_server.conversation_service import ConversationService
from openhands.sdk import LLM, Agent, Message, TextContent
from openhands.sdk.context import AgentContext
from openhands.sdk.skills import Skill, KeywordTrigger
from openhands.sdk.conversation.request import StartConversationRequest
from openhands.sdk.testing import TestLLM
from openhands.sdk.workspace import LocalWorkspace
async def main():
with TemporaryDirectory() as temporary:
root = Path(temporary)
async with ConversationService(
conversations_dir=root / "conversations"
) as owner:
info, _ = await owner.start_conversation(
StartConversationRequest(
agent=Agent(
llm=LLM(model="gpt-4o", usage_id="repro", stream=False),
tools=[],
include_default_tools=[],
agent_context=AgentContext(
skills=[
Skill(
name="python_tips",
content="Use Python.",
source="python.md",
trigger=KeywordTrigger(keywords=["python"]),
)
]
),
),
workspace=LocalWorkspace(working_dir=str(root / "workspace")),
autotitle=False,
)
)
svc = await owner.get_event_service(info.id)
svc.get_conversation().switch_llm(
TestLLM.from_messages(
[Message(role="assistant", content=[TextContent(text="done")])],
usage_id="repro",
stream=False,
)
)
snapped = asyncio.Event()
release = threading.Event()
capture_snapshot = svc._create_initial_state_sync
loop = asyncio.get_running_loop()
def held_snapshot():
result = capture_snapshot()
loop.call_soon_threadsafe(snapped.set)
if not release.wait(10):
raise TimeoutError("snapshot gate")
return result
app = FastAPI()
app.state.config = Config(session_api_keys=[])
app.state.conversation_service = owner
app.include_router(session_socket.session_router)
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
server = uvicorn.Server(
uvicorn.Config(app, lifespan="off", log_level="error")
)
server_task = asyncio.create_task(server.serve(sockets=[listener]))
try:
async with asyncio.timeout(10):
while not server.started:
await asyncio.sleep(0.01)
with patch.object(svc, "_create_initial_state_sync", held_snapshot):
url = f"ws://127.0.0.1:{port}/sockets/session/{info.id}?after_seq=-1"
async with websockets.connect(url) as ws:
received = []
async def receive():
async for payload in ws:
received.append(json.loads(payload))
reader = asyncio.create_task(receive())
await asyncio.wait_for(snapped.wait(), 5)
await svc.send_message(
Message(
role="user", content=[TextContent(text="python")]
),
run=True,
)
await svc.wait_for_run_completion(10)
release.set()
await asyncio.sleep(0.3)
trace = []
received_state = {}
for frame in received:
event = frame.get("event", {})
if event.get("kind") == "ConversationStateUpdateEvent":
if event["key"] == "full_state":
received_state = dict(event["value"])
trace.append(
(
"SNAPSHOT",
received_state["execution_status"],
received_state.get(
"activated_knowledge_skills"
),
)
)
else:
received_state[event["key"]] = event["value"]
if event["key"] == "execution_status":
trace.append(("STATUS", event["value"]))
print("SESSION_SOURCE", session_socket.__file__)
print("NETWORK_TRACE", trace)
print(
"SERVER_SKILLS",
svc.get_conversation().state.activated_knowledge_skills,
"CLIENT_SKILLS",
received_state.get("activated_knowledge_skills"),
)
await ws.close()
await reader
finally:
release.set()
server.should_exit = True
await asyncio.wait_for(server_task, 10)
asyncio.run(main())2. Legacy replay: buffered token chunks can arrive after the completed assistant message.
At sockets.py:559–564, StreamingDeltaEvent enters the replay buffer. If the corresponding final MessageEvent is replayed from disk, the transient chunks are sent afterward because they have no persisted IDs to deduplicate.
With stream=True, run=True, and /sockets/events/{id}?resend_mode=all, the real WebSocket trace was:
Base: DELTA('done') -> FINAL('done') -> FINAL('done')
PR: FINAL('done') -> DELTA('done')
A consumer that finalizes its streaming preview on the final message could interpret the late chunk as new output. I have not demonstrated this in current Canvas: it uses the session socket, and the normal Python SDK connection does not request legacy server-side replay.
This is specifically the legacy channel slated for retirement by #4683 after the remaining clients migrate. That makes the benefit of additional handling here a judgment call.
Legacy streaming replay reproduction script
From this PR checkout after make build, save as /tmp/repro_stream.py and run:
OH_PERSISTENCE_DIR=/tmp/pr6577-stream-state PYTHONPATH="$PWD" uv run python /tmp/repro_stream.pyThis uses the actual legacy socket route over a loopback connection and a scripted LLM that calls the normal token callback. Only the replay search is delayed.
import asyncio
import json
import socket
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import uvicorn
import websockets
from fastapi import FastAPI
from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
from openhands.agent_server import sockets
from openhands.agent_server.config import Config
from openhands.agent_server.conversation_service import ConversationService
from openhands.sdk import LLM, Agent, Message, TextContent
from openhands.sdk.conversation.request import StartConversationRequest
from openhands.sdk.llm.streaming import _invoke_token_callback
from openhands.sdk.testing import TestLLM
from openhands.sdk.workspace import LocalWorkspace
class StreamingTestLLM(TestLLM):
async def acompletion(self, messages, tools=None, on_token=None, **kwargs):
assert on_token is not None
await _invoke_token_callback(
on_token,
ModelResponseStream(
id="test-stream",
choices=[StreamingChoices(index=0, delta=Delta(content="done"))],
),
)
await asyncio.sleep(0)
return await super().acompletion(messages, tools=tools, **kwargs)
async def main():
with TemporaryDirectory() as temporary:
root = Path(temporary)
async with ConversationService(
conversations_dir=root / "conversations"
) as owner:
info, _ = await owner.start_conversation(
StartConversationRequest(
agent=Agent(
llm=LLM(model="gpt-4o", usage_id="repro", stream=True),
tools=[],
include_default_tools=[],
),
workspace=LocalWorkspace(working_dir=str(root / "workspace")),
autotitle=False,
)
)
svc = await owner.get_event_service(info.id)
svc.get_conversation().switch_llm(
StreamingTestLLM.from_messages(
[Message(role="assistant", content=[TextContent(text="done")])],
usage_id="repro",
stream=True,
)
)
gate, in_replay = asyncio.Event(), asyncio.Event()
search = svc.search_events
async def held_search(*args, **kwargs):
in_replay.set()
await gate.wait()
return await search(*args, **kwargs)
app = FastAPI()
app.state.config = Config(session_api_keys=[])
app.state.conversation_service = owner
app.include_router(sockets.conversation_sockets_router)
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
server = uvicorn.Server(
uvicorn.Config(app, lifespan="off", log_level="error")
)
server_task = asyncio.create_task(server.serve(sockets=[listener]))
try:
async with asyncio.timeout(10):
while not server.started:
await asyncio.sleep(0.01)
with patch.object(svc, "search_events", held_search):
url = f"ws://127.0.0.1:{port}/sockets/events/{info.id}?resend_mode=all"
async with websockets.connect(url) as ws:
received = []
async def receive():
async for payload in ws:
received.append(json.loads(payload))
reader = asyncio.create_task(receive())
await asyncio.wait_for(in_replay.wait(), 5)
await svc.send_message(
Message(role="user", content=[TextContent(text="go")]),
run=True,
)
await svc.wait_for_run_completion(10)
gate.set()
await asyncio.sleep(0.3)
trace = []
for event in received:
if event.get("kind") == "StreamingDeltaEvent":
trace.append(("DELTA", event.get("content")))
elif (
event.get("kind") == "MessageEvent"
and event.get("source") == "agent"
):
trace.append(
(
"FINAL",
event["llm_message"]["content"][0]["text"],
)
)
print("SOCKET_SOURCE", sockets.__file__)
print("NETWORK_TRACE", trace)
await ws.close()
await reader
finally:
gate.set()
server.should_exit = True
await asyncio.wait_for(server_task, 10)
asyncio.run(main())Validation on this head: 262 passed, 1 skipped across the focused race tests, related event-service/pubsub/WebSocket/streaming tests, and the live-server suite. The additional reproductions above were compared against the base revision. No additional finding in run admission or subscription cleanup.
…rder newer transient snapshots after the connect snapshot
…utor subscribe_to_events() took the state lock on the shared default executor again once #6577 was merged in, so six WebSocket connects during a tool step still starved the lock-free work of every other conversation. switch_acp_effort(), added on main, had the same shape. Both now run on the per-conversation state executor, and the lock-waiter test also covers the real subscription path.
HUMAN:
Just doing some experiment with lean
AGENT:
Why
Six concurrency bugs in run admission and the event sockets (#6576). The worst: at
max_concurrent_runs, a pause or delete that lands while a re-arm waits for a permit is overridden. A deleted conversation then runs again and rewrites its files on disk.Summary
EventService.run()re-checks the stop generation after the capacity wait, and returns the permit if a stop landed./sockets/sessiondedups on the live path, and takes its replay mark with the connect snapshot under one state-lock hold (Subscriber.on_initial_state)./sockets/eventsbuffers live events during the replay and dedups them by id.subscribe_to_eventsunsubscribes on failure, andPubSub.close()survives failing subscribers.Issue Number
Fixes #6576
Refs #6348 (the
PubSub.closeitem)How to Test
tests/agent_serversuite andtests/cross/test_remote_conversation_live_server.pygive 3032 passed and 4 failed. The 4 are incanvas_extensions/test_canvas_extension_backend.pyand fail the same way on main.Type
Notes
Closing sockets when a conversation is deleted (#5635) is left to #5757.
🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdkpython-node-runtimepython-node-runtimepython-node-runtimegolang: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:b53d6c6-pythonRun
All tags pushed for this build
About Multi-Architecture Support
b53d6c6-python) is a multi-arch manifest supporting both amd64 and arm64b53d6c6-python-amd64) are also available if needed