Skip to content

Fix RemoteConversation.run() timeout issues with async polling - #1444

Merged
xingyaoww merged 5 commits into
mainfrom
fix/async-run-with-polling
Dec 22, 2025
Merged

xingyaoww merged 5 commits into
mainfrom
fix/async-run-with-polling

Conversation

@xingyaoww

@xingyaoww xingyaoww commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Problem

We were experiencing intermittent timeout issues when calling RemoteConversation.run():

  • The read operation timed out
  • Server disconnected without sending a response

These errors occurred because the client held a single HTTP request open for the entire duration of the conversation run (up to 30 minutes), which is prone to network timeouts and connection drops.

Solution

This PR makes the run operation async with polling:

Server-side changes (EventService.run())

  • Modified to run the conversation in a background task using asyncio.create_task() instead of awaiting
  • Returns immediately after triggering the run (no long-held connection)
  • Checks for already-running state via both execution status and task reference
  • Publishes state update after run completes (in finally block to ensure it happens even on error)

Client-side changes (RemoteConversation.run())

  • Added blocking parameter (default True) to allow non-blocking calls
  • Added poll_interval parameter (default 1.0 seconds) to control polling frequency
  • Added timeout parameter (default 1800 seconds / 30 minutes) for maximum wait time
  • When blocking=True, polls GET /api/conversations/{id} for status until complete
  • Handles transient network errors during polling gracefully (logs warning and retries)

Usage

# Default behavior - blocks until complete (same as before, but now uses polling)
conversation.run()

# Non-blocking - returns immediately after triggering
conversation.run(blocking=False)

# Custom polling interval and timeout
conversation.run(poll_interval=2.0, timeout=3600)

Testing

  • Added tests for server-side EventService.run() background task behavior
  • Added tests for client-side polling logic, non-blocking mode, and timeout handling
  • All existing tests updated and passing

Agent Server images for this PR

• 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 amd64, arm64 nikolaik/python-nodejs:python3.12-nodejs22 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:6fa7a2f-python

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:6fa7a2f-golang-amd64
ghcr.io/openhands/agent-server:6fa7a2f-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:6fa7a2f-golang-arm64
ghcr.io/openhands/agent-server:6fa7a2f-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:6fa7a2f-java-amd64
ghcr.io/openhands/agent-server:6fa7a2f-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:6fa7a2f-java-arm64
ghcr.io/openhands/agent-server:6fa7a2f-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:6fa7a2f-python-amd64
ghcr.io/openhands/agent-server:6fa7a2f-nikolaik_s_python-nodejs_tag_python3.12-nodejs22-amd64
ghcr.io/openhands/agent-server:6fa7a2f-python-arm64
ghcr.io/openhands/agent-server:6fa7a2f-nikolaik_s_python-nodejs_tag_python3.12-nodejs22-arm64
ghcr.io/openhands/agent-server:6fa7a2f-golang
ghcr.io/openhands/agent-server:6fa7a2f-java
ghcr.io/openhands/agent-server:6fa7a2f-python

About Multi-Architecture Support

  • Each variant tag (e.g., 6fa7a2f-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., 6fa7a2f-python-amd64) are also available if needed

- Server: Modify EventService.run() to run conversation in background task
  using asyncio.create_task() instead of awaiting, returning immediately
- Client: Add blocking parameter to RemoteConversation.run() (default True)
  to allow non-blocking calls
- Client: Add polling logic to wait for completion when blocking=True
- Add comprehensive tests for both server and client changes

