Skip to content

fix(llm): time out hung async streams - #5000

Merged
neubig merged 15 commits into
mainfrom
fix/4997-stream-timeouts
Sep 30, 2026
Merged

neubig merged 15 commits into
mainfrom
fix/4997-stream-timeouts

Conversation

@neubig

@neubig neubig commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

HUMAN:
Implement #4996 as the final stacked lifecycle compatibility layer, preserving backward compatibility and avoiding generated-client churn.

AGENT:

Why

A stalled asynchronous model stream can hold a conversation and its workspace indefinitely.

Summary

Bound each completion attempt by the configured timeout and each idle interval between chunks by stream_idle_timeout, which defaults to timeout. Reuse existing retry/error handling so stalled calls can fail and recover.

REST API contract changes

Compared with base OpenAPI af3ed3ed9971 for public /api/** paths.

--- base public OpenAPI
+++ head public OpenAPI
@@ -4,0 +5 @@
+operation DELETE /api/canvas-extensions/installed/{extension_name}/backend/data operationId=delete_canvas_extension_backend_data_endpoint_api_canvas_extensions_installed__extension_name__backend_data_delete
@@ -22,0 +24,2 @@
+operation GET /api/canvas-extensions/installed/{extension_name}/backend operationId=get_canvas_extension_backend_status_endpoint_api_canvas_extensions_installed__extension_name__backend_get
+operation GET /api/canvas-extensions/installed/{extension_name}/backend/logs operationId=get_canvas_extension_backend_logs_endpoint_api_canvas_extensions_installed__extension_name__backend_logs_get
@@ -98,0 +102,3 @@
+operation POST /api/canvas-extensions/installed/{extension_name}/backend/prepare operationId=prepare_canvas_extension_backend_endpoint_api_canvas_extensions_installed__extension_name__backend_prepare_post
+operation POST /api/canvas-extensions/installed/{extension_name}/backend/start operationId=start_canvas_extension_backend_endpoint_api_canvas_extensions_installed__extension_name__backend_start_post
+operation POST /api/canvas-extensions/installed/{extension_name}/backend/stop operationId=stop_canvas_extension_backend_endpoint_api_canvas_extensions_installed__extension_name__backend_stop_post
@@ -154,0 +161 @@
+parameter DELETE /api/canvas-extensions/installed/{extension_name}/backend/data path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
@@ -176,0 +184,3 @@
+parameter GET /api/canvas-extensions/installed/{extension_name}/backend path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
+parameter GET /api/canvas-extensions/installed/{extension_name}/backend/logs path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
+parameter GET /api/canvas-extensions/installed/{extension_name}/backend/logs query:limit_bytes required=false schema=type="integer" default=65536 minimum=1 maximum=262144
@@ -290,0 +301,3 @@
+parameter POST /api/canvas-extensions/installed/{extension_name}/backend/prepare path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
+parameter POST /api/canvas-extensions/installed/{extension_name}/backend/start path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
+parameter POST /api/canvas-extensions/installed/{extension_name}/backend/stop path:extension_name required=true schema=type="string" minLength=1 maxLength=255 pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
@@ -346,0 +360,2 @@
+requestBody POST /api/canvas-extensions/installed/{extension_name}/backend/prepare application/json required=true schema=BackendRevisionRequest
+requestBody POST /api/canvas-extensions/installed/{extension_name}/backend/start application/json required=true schema=BackendRevisionRequest
@@ -391,0 +407,3 @@
+response DELETE /api/canvas-extensions/installed/{extension_name}/backend/data 200 application/json schema=BackendStatus
+response DELETE /api/canvas-extensions/installed/{extension_name}/backend/data 409 no-content
+response DELETE /api/canvas-extensions/installed/{extension_name}/backend/data 422 application/json schema=HTTPValidationError
@@ -430,0 +449,4 @@
+response GET /api/canvas-extensions/installed/{extension_name}/backend 200 application/json schema=BackendStatus
+response GET /api/canvas-extensions/installed/{extension_name}/backend 422 application/json schema=HTTPValidationError
+response GET /api/canvas-extensions/installed/{extension_name}/backend/logs 200 application/json schema=BackendLogs
+response GET /api/canvas-extensions/installed/{extension_name}/backend/logs 422 application/json schema=HTTPValidationError
@@ -584,0 +607,8 @@
+response POST /api/canvas-extensions/installed/{extension_name}/backend/prepare 200 application/json schema=BackendStatus
+response POST /api/canvas-extensions/installed/{extension_name}/backend/prepare 409 no-content
+response POST /api/canvas-extensions/installed/{extension_name}/backend/prepare 422 application/json schema=HTTPValidationError
+response POST /api/canvas-extensions/installed/{extension_name}/backend/start 200 application/json schema=BackendStatus
+response POST /api/canvas-extensions/installed/{extension_name}/backend/start 409 no-content
+response POST /api/canvas-extensions/installed/{extension_name}/backend/start 422 application/json schema=HTTPValidationError
+response POST /api/canvas-extensions/installed/{extension_name}/backend/stop 200 application/json schema=BackendStatus
+response POST /api/canvas-extensions/installed/{extension_name}/backend/stop 422 application/json schema=HTTPValidationError
@@ -1021,0 +1052,14 @@
+schema BackendLogs property logs required schema=type="string"
+schema BackendLogs property name required schema=type="string"
+schema BackendLogs property truncated required schema=type="boolean"
+schema BackendLogs type="object"
+schema BackendRevisionRequest property revision required schema=type="string" minLength=1
+schema BackendRevisionRequest type="object"
+schema BackendStatus property detail optional schema=anyOf=[type="string",type="null"]
+schema BackendStatus property name required schema=type="string"
+schema BackendStatus property pid optional schema=anyOf=[type="integer",type="null"]
+schema BackendStatus property port optional schema=anyOf=[type="integer",type="null"]
+schema BackendStatus property prepared_revision optional schema=anyOf=[type="string",type="null"]
+schema BackendStatus property revision optional schema=anyOf=[type="string",type="null"]
+schema BackendStatus property state required schema=type="string" enum=["missing","stopped","starting","ready","unhealthy","unsupported"]
+schema BackendStatus type="object"
@@ -1230,0 +1275,13 @@
+schema CanvasExtensionBackend property argv required schema=type="array" items=type="string" minItems=1
+schema CanvasExtensionBackend property artifacts required schema=type="object" additionalProperties=CanvasExtensionBackendArtifact
+schema CanvasExtensionBackend property health optional schema=CanvasExtensionBackendHealth
+schema CanvasExtensionBackend property inherit_environment optional schema=type="array" items=type="string"
+schema CanvasExtensionBackend property schema_version required schema=type="integer" const=1
+schema CanvasExtensionBackend type="object"
+schema CanvasExtensionBackendArtifact property path required schema=type="string"
+schema CanvasExtensionBackendArtifact property sha256 required schema=type="string" pattern="^[0-9a-f]{64}$"
+schema CanvasExtensionBackendArtifact type="object"
+schema CanvasExtensionBackendHealth property interval_seconds optional schema=type="number" default=0.1 maximum=10.0 exclusiveMinimum=0.0
+schema CanvasExtensionBackendHealth property path optional schema=type="string" default="/health" pattern="^/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$"
+schema CanvasExtensionBackendHealth property timeout_seconds optional schema=type="number" default=30 maximum=300.0 exclusiveMinimum=0.0
+schema CanvasExtensionBackendHealth type="object"
@@ -1232,0 +1290 @@
+schema CanvasExtensionManifest property backend optional schema=anyOf=[CanvasExtensionBackend,type="null"]
@@ -1827,0 +1886 @@
+schema LLM-Input property stream_idle_timeout optional schema=anyOf=[type="number" minimum=0.0,type="null"] default=300
@@ -1883,0 +1943 @@
+schema LLM-Output property stream_idle_timeout optional schema=anyOf=[type="number" minimum=0.0,type="null"] default=300

Issue Number

Fixes #4997.

How to Test

uv run pytest tests/sdk/llm/test_llm_timeout.py -q

All 13 focused tests pass, including a real HTTP server that stalls mid-stream. Pre-commit and current-head CI pass. The isolated software factory runs this timeout handling during its Docker agent jobs.

Type

  • Bug fix

Notes

Independent main PR. Maintainer eval review remains appropriate because this changes model-stream timeout behavior.

REST API contract changes

Compared with base OpenAPI 76e9e25078ed for public /api/** paths.

--- base public OpenAPI
+++ head public OpenAPI
@@ -1667,0 +1668 @@
+schema LLM-Input property stream_idle_timeout optional schema=anyOf=[type="number" minimum=0.0,type="null"] default=300
@@ -1723,0 +1725 @@
+schema LLM-Output property stream_idle_timeout optional schema=anyOf=[type="number" minimum=0.0,type="null"] default=300

Live Agent Canvas evidence

Live isolated Canvas comparison: with an actual 3-second attempt limit, the base still ran after 11.233 seconds of arriving chunks; the PR head showed the hard timeout, then recovered in the same conversation. A separate run showed the 2-second idle timeout. Actual agent settings were verified; an exploratory onboarding run with default settings was excluded. The 2.939-second measurement is the persisted SDK error, while the first sampled UI Error appears 12.552 seconds after Send. Background Automation-service 404 toasts are disclosed and unrelated; this comparison intentionally starts no Automation service.

Before GIF · After GIF · Report and reproduction · Measured evidence. These immutable links retain the artifacts if .pr/ is later cleaned up.

Live hung-stream evidence: fails on base, passes on head

This section was added by an AI agent (OpenHands) on behalf of the user. It was run on 2026-09-30, after this PR merged, so it documents the merged change and does not change it.

SHAs. Base af3ed3ed99715fabd385058bec31d538336c9740. Head 634859769cb0788f6fc20b2111a0cc876cdfe57b, merged as 656a5c4794d0c31beda37b3ed5f944e120a7016f. Environment: Python 3.13, litellm 1.93.0, openai 2.33.0, httpx 0.28.1. LLM_API_KEY was not needed.

Setup. A real aiohttp server on 127.0.0.1 streams OpenAI chat-completions and Responses SSE. The SDK runs unmodified through LLM.acompletion / LLM.aresponses and LocalConversation.arun → Agent.astep, then litellm → openai/httpx. Nothing in the SDK is mocked. Settings: timeout=3, stream=True, and a 20s outer watchdog. Both stall modes keep bytes flowing, so httpx's per-read timeout never fires, which is the #4997 root cause:

  • heartbeat: one first event, then only SSE comment lines (: ping) every 0.5s.
  • trickle: a real text delta every 0.5s, never finishing.
  • *_then_recover: attempt 1 stalls and attempt 2 is a normal stream.

Responses cases use openai/gpt-5.1-codex. For models litellm does not know, it falls back to a non-streaming "fake stream"; responses_fake_stream_trickle covers that path.

case base af3ed3e head 6348597 head cleanup
chat_heartbeat_then_recover HUNG at 20.001s watchdog returned recovered in 3.844s stalled conn closed 4.216s after open; leftover tasks 0
chat_trickle_forever HUNG at 20.001s watchdog raised LLMTimeoutError (hard timeout) in 3.003s stalled conn closed 3.006s after open; leftover tasks 0
chat_idle1_then_recover HUNG at 20.001s watchdog returned recovered in 1.014s stalled conn closed 1.502s after open; leftover tasks 0
responses_heartbeat_then_recover HUNG at 20.001s watchdog returned recovered in 3.01s stalled conn closed 3.006s after open; leftover tasks 0
responses_trickle_forever HUNG at 20.001s watchdog raised LLMTimeoutError (hard timeout) in 3.002s stalled conn closed 3.006s after open; leftover tasks 0
responses_idle1_then_recover HUNG at 20.001s watchdog returned recovered in 1.124s stalled conn closed 1.614s after open; leftover tasks 0
responses_fake_stream_trickle HUNG at 20.001s watchdog raised LLMTimeoutError (hard timeout) in 3.003s stalled conn closed 3.004s after open; leftover tasks 0
conversation_chat_heartbeat HUNG at 20.001s watchdog, status running raised ConversationRunError (hard timeout) in 3.109s, status error stalled conn closed 3.005s after open; leftover tasks 0
conversation_responses_heartbeat HUNG at 20.001s watchdog, status running raised ConversationRunError (hard timeout) in 3.007s, status error stalled conn closed 3.004s after open; leftover tasks 0
cancel_llm_chat_heartbeat cancelled at 1.501s → CancelledError cancelled at 1.501s → CancelledError stalled conn closed 1.502s after open; leftover tasks 0
cancel_conversation_responses_heartbeat cancelled at 1.503s → returned normally, status paused cancelled at 1.501s → returned normally, status paused stalled conn closed 1.503s after open; leftover tasks 0

Longer base run. conversation_responses_heartbeat with WATCHDOG=60 was still hung at 60.001s, which is 20× the configured timeout. The status was running and the only events were [SystemPromptEvent, MessageEvent], matching the #4997 symptom. The same case on head ends in error with a ConversationErrorEvent after 3.0s.

Cleanup on head. After a timeout, the stalled server connection was released within one 0.5s server tick of the deadline. The close times above are upper bounds because of that tick. There was one outlier: chat_heartbeat_then_recover took 3.844s in the tabulated run, and its close was seen 4.216s after open. Client and server share one event loop in this harness. Six fresh-process reruns of that case gave 3.010–3.013s, with the close at 3.004–3.006s after open. After each failure case, 0 ESTABLISHED sockets remained on the port. After each recovered case, only the pooled keep-alive connection from the successful attempt remained. No case left any asyncio tasks. Cancellation behaves the same as on base: cancelling an in-flight acompletion raises CancelledError, not a timeout, and cancelling arun() gives paused plus an InterruptEvent. The stalled socket closes promptly in both cases.

Pytest regressions (fail on base, pass on head). The live repro exposed two gaps in the existing tests. The keep_sending=True branch of _hung_chat_completion_server was never used, so no test covered a byte-flowing stream that defeats httpx's read timeout. The Responses path was only tested with a mocked litellm_aresponses. Two new real-HTTP tests close these gaps:

  • test_async_hard_timeout_ends_real_stream_that_never_finishes
  • test_aresponses_idle_timeout_recovers_from_real_heartbeat_stream

Both also assert that the stalled server handler finished.

run result
base af3ed3e 2 failed in 30.40s. Both were still hung when the in-test 15s asyncio.timeout guard fired.
head 6348597 test_llm_timeout.py + test_responses_parsing_and_kwargs.py: 41 passed. tests/sdk/llm -n 4: 1077 passed. New tests: 30/30 sequential, 32/32 across 4 parallel loops.
current main 5ffdd29 test_llm_timeout.py: 21 passed. The fix is still present.

These tests are not pushed. This PR merged and its branch was deleted before this run, so they exist only as local commit 23aac47 on top of 6348597, included as a patch below. They can go in a follow-up PR if maintainers want them. No SDK code changes were needed: nothing in this run showed a defect introduced by the PR.

Observations (none blocking):

  1. With the default stream_idle_timeout = timeout, the hard timeout usually fires first once the first chunk has arrived, since both are 3s here. The idle timer only reports itself when set lower. In the *_idle1_* cases, with stream_idle_timeout=1, the call recovered in 1.01–1.12s.
  2. As earlier reviews noted, the hard timeout also caps the total duration of each attempt. A legitimate stream longer than timeout is now aborted and retried.
  3. The sync completion() / responses() stream loops are still unbounded. This is pre-existing and outside [Bug]: Conversations stall indefinitely when ChatGPT subscription LLM call hangs #4997's async scope.
  4. If a wrapper returns a sync iterable, the async run_in_executor(list, …) fallback is unblocked by the hard timeout, but its worker thread cannot be stopped. This is pre-existing. The pinned lmnr>=0.7.60 uses a callback logger, not a return-value wrapper, so this path is not expected in practice.

Commands

git checkout <sha> && uv sync --dev
REPO=$PWD WATCHDOG=20 uv run python repro.py > <sha>.jsonl          # all 11 cases
REPO=$PWD WATCHDOG=60 uv run python repro.py conversation_responses_heartbeat   # base only
uv run pytest tests/sdk/llm/test_llm_timeout.py -p no:randomly -q \
  -k "never_finishes or real_heartbeat_stream"
repro.py (live reproduction script)
"""Live reproduction of hung async LLM streams through the real SDK path.

A local aiohttp server speaks the OpenAI chat-completions and Responses SSE
protocols over real TCP. The SDK reaches it unmodified through
LLM.acompletion/aresponses (and LocalConversation.arun -> Agent.astep)
-> litellm -> openai/httpx. No SDK code is mocked or patched.

Stall modes (both keep bytes flowing, so the httpx read timeout never fires):
  heartbeat  first event, then only SSE comment lines (": ping") every 0.5s
  trickle    a real text delta every 0.5s forever, never finishing
  ok         a normal, finished stream whose text is "recovered"

Usage: REPO=<sdk checkout> WATCHDOG=20 uv run python repro.py [case ...]
"""

import asyncio
import json
import os
import subprocess
import sys
import time
from typing import Any

from aiohttp import web
from pydantic import SecretStr

from openhands.sdk import LLM, Agent, Message, TextContent
from openhands.sdk.conversation.impl.local_conversation import LocalConversation


WATCHDOG = float(os.environ.get("WATCHDOG", "20"))
TIMEOUT = 3
T0 = time.monotonic()


def now() -> float:
    return round(time.monotonic() - T0, 3)


def chat_chunk(n: int, delta: dict, finish: str | None = None) -> bytes:
    body = {
        "id": f"chatcmpl-{n}",
        "object": "chat.completion.chunk",
        "created": 1,
        "model": "test-model",
        "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
    }
    return f"data: {json.dumps(body)}\n\n".encode()


def resp_event(kind: str, **payload: Any) -> bytes:
    data = json.dumps({"type": kind, **payload})
    return f"event: {kind}\ndata: {data}\n\n".encode()


def resp_obj(n: int, status: str, output: list) -> dict:
    return {
        "id": f"resp_{n}", "object": "response", "created_at": 1,
        "model": "test-model", "status": status, "output": output,
        "parallel_tool_calls": False, "tool_choice": "auto", "tools": [],
        "usage": {
            "input_tokens": 1, "output_tokens": 1, "total_tokens": 2,
            "input_tokens_details": {"cached_tokens": 0},
            "output_tokens_details": {"reasoning_tokens": 0},
        },
    }


def resp_delta(n: int, seq: int, text: str) -> bytes:
    return resp_event("response.output_text.delta", sequence_number=seq,
                      item_id=f"msg_{n}", output_index=0, content_index=0,
                      delta=text)


class Server:
    def __init__(self, modes: list[str]) -> None:
        self.modes = list(modes)
        self.connections: list[dict[str, Any]] = []

    async def _stream(self, request: web.Request, api: str) -> web.StreamResponse:
        await request.json()
        n = len(self.connections) + 1
        mode = self.modes.pop(0) if len(self.modes) > 1 else self.modes[0]
        conn: dict[str, Any] = {"attempt": n, "api": api, "mode": mode,
                                "opened": now()}
        self.connections.append(conn)
        resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
        await resp.prepare(request)
        try:
            if api == "chat":
                await resp.write(chat_chunk(n, {"role": "assistant", "content": ""}))
            else:
                await resp.write(resp_event("response.created", sequence_number=0,
                                            response=resp_obj(n, "in_progress", [])))
            if mode == "ok":
                if api == "chat":
                    await resp.write(chat_chunk(n, {"content": "recovered"}))
                    await resp.write(chat_chunk(n, {}, "stop"))
                    await resp.write(b"data: [DONE]\n\n")
                else:
                    msg = {"type": "message", "id": f"msg_{n}", "role": "assistant",
                           "status": "completed",
                           "content": [{"type": "output_text", "text": "recovered",
                                        "annotations": []}]}
                    await resp.write(resp_delta(n, 1, "recovered"))
                    await resp.write(resp_event("response.output_item.done",
                                                sequence_number=2, output_index=0,
                                                item=msg))
                    await resp.write(resp_event("response.completed",
                                                sequence_number=3,
                                                response=resp_obj(n, "completed",
                                                                  [msg])))
                conn["closed"] = now()
                conn["how"] = "completed"
                return resp
            seq = 1
            while True:
                await asyncio.sleep(0.5)
                if request.transport is None or request.transport.is_closing():
                    raise ConnectionResetError("client closed")
                if mode == "heartbeat":
                    await resp.write(b": ping\n\n")
                elif api == "chat":
                    await resp.write(chat_chunk(n, {"content": "."}))
                else:
                    await resp.write(resp_delta(n, seq, "."))
                seq += 1
        except (ConnectionResetError, asyncio.CancelledError) as e:
            conn["closed"] = now()
            conn["how"] = f"client disconnected ({type(e).__name__})"
            raise

    async def start(self) -> str:
        app = web.Application()
        app.router.add_post("/chat/completions",
                            lambda r: self._stream(r, "chat"))
        app.router.add_post("/responses", lambda r: self._stream(r, "responses"))
        self.runner = web.AppRunner(app, shutdown_timeout=0.1)
        await self.runner.setup()
        site = web.TCPSite(self.runner, "127.0.0.1", 0)
        await site.start()
        return f"http://127.0.0.1:{self.runner.addresses[0][1]}"


def established_sockets(port: int) -> int:
    """Count ESTABLISHED TCP sockets touching ``port`` (from /proc/net/tcp)."""
    hexport = f"{port:04X}"
    count = 0
    with open("/proc/net/tcp") as f:
        for line in f.readlines()[1:]:
            local, remote, state = line.split()[1:4]
            if state == "01" and hexport in (local.split(":")[1],
                                              remote.split(":")[1]):
                count += 1
    return count


async def run_case(name: str, modes: list[str], num_retries: int, via: str,
                   api: str, extra: dict[str, Any],
                   cancel_after: float | None) -> dict[str, Any]:
    server = Server(modes)
    base_url = await server.start()
    port = int(base_url.rsplit(":", 1)[1])
    kwargs = dict(extra)
    if api == "responses":
        kwargs["api_mode"] = "responses"
        # litellm natively streams Responses only for models it knows support
        # it; an unknown model gets MockResponsesAPIStreamingIterator, i.e. a
        # non-streaming body read ("fake stream").
        kwargs.setdefault("model", "openai/gpt-5.1-codex")
    kwargs.setdefault("model", "openai/test-model")
    result: dict[str, Any] = {"case": name, "via": via, "api": api,
                              "timeout": TIMEOUT, "num_retries": num_retries,
                              "model": kwargs["model"], "llm_extra": extra}
    try:
        llm = LLM(api_key=SecretStr("test-key"),
                  base_url=base_url, usage_id="repro", stream=True,
                  timeout=TIMEOUT, num_retries=num_retries, retry_min_wait=0,
                  retry_max_wait=0, retry_multiplier=0, **kwargs)
    except Exception as e:  # noqa: BLE001
        await server.runner.cleanup()
        result["outcome"] = "CANNOT CONFIGURE"
        result["detail"] = f"{type(e).__name__}: {str(e).splitlines()[0][:160]}"
        return result
    conversation: LocalConversation | None = None

    async def call() -> str:
        nonlocal conversation
        if via == "llm":
            fn = llm.aresponses if api == "responses" else llm.acompletion
            resp = await fn(
                messages=[Message(role="user", content=[TextContent(text="hi")])],
                on_token=lambda _c: None,
            )
            return "".join(c.text for c in resp.message.content
                           if isinstance(c, TextContent))
        conversation = LocalConversation(
            agent=Agent(llm=llm, tools=[]),
            workspace="/tmp/stream_hang_repro/ws",
            visualizer=None,
            token_callbacks=[lambda _e: None],
        )
        conversation.send_message("hi")
        await conversation.arun()
        return "arun returned"

    start = time.monotonic()
    task = asyncio.create_task(call())
    limit = cancel_after if cancel_after is not None else WATCHDOG
    done, _ = await asyncio.wait({task}, timeout=limit)
    result["elapsed_s"] = round(time.monotonic() - start, 3)
    if task in done:
        exc = task.exception()
        result["outcome"] = "returned" if exc is None else "raised"
        result["detail"] = (task.result() if exc is None
                            else f"{type(exc).__name__}: {str(exc)[:160]}")
    else:
        result["outcome"] = ("cancelled_by_caller" if cancel_after is not None
                             else f"HUNG (still running at {WATCHDOG:g}s watchdog)")
        if conversation is not None:
            result["conversation_status_before_cancel"] = (
                conversation.state.execution_status.value)
            result["conversation_event_kinds_before_cancel"] = [
                type(e).__name__ for e in conversation.state.events]
        cancel_start = time.monotonic()
        task.cancel()
        try:
            await task
            result["after_cancel"] = "returned normally"
        except BaseException as e:  # noqa: BLE001
            result["after_cancel"] = type(e).__name__
        result["cancel_latency_s"] = round(time.monotonic() - cancel_start, 3)
    if conversation is not None:
        status = conversation.state.execution_status
        result["conversation_status"] = status.value
        result["conversation_event_kinds"] = [
            type(e).__name__ for e in conversation.state.events
        ]
    await asyncio.sleep(1.0)  # let the server's next 0.5s tick observe a close
    result["server_connections"] = server.connections
    result["established_sockets_on_port_after"] = established_sockets(port)
    result["leftover_tasks"] = [
        t.get_coro().__qualname__ for t in asyncio.all_tasks()
        if t is not asyncio.current_task() and not t.done()
        and "RequestHandler" not in repr(t)
    ]
    await server.runner.cleanup()
    return result


# name: (server modes per attempt, num_retries, via, api, extra LLM kwargs)
CASES: dict[str, tuple[list[str], int, str, str, dict[str, Any]]] = {
    "chat_heartbeat_then_recover": (["heartbeat", "ok"], 2, "llm", "chat", {}),
    "chat_trickle_forever": (["trickle"], 1, "llm", "chat", {}),
    "chat_idle1_then_recover": (["heartbeat", "ok"], 2, "llm", "chat",
                                {"stream_idle_timeout": 1}),
    "responses_heartbeat_then_recover": (["heartbeat", "ok"], 2, "llm",
                                         "responses", {}),
    "responses_trickle_forever": (["trickle"], 1, "llm", "responses", {}),
    "responses_idle1_then_recover": (["heartbeat", "ok"], 2, "llm", "responses",
                                     {"stream_idle_timeout": 1}),
    "responses_fake_stream_trickle": (["trickle"], 1, "llm", "responses",
                                      {"model": "openai/test-model"}),
    "conversation_chat_heartbeat": (["heartbeat"], 1, "conversation", "chat", {}),
    "conversation_responses_heartbeat": (["heartbeat"], 1, "conversation",
                                         "responses", {}),
    "cancel_llm_chat_heartbeat": (["heartbeat"], 1, "llm", "chat", {}),
    "cancel_conversation_responses_heartbeat": (["heartbeat"], 1,
                                                "conversation", "responses", {}),
}


async def main() -> None:
    sha = subprocess.run(["git", "rev-parse", "HEAD"], text=True,
                         capture_output=True,
                         cwd=os.environ["REPO"]).stdout.strip()
    print(json.dumps({"sdk_sha": sha, "has_stream_idle_timeout":
                      "stream_idle_timeout" in LLM.model_fields,
                      "watchdog_s": WATCHDOG}), flush=True)
    for name in sys.argv[1:] or CASES:
        modes, retries, via, api, extra = CASES[name]
        cancel = 1.5 if name.startswith("cancel_") else None
        print(json.dumps(await run_case(name, modes, retries, via, api, extra,
                                        cancel)), flush=True)


if __name__ == "__main__":
    asyncio.run(main())
Regression-test patch (local commit 23aac47, not pushed)
From 23aac47efa229d9dc8bd6a0d675aecdc5827b691 Mon Sep 17 00:00:00 2001
From: openhands <openhands@all-hands.dev>
Date: Wed, 30 Sep 2026 10:30:56 +0000
Subject: [PATCH] test(llm): cover real byte-flowing async stream stalls

Add live-HTTP regressions for #4997: a chat stream that keeps sending chunks
must end at the per-attempt hard timeout, and a Responses stream that only
sends SSE keepalive comments must hit the idle timeout, retry, and recover.
Both assert the stalled server connection is released. Both fail (hang) on
af3ed3e and pass on 6348597.

Co-authored-by: openhands <openhands@all-hands.dev>
---
 tests/sdk/llm/test_llm_timeout.py | 166 +++++++++++++++++++++++++++---
 1 file changed, 153 insertions(+), 13 deletions(-)

diff --git a/tests/sdk/llm/test_llm_timeout.py b/tests/sdk/llm/test_llm_timeout.py
index 0cd2f02..a0ec235 100644
--- a/tests/sdk/llm/test_llm_timeout.py
+++ b/tests/sdk/llm/test_llm_timeout.py
@@ -223,29 +223,40 @@ class TestLLMTimeoutPassthrough:
 @asynccontextmanager
 async def _hung_chat_completion_server(
     *, keep_sending: bool = False
-) -> AsyncIterator[tuple[str, list[int]]]:
+) -> AsyncIterator[tuple[str, list[int], list[int]]]:
     attempts: list[int] = []
+    finished: list[int] = []
 
     async def completion(request: web.Request) -> web.StreamResponse:
         await request.json()
-        attempts.append(len(attempts) + 1)
+        attempt = len(attempts) + 1
+        attempts.append(attempt)
         response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
         await response.prepare(request)
         chunk = {
-            "id": f"chatcmpl-{attempts[-1]}",
+            "id": f"chatcmpl-{attempt}",
             "object": "chat.completion.chunk",
             "created": 1,
             "model": "test-model",
             "choices": [{"index": 0, "delta": {"role": "assistant", "content": "Hi"}}],
         }
-        while True:
-            await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
-            if not keep_sending:
-                await asyncio.Event().wait()
-            await asyncio.sleep(0.01)
+        try:
+            while True:
+                await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
+                if not keep_sending:
+                    await asyncio.Event().wait()
+                await asyncio.sleep(0.01)
+        finally:
+            finished.append(attempt)
+
+    async with _serve("/chat/completions", completion) as base_url:
+        yield base_url, attempts, finished
+
 
+@asynccontextmanager
+async def _serve(path: str, handler) -> AsyncIterator[str]:
     app = web.Application()
-    app.router.add_post("/chat/completions", completion)
+    app.router.add_post(path, handler)
     runner = web.AppRunner(app, shutdown_timeout=0.01)
     await runner.setup()
     site = web.TCPSite(runner, "127.0.0.1", 0)
@@ -255,14 +266,89 @@ async def _hung_chat_completion_server(
     port = address[1]
     assert isinstance(port, int)
     try:
-        yield f"http://127.0.0.1:{port}", attempts
+        yield f"http://127.0.0.1:{port}"
     finally:
         await runner.cleanup()
 
 
-def _streaming_llm(base_url: str, **kwargs) -> LLM:
+def _sse_event(kind: str, **payload) -> bytes:
+    return f"event: {kind}\ndata: {json.dumps({'type': kind, **payload})}\n\n".encode()
+
+
+def _response_object(attempt: int, status: str, output: list) -> dict:
+    return {
+        "id": f"resp_{attempt}",
+        "object": "response",
+        "created_at": 1,
+        "model": "gpt-5.1-codex",
+        "status": status,
+        "output": output,
+        "parallel_tool_calls": False,
+        "tool_choice": "auto",
+        "tools": [],
+    }
+
+
+@asynccontextmanager
+async def _heartbeat_then_ok_responses_server() -> AsyncIterator[
+    tuple[str, list[int], list[int]]
+]:
+    """First attempt sends only SSE comment heartbeats; later ones complete."""
+    attempts: list[int] = []
+    finished: list[int] = []
+
+    async def responses(request: web.Request) -> web.StreamResponse:
+        await request.json()
+        attempt = len(attempts) + 1
+        attempts.append(attempt)
+        response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
+        await response.prepare(request)
+        created = _response_object(attempt, "in_progress", [])
+        await response.write(
+            _sse_event("response.created", sequence_number=0, response=created)
+        )
+        try:
+            while attempt == 1:
+                await asyncio.sleep(0.05)
+                await response.write(b": keepalive\n\n")
+            message = {
+                "type": "message",
+                "id": f"msg_{attempt}",
+                "role": "assistant",
+                "status": "completed",
+                "content": [
+                    {"type": "output_text", "text": "recovered", "annotations": []}
+                ],
+            }
+            completed = _response_object(attempt, "completed", [message])
+            await response.write(
+                _sse_event(
+                    "response.output_item.done",
+                    sequence_number=1,
+                    output_index=0,
+                    item=message,
+                )
+                + _sse_event(
+                    "response.completed", sequence_number=2, response=completed
+                )
+            )
+            return response
+        finally:
+            finished.append(attempt)
+
+    async with _serve("/responses", responses) as base_url:
+        yield base_url, attempts, finished
+
+
+async def _wait_until(predicate, seconds: float = 5) -> None:
+    async with asyncio.timeout(seconds):
+        while not predicate():
+            await asyncio.sleep(0.01)
+
+
+def _streaming_llm(base_url: str, model: str = "openai/test-model", **kwargs) -> LLM:
     return LLM(
-        model="openai/test-model",
+        model=model,
         api_key=SecretStr("test-key"),
         base_url=base_url,
         usage_id="timeout-test",
@@ -276,7 +362,7 @@ def _streaming_llm(base_url: str, **kwargs) -> LLM:
 
 @pytest.mark.asyncio
 async def test_async_stream_idle_timeout_retries_real_http_stream() -> None:
-    async with _hung_chat_completion_server() as (base_url, attempts):
+    async with _hung_chat_completion_server() as (base_url, attempts, _):
         # The hard timeout needs real headroom: the idle-trigger path takes a
         # couple of seconds here (two attempts to first chunk), so a tight
         # `timeout` would let the outer hard timeout win under CPU contention
@@ -297,6 +383,60 @@ async def test_async_stream_idle_timeout_retries_real_http_stream() -> None:
     assert len(attempts) == 2
 
 
+@pytest.mark.asyncio
+async def test_async_hard_timeout_ends_real_stream_that_never_finishes() -> None:
+    # Chunks keep arriving, so neither the httpx read timeout nor the idle
+    # timeout can fire; only the per-attempt hard timeout ends the call.
+    async with _hung_chat_completion_server(keep_sending=True) as (
+        base_url,
+        attempts,
+        finished,
+    ):
+        llm = _streaming_llm(base_url, timeout=1, num_retries=1)
+
+        async with asyncio.timeout(15):
+            with pytest.raises(LLMTimeoutError, match="hard timeout after 1"):
+                await llm.acompletion(
+                    messages=[
+                        Message(role="user", content=[TextContent(text="Hello")])
+                    ],
+                    on_token=lambda _: None,
+                )
+            await _wait_until(lambda: sorted(finished) == attempts)
+
+    assert attempts == [1]
+
+
+@pytest.mark.asyncio
+async def test_aresponses_idle_timeout_recovers_from_real_heartbeat_stream() -> None:
+    # SSE comment heartbeats keep the socket busy without yielding an event,
+    # the shape of the ChatGPT-subscription stall in #4997.
+    async with _heartbeat_then_ok_responses_server() as (
+        base_url,
+        attempts,
+        finished,
+    ):
+        llm = _streaming_llm(
+            base_url,
+            model="openai/gpt-5.1-codex",
+            timeout=30,
+            stream_idle_timeout=0.5,
+            num_retries=2,
+        )
+
+        async with asyncio.timeout(15):
+            response = await llm.aresponses(
+                [Message(role="user", content=[TextContent(text="Hello")])],
+                on_token=lambda _: None,
+            )
+            await _wait_until(lambda: sorted(finished) == attempts)
+
+    assert attempts == [1, 2]
+    assert [c.text for c in response.message.content if isinstance(c, TextContent)] == [
+        "recovered"
+    ]
+
+
 class _TransportTimeoutStream:
     """Async iterator whose first chunk raises a transport-level TimeoutError."""
 
-- 
2.47.3

🐳 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:6348597-python

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:6348597-golang-amd64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-golang-amd64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-golang-amd64
ghcr.io/openhands/agent-server:6348597-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:6348597-golang-arm64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-golang-arm64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-golang-arm64
ghcr.io/openhands/agent-server:6348597-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:6348597-java-amd64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-java-amd64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-java-amd64
ghcr.io/openhands/agent-server:6348597-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:6348597-java-arm64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-java-arm64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-java-arm64
ghcr.io/openhands/agent-server:6348597-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:6348597-python-amd64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-amd64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-amd64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-amd64
ghcr.io/openhands/agent-server:6348597-python-arm64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-arm64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-arm64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-arm64
ghcr.io/openhands/agent-server:6348597-python-minimal-amd64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-minimal-amd64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-minimal-amd64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-minimal-amd64
ghcr.io/openhands/agent-server:6348597-python-minimal-arm64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-minimal-arm64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-minimal-arm64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-minimal-arm64
ghcr.io/openhands/agent-server:6348597-python-slim-amd64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-slim-amd64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-slim-amd64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-slim-amd64
ghcr.io/openhands/agent-server:6348597-python-slim-arm64
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-slim-arm64
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-slim-arm64
ghcr.io/openhands/agent-server:6348597-python-node-runtime-slim-arm64
ghcr.io/openhands/agent-server:6348597-golang
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-golang
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-golang
ghcr.io/openhands/agent-server:6348597-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:6348597-java
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-java
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-java
ghcr.io/openhands/agent-server:6348597-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:6348597-python-minimal
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-minimal
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-minimal
ghcr.io/openhands/agent-server:6348597-python-node-runtime-minimal
ghcr.io/openhands/agent-server:6348597-python-slim
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python-slim
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python-slim
ghcr.io/openhands/agent-server:6348597-python-node-runtime-slim
ghcr.io/openhands/agent-server:6348597-python
ghcr.io/openhands/agent-server:634859769cb0788f6fc20b2111a0cc876cdfe57b-python
ghcr.io/openhands/agent-server:fix-4997-stream-timeouts-python
ghcr.io/openhands/agent-server:6348597-python-node-runtime

About Multi-Architecture Support

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

Add retry-scoped hard timeouts and per-chunk idle timeouts for async LLM calls. Cover real SSE hangs, retries, Responses streams, and exhausted conversation error state.

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

github-actions Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions github-actions Bot added the release-note-required PR requires explicit release-note coverage for behavioral or default changes label Sep 12, 2026
@github-actions

github-actions Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/llm
   llm.py11669092%747, 786–787, 792, 902, 918, 1163, 1249, 1289–1291, 1328, 1335, 1485, 1613, 1899, 1903–1904, 2105, 2112, 2123, 2208, 2212–2213, 2283, 2290, 2300, 2307, 2318, 2386, 2399, 2417, 2431, 2433, 2435, 2460, 2462, 2471–2472, 2496, 2641, 2797–2798, 2911, 3224–3225, 3234, 3252, 3279–3280, 3282, 3284, 3286, 3294, 3297, 3299, 3301, 3312–3313, 3321, 3324, 3327–3328, 3339–3341, 3345, 3349–3350, 3355, 3365, 3370, 3434, 3436, 3438–3441, 3443–3446, 3451–3454, 3469, 3480, 3540, 3542
TOTAL444101248172% 

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig
neubig force-pushed the fix/4997-stream-timeouts branch from 1b79602 to 7729bc8 Compare September 12, 2026 16:09
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
@neubig
neubig force-pushed the fix/4997-stream-timeouts branch from de4203f to 443c446 Compare September 12, 2026 16:36
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@neubig
neubig marked this pull request as draft September 12, 2026 21:26
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🤖 OpenHands is reviewing this PR.

Head commit: 8c0dd7a5af0650662dc8518ed455b3e4b49edea1
View the conversation: https://oss-agent-canvas.ngrok.dev/conversations/efc81730-8984-43ee-91ef-84ace2f57da2

This comment was posted by an AI agent (OpenHands).

@all-hands-bot all-hands-bot 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.

This review was created by an AI agent (OpenHands) on behalf of the repository maintainers.

Summary

This PR adds two timeout mechanisms for async LLM streaming:

  1. Hard per-attempt timeout (_async_hard_timeout_decorator): wraps each retry attempt with asyncio.timeout(self.timeout), raising LiteLLMTimeout when expired.
  2. Stream idle timeout (_aiter_with_idle_timeout): wraps each anext() call with asyncio.wait_for(..., timeout=stream_idle_timeout), so receiving a chunk resets the idle deadline.

Both are placed inside the tenacity retry decorator, so timeouts are retryable per attempt and eventually map to LLMTimeoutError after retries are exhausted. The stream_idle_timeout field defaults to the existing timeout value via _coerce_inputs, preserving backward compatibility.

Code Quality

The implementation is clean and correct:

  • Decorator ordering (@retry -> @hard_timeout -> function body) is right — each attempt gets its own hard timeout, and the retry layer can retry on LiteLLMTimeout.
  • Idle timeout wrapping each anext() is the right granularity — a slow-but-alive stream will not trip it, only a truly hung one will.
  • LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so both timeout types are retried automatically.
  • _coerce_inputs defaulting stream_idle_timeout to timeout is backward compatible.
  • Tests include a real aiohttp server that hangs mid-stream, verifying the retry path end-to-end.

No material bugs found.

PR Description Mismatch

The PR title and actual code changes match, but the HUMAN and AGENT sections of the PR description appear to be from a different PR (they describe TypeScript lifecycle adapters and reference npm test commands). The issue number (#4997) and the REST API contract summary (stream_idle_timeout schema addition) do match the code. Worth cleaning up the description before merge.

Eval Risk

This PR changes LLM streaming behavior (adds async hard timeout + per-chunk idle timeout). While the defaults (300s) match the existing timeout and should not affect normal benchmark operation, this falls in the eval-risk category. No eval monitor link or human eval confirmation was found in PR comments. Flagging for a human maintainer to decide after running lightweight evals.

Risk Assessment: MEDIUM — Low probability of benchmark impact (timeouts only fire on genuinely hung/slow streams), but the change touches LLM calling behavior so eval validation is warranted.

@neubig

neubig commented Sep 12, 2026

Copy link
Copy Markdown
Member Author

Corrected the AGENT description to describe the async stream timeout implementation and its Python validation, preserving the generated API summary and image links. The HUMAN text remains untouched and still refers to the unrelated lifecycle change; that section needs its human author to correct it. The lightweight maintainer eval recommendation remains documented.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🤖 OpenHands is reviewing this PR.

Head commit: ba6c21735e44c28d476563e74ea8765d22c666a1
View the conversation: https://oss-agent-canvas.ngrok.dev/conversations/ad57aaf8-2f1d-4e31-b8dd-97bc8bf582e9

This comment was posted by an AI agent (OpenHands).

@all-hands-bot all-hands-bot 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.

This review was created by an AI agent (OpenHands) on behalf of the repository maintainers.

Summary

This PR adds two layers of async stream timeout protection to the LLM layer:

  1. Hard per-attempt timeout (_async_hard_timeout_decorator) — wraps each retryable attempt with asyncio.timeout(self.timeout), placed inside the tenacity retry decorator so each attempt is individually bounded and retryable.
  2. Stream idle timeout (_aiter_with_idle_timeout) — wraps each __anext__() call with asyncio.wait_for, so a stalled mid-stream chunk fails fast.

Both raise LiteLLMTimeout (already in LLM_RETRY_EXCEPTIONS), so they integrate with existing retry/error-mapping infrastructure and eventually surface as LLMTimeoutError after retries are exhausted. The design is clean and the decorator ordering (retry → hard_timeout → _one_attempt) is correct.

The tests are solid — a real HTTP server that stalls mid-stream, a direct hard-timeout unit test, an end-to-end conversation error-state test, and an aresponses path test. These exercise real code paths rather than just asserting mock calls.

Finding

One edge case worth noting (see inline comment on _aiter_with_idle_timeout): when the hard timeout fires while _aiter_with_idle_timeout is awaiting a chunk, the TimeoutError from asyncio.timeout() propagates through asyncio.wait_for() and is caught by the idle-timeout except TimeoutError block, which mislabels it as "stream idle timeout" with the idle-timeout duration rather than "hard timeout" with the hard-timeout duration. This is functionally harmless (both raise LiteLLMTimeout → retried → LLMTimeoutError), but could produce misleading error messages when stream_idle_timeout > timeout. In practice this is unlikely since they default to the same value.

Eval Risk

This PR changes LLM calling behavior (adding timeout enforcement to async streams). While the 300s defaults are generous and unlikely to affect normal benchmark runs, this could plausibly affect evaluation performance in edge cases (e.g., very long reasoning model responses). No eval monitor link or human eval confirmation is present in the PR description or comments. Flagging for human maintainer eval review before merge.

Risk Assessment

🟡 Medium — Well-designed fix for a real problem (hung async streams holding conversations indefinitely). No security issues, no breaking API changes (new optional field with backward-compatible default). The main risk is the behavioral change to LLM stream handling, which warrants eval validation.

Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
@all-hands-bot

Copy link
Copy Markdown
Collaborator

⚠️ OpenHands gave up on this review for commit ba6c21735e44 after 2h (last state: active).

This comment was posted by an AI agent (OpenHands).

@github-actions

github-actions Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor
  ✅ **PR Artifacts Cleaned Up**

  The `.pr/` directory is no longer present.

@neubig

neubig commented Sep 13, 2026

Copy link
Copy Markdown
Member Author

Please review the current head and its linked live evidence. If there are no remaining actionable findings, please submit an APPROVE review rather than a COMMENT-only review. If changes are still needed, identify them explicitly. This request is for code-review approval; it does not waive any separate human-note, CI, or dependency requirements.

@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot September 13, 2026 18:06

@all-hands-bot all-hands-bot 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.

This review was created by an AI agent (OpenHands) on behalf of the repository maintainers.

Overview

This PR bounds async LLM streams with two complementary timeouts: a hard per-attempt timeout (asyncio.timeout(self.timeout)) wrapping each retry attempt, and a stream idle timeout (asyncio.wait_for on each __anext__) that detects stalled streams between chunks. Both raise LiteLLMTimeout, which flows through the existing retry → error-mapping pipeline as LLMTimeoutError. The design is clean — the decorator ordering (retry outer, hard-timeout inner) means each retry attempt is independently bounded, and the idle timeout wrapping at stream consumption points correctly resets the idle deadline on each chunk.

Analysis

No material bugs found. The implementation is sound:

  • The LiteLLMTimeout exceptions raised by both timeout paths are already in LLM_RETRY_EXCEPTIONS, so stalled calls will retry as expected.
  • _coerce_inputs correctly defaults stream_idle_timeout to match timeout when not explicitly provided, preserving backward compatibility.
  • The timeout_context.expired() check in the hard timeout decorator correctly distinguishes timeouts raised by the asyncio context from TimeoutError raised by inner code.
  • The REST API contract change is additive (stream_idle_timeout on LLM input/output schemas), not breaking.
  • Tests exercise real HTTP streaming (_hung_chat_completion_server), the decorator directly, the responses API path, and conversation-level error transition — good coverage of the new behavior.

One design note (not blocking): The sync completion/responses paths do not get the hard timeout decorator — they rely solely on LiteLLM's HTTP timeout kwarg. This is fine for the stated issue (#4997 targets async streams), but worth noting that sync streaming with slow-but-continuous chunks could still hang past the configured timeout, since the sync _transport_call drains the iterator with a plain for chunk in stream loop. Not a regression (this is pre-existing behavior), just an asymmetry to be aware of.

Eval Risk

This PR changes LLM stream timeout behavior. In normal operation (streams that complete within the 300s default), behavior is identical — the new enforcement only fires for stalled or excessively long streams, which previously hung indefinitely. However, a legitimate long-running streaming response that takes longer than timeout seconds total (but keeps sending chunks) will now be killed by the hard timeout, where previously it could continue indefinitely. This is arguably correct (the configured timeout should be enforced), but it is a behavioral change.

Per the repo review policy, flagging for a human maintainer to decide whether lightweight evals are needed before merging.

Risk Assessment

🟡 Medium — The change is well-implemented and backward-compatible for normal operation, but it introduces new timeout enforcement that could affect long-running streaming completions. No security concerns, no breaking API changes, good test coverage. Recommending a human maintainer eval check given the behavior change in stream timeout semantics.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

⚠️ Review paused: current-head checks did not pass

The current head bafec89f40ec has checks that did not pass, so no review conversation was started:

  • pre-commit

Fix the checks above and push. The scheduled scan then starts the review on the updated head.

This is an automated check - no AI was used to generate this comment.

The merge resolution collapsed the two blank lines ruff format requires
between top-level defs, which made the pre-commit Ruff format hook rewrite
the file and fail CI.

Tests: tests/sdk/llm/test_llm_timeout.py and
tests/sdk/llm/test_responses_parsing_and_kwargs.py - 33 passed.

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

This change belongs in this repository (openhands-sdk owns LLM call behavior) and has the architecture direction it needs: it is an independent bug fix for #4997, not the TypeScript lifecycle work described in the copied #4996 HUMAN/AGENT text. HEAD is f3ae870, matching the requested SHA. All current-head checks pass.

Summary

The PR bounds async LLM streams two ways: _async_hard_timeout_decorator wraps each retry attempt in asyncio.timeout(self.timeout), and _aiter_with_idle_timeout wraps each anext() with asyncio.wait_for. Both are placed inside the tenacity retry decorator (@self._make_retry_decorator() then @self._async_hard_timeout_decorator()), so an expired attempt is retryable; both raise LiteLLMTimeout, which is already in LLM_RETRY_EXCEPTIONS and maps to LLMTimeoutError once retries are exhausted. stream_idle_timeout defaults to timeout via _coerce_inputs, so existing profiles without the field keep prior behavior.

Verification against the linked issue

#4997 is open with ready-for-dev, bug, llm, priority:high. Its acceptance criteria are: (1) a stream-level idle timeout, (2) a hard per-call timeout, (3) retry then conversation ERROR on exhaustion, and (4) a test that fails on base and passes on the branch. All four are met on this head:

  • Idle and hard timeouts are implemented as above; only enable_streaming and on_token is not None is affected, so non-streaming calls keep LiteLLM's HTTP timeout.
  • _timeout_error builds a LiteLLMTimeout, which routes through the existing retry/error mapping; test_exhausted_stream_timeout_transitions_conversation_to_error asserts the conversation reaches ConversationExecutionStatus.ERROR.
  • Real-code-path tests: an aiohttp server that hangs mid-stream (test_async_stream_idle_timeout_retries_real_http_stream), a direct decorator test, and an aresponses path test.

The prior stream-scope comment on _aiter_with_idle_timeout is resolved: the outer asyncio.timeout() delivers cancellation, not a bare TimeoutError, so inner code is not mislabeled, and the author supplied a live run (timeout=3, stream_idle_timeout=300) reporting LLM hard timeout after 3 seconds. The hard-timeout helper is byte-identical to the candidate commit ba6c217 referenced by the live evidence, and the post-evidence change to llm.py was only the merge of main (model bump / auth refresh), so the evidence still describes this head.

Eval risk (maintainer decision)

This alters model-stream timeout behavior, so the repo's live-evidence review path applies; the linked issue (priority:high, ready-for-dev) prescribes the required evidence, which is present. Per the review guide, the open item for the human maintainer is whether to run lightweight evals, since a legitimately long stream that keeps sending chunks but exceeds timeout in total duration will now be aborted. No Run tests, Run Examples Scripts, or Run Integration Tests PR-specific result/comment was located in the review threads for this head; if the maintainer's process treats that absence as required validation for an LLM-behavior change, that should be confirmed before merge. This is a process judgment, not a code defect.

Non-blocking notes (not findings)

  • The sync _transport_call drains for chunk in stream with no per-chunk idle or total bound, so a hung sync stream is not covered. This is pre-existing and outside the async-only scope of #4997.
  • stream_idle_timeout is not passed to the LiteLLM transport (only timeout is, in _prepare_transport_kwargs), so no provider-side keyword collision.

✅ APPROVED

@VascoSch92

Copy link
Copy Markdown
Member

I think I already fixed it... Also two weeks ago and it is already merged and released.

Is this still relevant or another problem?

@neubig
neubig marked this pull request as ready for review September 28, 2026 15:02

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

This belongs in this repository: openhands-sdk owns LLM call behavior, and this is an independent bug fix for #4997 (not the TypeScript lifecycle work quoted in the copied #4996 HUMAN/AGENT text). HEAD is 21e93ebb, matching the requested SHA.

What changed

Async LLM streams are now bounded two ways, both inside the tenacity retry decorator (@self._make_retry_decorator() then @self._async_hard_timeout_decorator() on _one_attempt in acompletion and aresponses):

  • _async_hard_timeout_decorator wraps each attempt in asyncio.timeout(self.timeout), converting an expired context into LiteLLMTimeout("LLM hard timeout after N seconds").
  • _aiter_with_idle_timeout wraps each anext() in asyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raises LiteLLMTimeout("LLM stream idle timeout after N seconds").

LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so both paths retry and map to LLMTimeoutError on exhaustion. stream_idle_timeout defaults to timeout via _coerce_inputs, so existing profiles without the field keep prior behavior. Only the streaming-with-callback branch is affected; non-streaming calls keep LiteLLM's HTTP timeout.

Verification on this head

  • tests/sdk/llm/test_llm_timeout.py + tests/sdk/llm/test_responses_parsing_and_kwargs.py: 33 passed locally. Coverage includes a real aiohttp server that hangs mid-stream (asserts retry count), a direct hard-timeout test, an aresponses hung-stream test, and a conversation-level ERROR transition test.
  • All current-head GitHub Actions checks pass (including pre-commit, sdk-tests, integration-test, REST API (OpenAPI), Persisted settings).
  • Linked #4997 is OPEN with bug, llm, priority:high, security-related, ready-for-dev; its four acceptance criteria (idle timeout, hard timeout, retry→ERROR, failing-on-base test) are met.
  • The prior inline thread on _aiter_with_idle_timeout is resolved: the outer asyncio.timeout() delivers cancellation rather than a bare TimeoutError, so the idle handler does not mislabel it, and the author's live run (timeout=3, stream_idle_timeout=300) reported LLM hard timeout after 3 seconds.
  • The openhands-sdk/openhands/sdk/llm/llm.py blob is unchanged (c9cc7307) from the previously reviewed head; this head only removed the .pr/ artifacts and merged main. The live before/after evidence linked in the PR body remains reachable at its immutable commit blob.

Eval risk (maintainer decision)

Per the review guide's agent-behavior section, missing optional eval evidence is not a code defect and does not by itself justify withholding approval, so this is flagged rather than treated as a finding. The concrete behavioral change: a legitimate long stream that keeps sending chunks but exceeds timeout in total duration will now be aborted by the hard timeout, where it previously could run indefinitely. The default (300s) only fires on pathological stalls, so regression probability is low, but the maintainer may want a lightweight eval given this alters model-stream timeout semantics. This is the only open item.

Non-blocking notes (not findings)

  • The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream is not covered. This is pre-existing and outside the async-only scope of #4997.
  • stream_idle_timeout is not forwarded to the LiteLLM transport (only timeout is, in _prepare_transport_kwargs), so there is no provider keyword collision.

No material correctness, security, or compatibility defects found on this head.

✅ APPROVED

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

This belongs in this repository (openhands-sdk owns LLM call behavior); it is an independent bug fix for #4997, not the TypeScript lifecycle work quoted in the copied #4996 HUMAN/AGENT text. HEAD is 21e93ebb, matching the requested SHA.

Material finding: the PR no longer merges cleanly

GitHub now reports this PR mergeable: CONFLICTING. Resolving against the current origin/main (af3ed3ed) with git merge-tree shows content conflicts in two changed files:

  • openhands-sdk/openhands/sdk/llm/llm.py
  • tests/sdk/llm/test_responses_parsing_and_kwargs.py

The conflicts are not in the timeout logic itself. main has since refactored LLMCallContext out of openhands/sdk/llm/llm.py into openhands.sdk.llm.call_context (with a deprecated re-export) and removed the LLM._call_context private attr (#4159), and the PR head still imports/touches openhands.sdk.llm.llm.LLMCallContext. main does not yet contain stream_idle_timeout, _aiter_with_idle_timeout, or _async_hard_timeout_decorator, so the feature is unmerged and the conflict is confined to imports/call-context plumbing — a rebase should be straightforward, but the PR cannot be merged until it is resolved. The author needs to rebase onto current main.

Code assessment (unchanged from the prior approval at this head)

The timeout implementation is sound and I found no correctness, security, or compatibility defect on this head:

  • _async_hard_timeout_decorator wraps each retry attempt in asyncio.timeout(self.timeout), raising LiteLLMTimeout on expiry; _aiter_with_idle_timeout wraps each anext() in asyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline.
  • Both decorators sit inside the tenacity retry decorator on _one_attempt in acompletion/aresponses; LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so timeouts retry and map to LLMTimeoutError on exhaustion.
  • stream_idle_timeout defaults to timeout via _coerce_inputs, preserving behavior for existing profiles; only the streaming-with-callback branch is affected.
  • tests/sdk/llm/test_llm_timeout.py + tests/sdk/llm/test_responses_parsing_and_kwargs.py: 33 passed locally on this head, including a real aiohttp mid-stream stall and a conversation-level ERROR transition. All current-head Actions checks pass (pre-commit, sdk-tests, integration-test, REST API (OpenAPI), Persisted settings).
  • Linked #4997 is OPEN with bug, llm, priority:high, security-related, ready-for-dev; its acceptance criteria are met. The single prior inline thread is resolved.

Eval risk (maintainer decision)

The change alters model-stream timeout semantics: a legitimate long stream that keeps sending chunks but exceeds timeout in total duration will now be aborted by the hard timeout. Defaults (300s) only fire on pathological stalls, so regression probability is low, but the maintainer may want a lightweight eval. Per the review guide this is flagged, not treated as a defect.

Non-blocking notes

  • The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream is not covered. Pre-existing and outside the async-only scope of #4997.
  • stream_idle_timeout is not forwarded to the LiteLLM transport (only timeout is, in _prepare_transport_kwargs), so there is no provider keyword collision.

The implementation is correct and previously approved; the only action required before merge is a rebase onto current main.

🔄 CHANGES REQUESTED

Resolve llm.py and test_responses_parsing_and_kwargs.py: keep this branch's
Awaitable/TypeVar imports and timeout helpers, take main's refactor that moved
LLMCallContext into openhands.sdk.llm.call_context (deprecated shim retained),
and drop the now-unused dataclasses import.
@neubig

neubig commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

@VascoSch92 thanks — this is a different problem from #5203/#5204. Yours fixed each Responses chunk being misread as a new attempt (streaming looked disabled and text was dropped); #4997 is a stream that connects and then never delivers another chunk, so the await never returns and the conversation sits in RUNNING with no events, no error, and no timeout.

I verified this in openhands-sdk==1.49.6 from PyPI: your id=event.item_id fix is in _process_stream_event, but there is no idle or hard timeout anywhere in the async path, so the hang is still present in released versions.

The pre-commit failure you saw on bafec89f was stale — I've merged current main (af3ed3ed) into the branch and pushed 1d50d2e0; the branch is now mergeable, all checks pass, and the focused tests are green (33 in test_llm_timeout.py/test_responses_parsing_and_kwargs.py).

This comment was posted by an AI agent (OpenHands) on behalf of @neubig.

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

Belongs in this repository (openhands-sdk owns LLM call behavior); it is an independent bug fix for #4997, not the TypeScript lifecycle work quoted in the copied #4996 HUMAN/AGENT text. HEAD is 1d50d2e, matching the reviewed SHA.

Rebase check

The prior CONFLICTING state is resolved: GitHub now reports MERGEABLE. The rebase onto current main correctly incorporated main's LLMCallContext relocation into openhands.sdk.llm.call_context (plus the deprecated __getattr__ re-export) and the call_context= threading, while preserving the timeout changes. The tests/sdk/llm/test_responses_parsing_and_kwargs.py conflict is likewise resolved in favor of the new LLMCallContext import path. No timeout logic was altered by the rebase.

Change assessment

Two complementary bounds, both inside the tenacity retry decorator on _one_attempt in acompletion/aresponses:

  • _async_hard_timeout_decorator wraps each attempt in asyncio.timeout(self.timeout), raising LiteLLMTimeout when the context expires.
  • _aiter_with_idle_timeout wraps each anext() in asyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raises LiteLLMTimeout.

LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so both paths retry and map to LLMTimeoutError on exhaustion. stream_idle_timeout defaults to timeout via _coerce_inputs, preserving behavior for existing profiles; only the streaming-with-callback branch is affected. I found no correctness, security, or compatibility defect.

Verification on this head

  • tests/sdk/llm/test_llm_timeout.py + tests/sdk/llm/test_responses_parsing_and_kwargs.py: 33 passed locally, including a real aiohttp mid-stream stall (retry-count asserted), a direct hard-timeout test, an aresponses hung-stream test, and a conversation-level ERROR transition.
  • All current-head Actions checks pass (pre-commit, sdk-tests, integration-test, REST API (OpenAPI), Persisted settings).
  • Linked #4997 is OPEN with bug, llm, priority:high, security-related, ready-for-dev; its four acceptance criteria (idle timeout, hard timeout, retry→ERROR, failing-on-base test) are met.
  • The single prior inline thread on _aiter_with_idle_timeout is resolved: the outer asyncio.timeout() delivers cancellation rather than a bare TimeoutError, so the idle handler does not mislabel it.

Eval risk (maintainer decision)

The change alters model-stream timeout semantics: a legitimate long stream that keeps sending chunks but exceeds timeout in total duration will now be aborted by the hard timeout. Defaults (300s) only fire on pathological stalls, so regression probability is low, but the maintainer may want a lightweight eval. Per the review guide this is flagged, not treated as a defect.

Non-blocking notes

  • The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream is not covered. Pre-existing and outside the async-only scope of #4997.
  • stream_idle_timeout is not forwarded to the LiteLLM transport (only timeout is, in _prepare_transport_kwargs), so there is no provider keyword collision.

No material findings on this head.

✅ APPROVED

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

Belongs in this repository (openhands-sdk owns LLM call behavior); it is an independent bug fix for #4997, not the TypeScript lifecycle work quoted in the copied #4996 HUMAN/AGENT text. HEAD is 1d50d2e, matching the reviewed SHA.

Change assessment

Two complementary bounds, both inside the tenacity retry decorator on _one_attempt in acompletion/aresponses:

  • _async_hard_timeout_decorator wraps each attempt in asyncio.timeout(self.timeout), raising LiteLLMTimeout when the context expires.
  • _aiter_with_idle_timeout wraps each anext() in asyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raises LiteLLMTimeout.

LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so both paths retry and map to LLMTimeoutError on exhaustion. stream_idle_timeout defaults to timeout via _coerce_inputs, preserving behavior for existing profiles; only the streaming-with-callback branch is affected. The rebase onto current main cleanly incorporated main's LLMCallContext relocation into openhands.sdk.llm.call_context (with the deprecated __getattr__ re-export) without altering the timeout logic. No correctness, security, or compatibility defect found.

Verification on this head

  • tests/sdk/llm/test_llm_timeout.py + tests/sdk/llm/test_responses_parsing_and_kwargs.py: 33 passed locally, including a real aiohttp mid-stream stall (retry-count asserted), a direct hard-timeout test, an aresponses hung-stream test, and a conversation-level ERROR transition.
  • All current-head Actions checks pass (pre-commit, sdk-tests, integration-test, REST API (OpenAPI), Persisted settings). GitHub reports the PR MERGEABLE.
  • Linked #4997 is OPEN with bug, llm, priority:high, security-related, ready-for-dev; its four acceptance criteria (idle timeout, hard timeout, retry→ERROR, failing-on-base test) are met.
  • The single prior inline thread on _aiter_with_idle_timeout is resolved: the outer asyncio.timeout() delivers cancellation rather than a bare TimeoutError, so the idle handler does not mislabel it.

Eval risk (maintainer decision)

The change alters model-stream timeout semantics: a legitimate long stream that keeps sending chunks but exceeds timeout in total duration will now be aborted by the hard timeout. Defaults (300s) only fire on pathological stalls, so regression probability is low, but the maintainer may want a lightweight eval. Per the review guide this is flagged, not treated as a defect.

Non-blocking notes

  • The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream is not covered. Pre-existing and outside the async-only scope of #4997.
  • stream_idle_timeout is not forwarded to the LiteLLM transport (only timeout is, in _prepare_transport_kwargs), so there is no provider keyword collision.

No material findings on this head.

✅ APPROVED

@all-hands-bot
all-hands-bot requested a review from enyst September 29, 2026 05:04

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

Belongs in this repository: openhands-sdk owns LLM call behavior. This is an independent bug fix for #4997 (the HUMAN: text quoting #4996/TypeScript lifecycle work is stale copy; #4996 is a different issue). Head 1d50d2e matches the requested SHA, all current-head checks pass, and the single prior inline thread is resolved.

Findings

I verified the timeout logic by running the focused suite and targeted probes on this head. Two material issues remain.

1. _aiter_with_idle_timeout asserts when the idle timeout is disabled (llm.py:1189-1191)

stream_idle_timeout is documented and tested as disableable with None. With timeout=300, stream_idle_timeout=None, the timeout is None branch awaits anext() unguarded, but this except TimeoutError handler still runs and hits assert timeout is not None, so the original exception is replaced by an AssertionError (reproduced directly on this head). It also relabels any genuine transport TimeoutError as "stream idle timeout" even when the idle timer never fired; note litellm.Timeout is not a builtins.TimeoutError subclass, so a provider-side timeout is a plausible source. Scope is narrow (requires an explicit stream_idle_timeout=None, not the default), but it turns a recoverable timeout into a crash.

2. test_async_stream_idle_timeout_retries_real_http_stream is flaky (test_llm_timeout.py:287)

The test uses timeout=2 with stream_idle_timeout=0.05 and requires the raised LLMTimeoutError to match "idle timeout". The nominal idle-trigger path is ~1.9s (two attempts at ~0.75s to first chunk plus 0.05s idle), leaving only ~0.1s of headroom against the 2s hard timeout, so under CPU contention the outer asyncio.timeout(2) fires first and the error reads "LLM hard timeout after 2 seconds". Observed on this head: 1 failure / 12 sequential runs, and 1 failure / 32 runs with four concurrent loops. CI runs sdk-tests with pytest -n auto, which schedules tests concurrently, so this is a real CI-flake risk.

Notes (non-blocking)

  • The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream remains uncovered. Pre-existing and outside the async-only scope of #4997.
  • The hard timeout also bounds total streaming duration per attempt, so a legitimate stream that keeps sending chunks past timeout is now aborted. The 300s default only fires on pathological stalls, but this is the eval risk the maintainer should weigh.

🔄 CHANGES REQUESTED

Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread tests/sdk/llm/test_llm_timeout.py Resolved
Only convert a TimeoutError into the idle-timeout error when the idle
timer actually expired. With stream_idle_timeout=None the awaited chunk
was unguarded, yet the shared handler still ran and hit an assert, so a
genuine transport TimeoutError surfaced as AssertionError and a real
timeout was mislabelled as an idle timeout.

Await each chunk under asyncio.timeout instead of asyncio.wait_for so a
transport-raised TimeoutError keeps its identity, matching the attribution
logic already used by the hard-timeout decorator.

Give the real-HTTP idle-timeout test hard-timeout headroom (timeout=30)
so CPU contention cannot let the outer hard timeout win and flake CI's
pytest -n auto runs.

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot September 29, 2026 17:44
@neubig

neubig commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

Addressed both unresolved review findings from the last review on 1d50d2e; head is now 6348597.

1. Real transport TimeoutError is preserved (llm.py). The conversion is now isolated in _anext_with_idle_timeout, which awaits the chunk under asyncio.timeout(timeout) and only raises the idle-timeout error when timeout_context.expired() is true. Otherwise the original exception propagates unchanged. This removes the assert timeout is not None entirely, so stream_idle_timeout=None no longer turns a transport timeout into an AssertionError, and an enabled idle timer no longer mislabels a transport-raised TimeoutError. Using asyncio.timeout instead of asyncio.wait_for is deliberate: wait_for cannot tell its own expiry from a TimeoutError raised inside the awaited operation.

2. Flaky idle-timeout test de-flaked (test_llm_timeout.py). test_async_stream_idle_timeout_retries_real_http_stream now uses timeout=30 (was 2) while keeping stream_idle_timeout=0.05 and the len(attempts) == 2 retry assertion, giving ~28s of hard-timeout headroom instead of ~0.1s.

Added regression tests, verified to fail on the pre-fix head: transport TimeoutError with stream_idle_timeout=None, transport TimeoutError with the idle timer enabled, the same through the outer hard-timeout decorator, plus hard-timeout and genuine idle-timeout attribution checks.

Verification: tests/sdk/llm/test_llm_timeout.py 19 passed; full tests/sdk/llm 1072 passed; the HTTP test 60/60 across 20 sequential and 40 four-way-concurrent runs; ruff, ruff-format, pycodestyle, pyright, and the import/dynamic-attribute/tool-registration checks all clean. Pre-commit checks, Run tests, and Review Thread Gate pass on 6348597.

@all-hands-bot re-requested as reviewer. Please review 6348597 and, if there are no remaining actionable findings, submit an APPROVE review rather than a COMMENT-only review.

This comment was posted by an AI agent (OpenHands) on behalf of @neubig.

@all-hands-bot all-hands-bot 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.

This review was posted by an AI agent (OpenHands).

Scope

Belongs in this repository: openhands-sdk owns LLM call behavior. This is an independent bug fix for #4997. The HUMAN: text quoting #4996 (TypeScript lifecycle work) is stale copy and does not describe this diff. Head 6348597 matches the requested SHA; #4997 is OPEN with bug, llm, priority:high, security-related, ready-for-dev; all three prior review threads are resolved and the latest unresolved-review-threads run on this head passes.

Change assessment

Two bounds, both inside the tenacity retry decorator on _one_attempt in acompletion/aresponses:

  • _async_hard_timeout_decorator wraps each attempt in asyncio.timeout(self.timeout) and raises LiteLLMTimeout only when timeout_context.expired().
  • _aiter_with_idle_timeout / _anext_with_idle_timeout wrap each chunk await in asyncio.timeout(stream_idle_timeout), so a received chunk resets the deadline and a stalled stream raises LiteLLMTimeout.

LiteLLMTimeout is already in LLM_RETRY_EXCEPTIONS, so both paths retry and map to LLMTimeoutError on exhaustion. stream_idle_timeout defaults to timeout via _coerce_inputs, preserving behavior for existing profiles; only the async streaming-with-callback branch is affected.

Prior findings — verified fixed on this head

Both issues raised on 1d50d2e are resolved:

  1. Idle-timeout attribution. _anext_with_idle_timeout now converts an error only when its own timer expired and otherwise re-raises unchanged; the assert timeout is not None is gone. I reproduced the old AssertionError on the prior head with stream_idle_timeout=None and a transport TimeoutError; on this head both stream_idle_timeout=None and stream_idle_timeout=30 propagate the original TimeoutError unchanged.
  2. Flaky real-HTTP test. The hard timeout now has real headroom (timeout=30 vs a ~1.9s idle-trigger path). I reproduced 1 failure / 32 runs under four concurrent loops on the prior head; on this head the test passed 60/60 under the same four concurrent loops, and 20/20 sequentially.

Verification on this head

  • tests/sdk/llm/test_llm_timeout.py + tests/sdk/llm/test_responses_parsing_and_kwargs.py: 39 passed.
  • Full tests/sdk/llm: 1073 passed; the only 2 failures (auth/test_credentials.py::test_get_credentials_dir_default, ::test_get_credentials_dir_xdg) also fail on base main and are caused by this sandbox's HOME, unrelated to the diff.
  • New regression tests cover transport-timeout passthrough (None and enabled), hard-vs-idle attribution, and the genuine idle-timeout path.

Eval risk (maintainer decision)

The hard timeout also bounds total streaming duration per attempt, so a legitimate stream that keeps sending chunks but exceeds timeout in total duration is now aborted. The 300s default only fires on pathological stalls, so regression probability is low, but a lightweight maintainer eval remains appropriate.

Non-blocking note

The sync _transport_call still drains for chunk in stream with no per-chunk idle or total bound; a hung sync stream is not covered. Pre-existing and outside the async-only scope of #4997.

No material findings on this head.

✅ APPROVED

@all-hands-bot

Copy link
Copy Markdown
Collaborator

Review of 6348597

Re-requested by @neubig. I verified the diff directly rather than relying on the summary.

Both prior findings are fixed.

  1. Transport TimeoutError preserved. _anext_with_idle_timeout awaits the chunk under asyncio.timeout(timeout) and converts only when timeout_context.expired() is true; otherwise it re-raises unchanged. The assert timeout is not None is gone. I reproduced the old AssertionError on 1d50d2e (transport TimeoutError with stream_idle_timeout=None) and confirmed the fixed behavior on this head: both stream_idle_timeout=None and stream_idle_timeout=30 propagate the original TimeoutError unchanged, and litellm.Timeout (not a builtins.TimeoutError subclass) also passes through unrelabelled.

  2. Flaky real-HTTP test de-flaked. timeout=30 against a ~1.9s idle-trigger path. On this head the test passed 20/20 sequentially and 40/40 under four-way concurrency; the prior head showed 1 failure / 32 runs under the same concurrency.

Verification I ran on this head

  • tests/sdk/llm/test_llm_timeout.py: 19 passed; tests/sdk/llm/test_responses_parsing_and_kwargs.py: 20 passed.
  • The new regression tests fail on the pre-fix llm.py (4 failures: AssertionError plus a mislabeled idle timeout), so they genuinely cover the fixed behavior rather than passing vacuously.
  • Full tests/sdk/llm: 1073 passed. The only 2 failures (auth/test_credentials.py::test_get_credentials_dir_default, ::test_get_credentials_dir_xdg) also fail on base main and are caused by this sandbox's HOME, unrelated to the diff.
  • Targeted probes: idle attribution (LLM stream idle timeout after 0.05 seconds), hard-timeout attribution while the inner idle timer is enabled (LLM hard timeout after 1 seconds), timeout=None (hard timer disabled, idle still fires), stream_idle_timeout=0, and task.cancel() → CancelledError (the interrupt path is unaffected).
  • ruff / ruff-format clean; all three review threads resolved; current-head CI passes, including unresolved-review-threads.

Decision: no remaining actionable findings — APPROVE. An APPROVE review is already recorded on this head (review id 5356602501, commit 6348597), so I am not duplicating it with a second review.

Non-blocking notes: the sync _transport_call still drains for chunk in stream with no per-chunk or total bound (pre-existing, outside the async-only scope of #4997), and the hard timeout now also caps total streaming duration per attempt, which a maintainer may want to weigh with a lightweight eval.

Generated by OpenHands AI on behalf of the user.

@neubig
neubig merged commit 656a5c4 into main Sep 30, 2026
62 of 63 checks passed
@neubig
neubig deleted the fix/4997-stream-timeouts branch September 30, 2026 02:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note-required PR requires explicit release-note coverage for behavioral or default changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Conversations stall indefinitely when ChatGPT subscription LLM call hangs

4 participants