Repository navigation
fix(llm): time out hung async streams - #5000
Conversation
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>
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
Co-authored-by: openhands <openhands@all-hands.dev>
1b79602 to
7729bc8
Compare
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
de4203f to
443c446
Compare
|
🚦 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 This is an automated check - no AI was used to generate this comment. |
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
all-hands-bot
left a comment
There was a problem hiding this comment.
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:
- Hard per-attempt timeout (
_async_hard_timeout_decorator): wraps each retry attempt withasyncio.timeout(self.timeout), raisingLiteLLMTimeoutwhen expired. - Stream idle timeout (
_aiter_with_idle_timeout): wraps eachanext()call withasyncio.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 onLiteLLMTimeout. - Idle timeout wrapping each
anext()is the right granularity — a slow-but-alive stream will not trip it, only a truly hung one will. LiteLLMTimeoutis already inLLM_RETRY_EXCEPTIONS, so both timeout types are retried automatically._coerce_inputsdefaultingstream_idle_timeouttotimeoutis 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.
|
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. |
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
all-hands-bot
left a comment
There was a problem hiding this comment.
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:
- Hard per-attempt timeout (
_async_hard_timeout_decorator) — wraps each retryable attempt withasyncio.timeout(self.timeout), placed inside the tenacity retry decorator so each attempt is individually bounded and retryable. - Stream idle timeout (
_aiter_with_idle_timeout) — wraps each__anext__()call withasyncio.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.
|
This comment was posted by an AI agent (OpenHands). |
|
|
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. |
all-hands-bot
left a comment
There was a problem hiding this comment.
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
LiteLLMTimeoutexceptions raised by both timeout paths are already inLLM_RETRY_EXCEPTIONS, so stalled calls will retry as expected. _coerce_inputscorrectly defaultsstream_idle_timeoutto matchtimeoutwhen not explicitly provided, preserving backward compatibility.- The
timeout_context.expired()check in the hard timeout decorator correctly distinguishes timeouts raised by the asyncio context fromTimeoutErrorraised by inner code. - The REST API contract change is additive (
stream_idle_timeouton 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.
|
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
left a comment
There was a problem hiding this comment.
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 Noneis affected, so non-streaming calls keep LiteLLM's HTTPtimeout. _timeout_errorbuilds aLiteLLMTimeout, which routes through the existing retry/error mapping;test_exhausted_stream_timeout_transitions_conversation_to_errorasserts the conversation reachesConversationExecutionStatus.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 anaresponsespath 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_calldrainsfor chunk in streamwith 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_timeoutis not passed to the LiteLLM transport (onlytimeoutis, in_prepare_transport_kwargs), so no provider-side keyword collision.
✅ APPROVED
|
I think I already fixed it... Also two weeks ago and it is already merged and released. Is this still relevant or another problem? |
all-hands-bot
left a comment
There was a problem hiding this comment.
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_decoratorwraps each attempt inasyncio.timeout(self.timeout), converting an expired context intoLiteLLMTimeout("LLM hard timeout after N seconds")._aiter_with_idle_timeoutwraps eachanext()inasyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raisesLiteLLMTimeout("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, anaresponseshung-stream test, and a conversation-levelERRORtransition 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_timeoutis resolved: the outerasyncio.timeout()delivers cancellation rather than a bareTimeoutError, so the idle handler does not mislabel it, and the author's live run (timeout=3,stream_idle_timeout=300) reportedLLM hard timeout after 3 seconds. - The
openhands-sdk/openhands/sdk/llm/llm.pyblob is unchanged (c9cc7307) from the previously reviewed head; this head only removed the.pr/artifacts and mergedmain. 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_callstill drainsfor chunk in streamwith 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_timeoutis not forwarded to the LiteLLM transport (onlytimeoutis, 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
left a comment
There was a problem hiding this comment.
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.pytests/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_decoratorwraps each retry attempt inasyncio.timeout(self.timeout), raisingLiteLLMTimeouton expiry;_aiter_with_idle_timeoutwraps eachanext()inasyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline.- Both decorators sit inside the tenacity retry decorator on
_one_attemptinacompletion/aresponses;LiteLLMTimeoutis already inLLM_RETRY_EXCEPTIONS, so timeouts retry and map toLLMTimeoutErroron exhaustion. stream_idle_timeoutdefaults totimeoutvia_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-levelERRORtransition. 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_callstill drainsfor chunk in streamwith 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_timeoutis not forwarded to the LiteLLM transport (onlytimeoutis, 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.
|
@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 I verified this in The This comment was posted by an AI agent (OpenHands) on behalf of @neubig. |
all-hands-bot
left a comment
There was a problem hiding this comment.
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_decoratorwraps each attempt inasyncio.timeout(self.timeout), raisingLiteLLMTimeoutwhen the context expires._aiter_with_idle_timeoutwraps eachanext()inasyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raisesLiteLLMTimeout.
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, anaresponseshung-stream test, and a conversation-levelERRORtransition.- 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_timeoutis resolved: the outerasyncio.timeout()delivers cancellation rather than a bareTimeoutError, 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_callstill drainsfor chunk in streamwith 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_timeoutis not forwarded to the LiteLLM transport (onlytimeoutis, in_prepare_transport_kwargs), so there is no provider keyword collision.
No material findings on this head.
✅ APPROVED
all-hands-bot
left a comment
There was a problem hiding this comment.
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_decoratorwraps each attempt inasyncio.timeout(self.timeout), raisingLiteLLMTimeoutwhen the context expires._aiter_with_idle_timeoutwraps eachanext()inasyncio.wait_for(..., timeout=stream_idle_timeout), so a received chunk resets the idle deadline and a stalled stream raisesLiteLLMTimeout.
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, anaresponseshung-stream test, and a conversation-levelERRORtransition.- All current-head Actions checks pass (
pre-commit,sdk-tests,integration-test,REST API (OpenAPI),Persisted settings). GitHub reports the PRMERGEABLE. - 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_timeoutis resolved: the outerasyncio.timeout()delivers cancellation rather than a bareTimeoutError, 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_callstill drainsfor chunk in streamwith 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_timeoutis not forwarded to the LiteLLM transport (onlytimeoutis, in_prepare_transport_kwargs), so there is no provider keyword collision.
No material findings on this head.
✅ APPROVED
all-hands-bot
left a comment
There was a problem hiding this comment.
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_callstill drainsfor chunk in streamwith 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
timeoutis now aborted. The 300s default only fires on pathological stalls, but this is the eval risk the maintainer should weigh.
🔄 CHANGES REQUESTED
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>
|
Addressed both unresolved review findings from the last review on 1. Real transport 2. Flaky idle-timeout test de-flaked (test_llm_timeout.py). Added regression tests, verified to fail on the pre-fix head: transport Verification: @all-hands-bot re-requested as reviewer. Please review This comment was posted by an AI agent (OpenHands) on behalf of @neubig. |
all-hands-bot
left a comment
There was a problem hiding this comment.
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_decoratorwraps each attempt inasyncio.timeout(self.timeout)and raisesLiteLLMTimeoutonly whentimeout_context.expired()._aiter_with_idle_timeout/_anext_with_idle_timeoutwrap each chunk await inasyncio.timeout(stream_idle_timeout), so a received chunk resets the deadline and a stalled stream raisesLiteLLMTimeout.
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:
- Idle-timeout attribution.
_anext_with_idle_timeoutnow converts an error only when its own timer expired and otherwise re-raises unchanged; theassert timeout is not Noneis gone. I reproduced the oldAssertionErroron the prior head withstream_idle_timeout=Noneand a transportTimeoutError; on this head bothstream_idle_timeout=Noneandstream_idle_timeout=30propagate the originalTimeoutErrorunchanged. - Flaky real-HTTP test. The hard timeout now has real headroom (
timeout=30vs 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 basemainand are caused by this sandbox'sHOME, unrelated to the diff. - New regression tests cover transport-timeout passthrough (
Noneand 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
Review of
|
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
af3ed3ed9971for public/api/**paths.Issue Number
Fixes #4997.
How to Test
uv run pytest tests/sdk/llm/test_llm_timeout.py -qAll 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
Notes
Independent main PR. Maintainer eval review remains appropriate because this changes model-stream timeout behavior.
REST API contract changes
Compared with base OpenAPI
76e9e25078edfor public/api/**paths.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. Head634859769cb0788f6fc20b2111a0cc876cdfe57b, merged as656a5c4794d0c31beda37b3ed5f944e120a7016f. Environment: Python 3.13, litellm 1.93.0, openai 2.33.0, httpx 0.28.1.LLM_API_KEYwas not needed.Setup. A real aiohttp server on
127.0.0.1streams OpenAI chat-completions and Responses SSE. The SDK runs unmodified throughLLM.acompletion/LLM.aresponsesandLocalConversation.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_tricklecovers that path.af3ed3e6348597chat_heartbeat_then_recoverrecoveredin 3.844schat_trickle_foreverLLMTimeoutError (hard timeout)in 3.003schat_idle1_then_recoverrecoveredin 1.014sresponses_heartbeat_then_recoverrecoveredin 3.01sresponses_trickle_foreverLLMTimeoutError (hard timeout)in 3.002sresponses_idle1_then_recoverrecoveredin 1.124sresponses_fake_stream_trickleLLMTimeoutError (hard timeout)in 3.003sconversation_chat_heartbeatrunningConversationRunError (hard timeout)in 3.109s, statuserrorconversation_responses_heartbeatrunningConversationRunError (hard timeout)in 3.007s, statuserrorcancel_llm_chat_heartbeatcancel_conversation_responses_heartbeatpausedpausedLonger base run.
conversation_responses_heartbeatwithWATCHDOG=60was still hung at 60.001s, which is 20× the configured timeout. The status wasrunningand the only events were[SystemPromptEvent, MessageEvent], matching the #4997 symptom. The same case on head ends inerrorwith aConversationErrorEventafter 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_recovertook 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-flightacompletionraisesCancelledError, not a timeout, and cancellingarun()givespausedplus anInterruptEvent. 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=Truebranch of_hung_chat_completion_serverwas never used, so no test covered a byte-flowing stream that defeats httpx's read timeout. The Responses path was only tested with a mockedlitellm_aresponses. Two new real-HTTP tests close these gaps:test_async_hard_timeout_ends_real_stream_that_never_finishestest_aresponses_idle_timeout_recovers_from_real_heartbeat_streamBoth also assert that the stalled server handler finished.
af3ed3easyncio.timeoutguard fired.6348597test_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.main5ffdd29test_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
23aac47on top of6348597, 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):
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, withstream_idle_timeout=1, the call recovered in 1.01–1.12s.timeoutis now aborted and retried.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.run_in_executor(list, …)fallback is unblocked by the hard timeout, but its worker thread cannot be stopped. This is pre-existing. The pinnedlmnr>=0.7.60uses a callback logger, not a return-value wrapper, so this path is not expected in practice.Commands
repro.py(live reproduction script)Regression-test patch (local commit
23aac47, not pushed)🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdkpython-node-runtimepython-node-runtimepython-node-runtimegolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:6348597-pythonRun
All tags pushed for this build
About Multi-Architecture Support
6348597-python) is a multi-arch manifest supporting both amd64 and arm646348597-python-amd64) are also available if needed