This fixes timeout issues ('The read operation timed out', 'Server
disconnected without sending a response') by:
1. Server triggers run and returns immediately (no long-held connection)
2. Client polls GET /api/conversations/{id} for status until complete
3. Users can opt-out of blocking with blocking=False for fire-and-forget

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   event_service.py30515250%54–55, 74–76, 80–85, 88–91, 106, 122, 126, 130–131, 138, 140, 147–148, 156–159, 166–168, 185, 209–210, 213–214, 216–218, 220, 225, 228–229, 232–234, 237, 241–243, 245, 247, 258–261, 274–275, 278–279, 282, 285–287, 290–291, 294–295, 299, 302, 306, 310–311, 313, 330–331, 348, 350, 354–356, 360, 369–370, 372, 376, 382, 384, 392–397, 456, 463, 467, 478–479, 489–492, 494–495, 499, 501, 505–508, 513–515, 517, 521–524, 528–531, 539–542, 561–562, 564–571, 573–574, 583–584, 586–587, 594–595, 597–598, 602, 608, 618–619, 626
openhands-sdk/openhands/sdk/conversation/impl
   remote_conversation.py43414267%62–68, 75–78, 107, 114, 122, 124–127, 137, 146, 150–151, 156–159, 194, 208, 225, 236, 245–246, 298, 318, 326, 338, 346–349, 352, 357–360, 362, 367–368, 373–377, 382–386, 391–394, 397, 408–409, 413, 417, 420, 494–495, 499–500, 508, 514, 516, 532–533, 538, 540–541, 552, 569–570, 577–579, 582–586, 588–589, 593, 595–603, 605, 609, 624, 642, 677, 679, 682–683, 685–686, 712, 736, 739, 744–745, 754–755, 764, 772, 777–779, 781, 784, 786–787, 807, 809, 815–816, 831, 838, 844–845, 860, 874–875, 882–883
TOTAL13411609354% 

@xingyaoww

Copy link
Copy Markdown
Contributor Author

cc @simonrosenberg @juanmichelini this supposedly should help fixing these two issues commonly seen in evaluation:

The read operation timed out
Server disconnected without sending a response

I'm running an eval to validate in this PR: OpenHands/benchmarks#179

Would appreciate an 👀 here in case i missed smth - but it is pretty smooth so far!

@xingyaoww
xingyaoww marked this pull request as ready for review December 19, 2025 03:50
@xingyaoww
xingyaoww requested a review from tofarr December 19, 2025 04:05

@juanmichelini juanmichelini left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM! assuming the eval OpenHands/benchmarks#179 runs smoothly, I will run a large split tomorrow.

@xingyaoww

Copy link
Copy Markdown
Contributor Author

@juanmichelini i've been running ~293 instances so far, didn't see a single instance of

The read operation timed out
Server disconnected without sending a response

yet

@enyst

enyst commented Dec 20, 2025

Copy link
Copy Markdown
Member

LGTM

@OpenHands Do you see any footguns? /codereview-roasted

Investigate the repo and keep your analysis grounded in reality, not disconnected hypotheticals.

@openhands-ai

openhands-ai Bot commented Dec 20, 2025

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

@openhands-ai

openhands-ai Bot commented Dec 20, 2025 •

Copy link
Copy Markdown

Summary of my review

(you asked for footguns)

Overall: The async “trigger + poll” approach is a solid, pragmatic fix for the timeout issues. It removes long-held connections and keeps the default blocking behavior via polling. A few server-side concurrency and lifecycle edges are worth tightening to avoid subtle runtime issues.

Critical footguns (must-fix)

  • EventService.run race: Two concurrent POST /run requests can both pass the “already running” checks and create two background tasks before self._run_task is set.
    • Fix: Make the check+set atomic (e.g., protect with an asyncio.Lock or set a sentinel before creating the task; or hold the state lock, set a “running” marker, then create the task).
  • Unobserved task exceptions: Exceptions thrown by conversation.run inside the background task aren’t caught; since the task isn’t awaited in production, you may get “Task exception was never retrieved.”
    • Fix: Catch/log exceptions inside _run_and_publish and always clear self._run_task in finally after publishing the state update.
  • Confirmation accept race: respond_to_confirmation calls run() when accept=True. If the run is still unwinding, run() raises “conversation_already_running” and you can end up returning a 500.
    • Fix: Treat “already running” as a no-op success in respond_to_confirmation.

Improvements (nice-to-have but recommended)

  • Client polling resilience: _wait_for_run_completion retries on error without backoff, which may cause bursty logs/load across many clients.
    • Fix: Add minimal exponential backoff with jitter on repeated failures.
  • Accept 202 for run trigger: Future-proof by adding 202 to acceptable_status_codes for the POST /run trigger.
  • Task lifecycle hygiene: After completion, self._run_task stays set to a completed task.
    • Fix: Set self._run_task = None in the task’s finally block.
  • Timeout default mismatch: RemoteConversation.run default timeout is 3600 while _wait_for_run_completion defaults to 1800.
    • Fix: Align or always pass through the run() timeout to the helper.
  • BaseConversation.run signature variance: Base defines run() without params; RemoteConversation.run adds optional args. Runtime is fine, but some type checkers can complain.
    • Fix: If pyright flags it, consider making BaseConversation.run accept optional kwargs (documented as implementation-specific) or expose a separate method on RemoteConversation.
  • Logging clarity: Logging the httpx.Response repr (“run() triggered successfully: {resp}”) isn’t very useful.
    • Fix: Log status_code and URL instead.
  • Tests: Add a test that accept confirmation while run is still RUNNING does not 500 and does not spin up a duplicate run task.

Verdict

  • Worth merging after addressing the server-side concurrency/exception handling footguns. The client/server behavior change is backward compatible and should eliminate the long-connection read timeouts you were seeing.

View full conversation

@xingyaoww

Copy link
Copy Markdown
Contributor Author

@OpenHands can you review the two footguns: #1444 (comment)

Are they valid? If so, can you try fix the critical ones - make minimal edits necessary (we already tested most of the PR, if we change it too much, we might need to re-run an expensive eval)

@openhands-ai

openhands-ai Bot commented Dec 22, 2025

Copy link
Copy Markdown

I'm on it! xingyaoww can track my progress at all-hands.dev

- Add asyncio.Lock to make check-and-set atomic, preventing race conditions
  when concurrent POST /run requests arrive
- Catch and log exceptions in _run_and_publish to prevent 'Task exception
  was never retrieved' warnings
- Clear _run_task in finally block for proper lifecycle hygiene
- Handle 'already running' in respond_to_confirmation as no-op success
  to prevent 500 errors when confirmation arrives during active run

Co-authored-by: openhands <openhands@all-hands.dev>
@openhands-ai

openhands-ai Bot commented Dec 22, 2025

Copy link
Copy Markdown

Summary

I reviewed the two critical footguns identified in the PR comment and confirmed they are valid. I've implemented minimal fixes for all three critical issues:

Fixes Applied

  1. Race condition in EventService.run() ✅

    • Added _run_lock: asyncio.Lock field to the dataclass
    • Wrapped the check-and-set logic in async with self._run_lock: to make it atomic
    • This prevents two concurrent POST /run requests from both passing the "already running" checks
  2. Unobserved task exceptions ✅

    • Added except Exception as e: block in _run_and_publish() to catch and log errors
    • This prevents "Task exception was never retrieved" warnings since the task isn't awaited
  3. Task lifecycle hygiene ✅

    • Added self._run_task = None in the finally block
    • This clears the task reference after completion
  4. Confirmation accept race ✅

    • Modified respond_to_confirmation() to catch ValueError("conversation_already_running")
    • Treats it as a no-op success instead of propagating as a 500 error

Verification

  • All 53 test_event_service.py tests pass
  • All 52 remote conversation tests pass
  • Pre-commit hooks pass (ruff format, ruff lint, pycodestyle, pyright)

Changes

  • Single file modified: openhands-agent-server/openhands/agent_server/event_service.py
  • 35 lines added, 20 lines removed (minimal changes as requested)

The changes have been pushed to the fix/async-run-with-polling branch.

View full conversation

@xingyaoww xingyaoww added the integration-test Runs the integration tests and comments the results label Dec 22, 2025
@github-actions

Copy link
Copy Markdown
Contributor

Hi! I started running the integration tests on your PR. You will receive a comment with the results shortly.

@xingyaoww

Copy link
Copy Markdown
Contributor Author

Thanks @enyst for the feedback - Just got OH fixed it, lmk if you have concerns there and happy to fix in follow-up PRs

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Integration Tests Results

Overall Success Rate: 97.8%
Total Cost: $1.17
Models Tested: 6
Timestamp: 2025-12-22 15:02:47 UTC

📁 Detailed Logs & Artifacts

Click the links below to access detailed agent/LLM logs showing the complete reasoning process for each model. On the GitHub Actions page, scroll down to the 'Artifacts' section to download the logs.

📊 Summary

Model Overall Integration (Required) Behavior (Optional) Tests Passed Skipped Total Cost
litellm_proxy_gpt_5.1_codex_max 100.0% 100.0% N/A 8/8 0 8 $0.15
litellm_proxy_mistral_devstral_2512 85.7% 85.7% N/A 6/7 1 8 $0.11
litellm_proxy_vertex_ai_gemini_3_pro_preview 100.0% 100.0% N/A 8/8 0 8 $0.26
litellm_proxy_claude_sonnet_4_5_20250929 100.0% 100.0% N/A 8/8 0 8 $0.41
litellm_proxy_deepseek_deepseek_chat 100.0% 100.0% N/A 7/7 1 8 $0.05
litellm_proxy_moonshot_kimi_k2_thinking 100.0% 100.0% N/A 7/7 1 8 $0.18

📋 Detailed Results

litellm_proxy_gpt_5.1_codex_max

  • Overall Success Rate: 100.0% (8/8)
  • Integration Tests (Required): 100.0% (8/8)
  • Total Cost: $0.15
  • Run Suffix: litellm_proxy_gpt_5.1_codex_max_a6b14a0_gpt51_codex_run_N8_20251222_145806

litellm_proxy_mistral_devstral_2512

  • Overall Success Rate: 85.7% (6/7)
  • Integration Tests (Required): 85.7% (6/8)
  • Total Cost: $0.11
  • Run Suffix: litellm_proxy_mistral_devstral_2512_a6b14a0_devstral_2512_run_N8_20251222_145804
  • Skipped Tests: 1

Skipped Tests:

  • t08_image_file_viewing: This test requires a vision-capable LLM model. Please use a model that supports image input.

Failed Tests:

  • t02_add_bash_hello ⚠️ REQUIRED: Shell script is not executable (Cost: $0.01)

litellm_proxy_vertex_ai_gemini_3_pro_preview

  • Overall Success Rate: 100.0% (8/8)
  • Integration Tests (Required): 100.0% (8/8)
  • Total Cost: $0.26
  • Run Suffix: litellm_proxy_vertex_ai_gemini_3_pro_preview_a6b14a0_gemini_3_pro_run_N8_20251222_145805

litellm_proxy_claude_sonnet_4_5_20250929

  • Overall Success Rate: 100.0% (8/8)
  • Integration Tests (Required): 100.0% (8/8)
  • Total Cost: $0.41
  • Run Suffix: litellm_proxy_claude_sonnet_4_5_20250929_a6b14a0_sonnet_run_N8_20251222_145804

litellm_proxy_deepseek_deepseek_chat

  • Overall Success Rate: 100.0% (7/7)
  • Integration Tests (Required): 100.0% (7/8)
  • Total Cost: $0.05
  • Run Suffix: litellm_proxy_deepseek_deepseek_chat_a6b14a0_deepseek_run_N8_20251222_145803
  • Skipped Tests: 1

Skipped Tests:

  • t08_image_file_viewing: This test requires a vision-capable LLM model. Please use a model that supports image input.

litellm_proxy_moonshot_kimi_k2_thinking

  • Overall Success Rate: 100.0% (7/7)
  • Integration Tests (Required): 100.0% (7/8)
  • Total Cost: $0.18
  • Run Suffix: litellm_proxy_moonshot_kimi_k2_thinking_a6b14a0_kimi_k2_run_N8_20251222_145805
  • Skipped Tests: 1

Skipped Tests:

  • t08_image_file_viewing: This test requires a vision-capable LLM model. Please use a model that supports image input.

@xingyaoww
xingyaoww merged commit e8f73e7 into main Dec 22, 2025
@xingyaoww
xingyaoww deleted the fix/async-run-with-polling branch December 22, 2025 15:03
@enyst

enyst commented Dec 22, 2025

Copy link
Copy Markdown
Member

🍰

StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

integration-test Runs the integration tests and comments the results

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants