Skip to content

fix(agent-server): stop lost to a queued re-arm; event-socket replay races - #6577

Merged
VascoSch92 merged 6 commits into
mainfrom
vasco/agent-server-race-fixes
Nov 7, 2026
Merged

VascoSch92 merged 6 commits into
mainfrom
vasco/agent-server-race-fixes

Conversation

@VascoSch92

@VascoSch92 VascoSch92 commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

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/session dedups on the live path, and takes its replay mark with the connect snapshot under one state-lock hold (Subscriber.on_initial_state).
  • /sockets/events buffers live events during the replay and dedups them by id.
  • subscribe_to_events unsubscribes on failure, and PubSub.close() survives failing subscribers.

Issue Number

Fixes #6576
Refs #6348 (the PubSub.close item)

How to Test

uv run pytest tests/agent_server/test_rearm_stop_wins.py tests/agent_server/test_event_socket_races.py tests/agent_server/test_session_socket.py -q
  • The new tests fail on main.
  • With the fix, the full tests/agent_server suite and tests/cross/test_remote_conversation_live_server.py give 3032 passed and 4 failed. The 4 are in canvas_extensions/test_canvas_extension_backend.py and fail the same way on main.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python-slim amd64, arm64 python-node-runtime Link
python-minimal amd64, arm64 python-node-runtime Link
python amd64, arm64 python-node-runtime Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:b53d6c6-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-b53d6c6-python \
  ghcr.io/openhands/agent-server:b53d6c6-python

All tags pushed for this build

ghcr.io/openhands/agent-server:b53d6c6-golang-amd64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-golang-amd64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-golang-amd64
ghcr.io/openhands/agent-server:b53d6c6-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:b53d6c6-golang-arm64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-golang-arm64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-golang-arm64
ghcr.io/openhands/agent-server:b53d6c6-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:b53d6c6-java-amd64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-java-amd64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-java-amd64
ghcr.io/openhands/agent-server:b53d6c6-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:b53d6c6-java-arm64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-java-arm64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-java-arm64
ghcr.io/openhands/agent-server:b53d6c6-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-amd64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-amd64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-arm64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-arm64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-minimal-amd64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-minimal-amd64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-minimal-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-minimal-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-minimal-arm64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-minimal-arm64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-minimal-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-minimal-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-slim-amd64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-slim-amd64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-slim-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-slim-amd64
ghcr.io/openhands/agent-server:b53d6c6-python-slim-arm64
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-slim-arm64
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-slim-arm64
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-slim-arm64
ghcr.io/openhands/agent-server:b53d6c6-golang
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-golang
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-golang
ghcr.io/openhands/agent-server:b53d6c6-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:b53d6c6-java
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-java
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-java
ghcr.io/openhands/agent-server:b53d6c6-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:b53d6c6-python-minimal
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-minimal
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-minimal
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-minimal
ghcr.io/openhands/agent-server:b53d6c6-python-slim
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python-slim
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python-slim
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime-slim
ghcr.io/openhands/agent-server:b53d6c6-python
ghcr.io/openhands/agent-server:b53d6c65a85dab75663a43a5e027188bd8ee780b-python
ghcr.io/openhands/agent-server:vasco-agent-server-race-fixes-python
ghcr.io/openhands/agent-server:b53d6c6-python-node-runtime

About Multi-Architecture Support

  • Each variant tag (e.g., b53d6c6-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., b53d6c6-python-amd64) are also available if needed

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.
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@datadog-official

datadog-official Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Pipelines

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: b53d6c6 | Docs | Give us feedback!

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   event_service.py110910291%161, 167–168, 301–302, 432, 436, 441, 468, 475, 510, 513–514, 518–519, 530, 536, 664–665, 786, 806, 833, 842, 866–867, 871, 919, 954, 958–959, 994, 1001, 1007, 1221, 1251, 1254, 1332, 1350, 1364, 1533–1534, 1589, 1623, 1779–1782, 1786, 1829, 1833, 1840, 1854, 1868, 1892, 1939–1941, 2025, 2047, 2050–2051, 2076, 2082, 2084, 2100, 2102, 2109, 2117, 2119–2120, 2124, 2172, 2178, 2187–2188, 2195, 2210, 2221, 2334–2335, 2337–2344, 2346–2347, 2357, 2368, 2384–2385, 2396, 2423, 2429, 2435, 2444–2445, 2467, 2477
   pub_sub.py57296%106–107
   session_socket.py2775182%141, 145–146, 150, 152–155, 168–170, 227, 345, 372, 378–379, 382, 384–385, 388, 392, 394–395, 398, 410–412, 415, 430, 433, 437, 441, 447, 462, 487–488, 492–494, 512, 515–516, 518–523, 526–527, 530
   sockets.py2682690%208, 211, 214, 293–294, 298, 300–302, 310–311, 314, 436–439, 444–445, 450–452, 522, 524, 543, 570, 584
TOTAL542552068662% 

@VascoSch92 VascoSch92 changed the title fix(agent-server): stop lost to a queued re-arm; event-socket replay and teardown races fix(agent-server): stop lost to a queued re-arm; event-socket replay races Nov 7, 2026
@VascoSch92
VascoSch92 marked this pull request as ready for review November 7, 2026 11:55
@enyst
enyst requested a review from all-hands-bot November 7, 2026 12:06

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py

This 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.

@VascoSch92

Copy link
Copy Markdown
Member Author

@enyst Fixed :-)

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py

This 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.py

This 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

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@VascoSch92
VascoSch92 merged commit b0eeceb into main Nov 7, 2026
50 checks passed
@VascoSch92
VascoSch92 deleted the vasco/agent-server-race-fixes branch November 7, 2026 16:21
VascoSch92 added a commit that referenced this pull request Nov 11, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: agent-server races: a stop lost to a queued re-arm; event sockets duplicate, reorder and leak subscriptions

2 participants