Fake Anthropic/OpenAI SSE server that stalls mid-stream, tested on 9 SDKs. Python SDKs treat timeout as an idle read timeout (600 s default). Node anthropic/openai ignore timeout after headers and die at undici's 300 s. Keepalive pings (e.g. OpenRouter's) mean no SDK ever errors. Vercel AI SDK retries a pre-token stall 3x300 s. anthropic-python raises raw httpx2.ReadTimeout, not APIError. Tested idle watchdog included.
What happened
Agents hang for minutes when a provider or gateway sends 200 OK and a few tokens, then stops sending content without closing the socket. I wanted to know how long each SDK waits, with defaults and with the documented timeout. So I built a fake server (server.py, stdlib only) that speaks Anthropic /v1/messages SSE and OpenAI /v1/chat/completions SSE and accepts any key, then pointed each SDK at it via base_url. It has three stall variants, and the socket always stays open:
- partial: 200 +
message_start/content_block_delta "Hello"(or 2 OpenAI chunks), then silence - silent: 200 + SSE headers, then nothing
- ping: 200, then
: OPENROUTER PROCESSINGcomment lines every 10 s and never any content
I ran 60 runs in parallel, each capped at 720 s. The server logs every request, so retries are visible (output-server.txt).
Results (seconds from request to error)
Versions: anthropic 2.14.0, openai 3.60.0, litellm 1.111.1, openai-agents 0.26.1 (Python 3.12, httpx2), @anthropic-ai/sdk 1.14.0, openai 7.65.0, ai 7.0.186 + @ai-sdk/anthropic 4.0.112 / @ai-sdk/openai 4.0.126 (Node 26.11.1, undici 8.11.2). The raw log lines include ~1–4 s of import time; the figures below subtract it.
| SDK | partial, default | partial, timeout 30 s | silent, default | silent, 30 s | ping, default | ping, 30 s | exception | |---|---|---|---|---|---|---|---| | anthropic (Py) | 600 | 30 | 600 | 30 | never (>720) | never | httpx2.ReadTimeout (not anthropic.APITimeoutError) | | openai (Py) | 600 | 30 | 600 | 30 | never | never | openai.APITimeoutError ← httpx2.ReadTimeout | | openai-agents (Py, chat-completions model) | 600 | 30 | 600 | 30 | never | never | openai.APITimeoutError | | litellm anthropic/… | 600 | 30 | 600 | 30 | never | never | litellm.MidStreamFallbackError ← httpx.ReadTimeout | | litellm openai/… | 600 | 30 | 600 | 30 | never | never | litellm.Timeout ← openai.APITimeoutError | | @anthropic-ai/sdk (Node) | 300 | 300 | 300 | 300 | never | never | AnthropicError: terminated ← UND_ERR_BODY_TIMEOUT | | openai (Node) | 300 | 300 | 300 | 300 | never | never | TypeError: terminated ← UND_ERR_BODY_TIMEOUT | | ai streamText + @ai-sdk/anthropic or /openai | 300 | 30 | >720 (retried; 3rd attempt at 609 s) | 30 | never | 30 | APICallError ← UND_ERR_BODY_TIMEOUT; with timeout: no error part, an abort part | | ai streamText, timeout: {chunkMs: 30000} | — | 30 | — | >720 (retried ×3) | — | never | abort part |
What each timeout actually means:
- Python SDKs (anthropic, openai, litellm, agents):
timeout=30is an httpx per-read idle timeout, not a total. Any bytes reset it, including SSE comment/ping lines that the SDK then throws away. A gateway that pings every 10 s keeps a content-less stream alive forever, even withtimeout=30(pingcolumn). - Node `@anthropic-ai/sdk` and `openai`:
timeoutonly covers the wait for response headers.@anthropic-ai/sdk/client.mjs:791-803armssetTimeout(abort, ms)"around the underlying fetch only" and clears it infinallywhenfetch()resolves, which happens at headers.openai/client.mjs:1083-1115does the same. After that, the only thing that ends a stall is Node's built-in fetch (undici)bodyTimeoutof 300 s. Pings reset that too. Settingtimeout: 30000made no difference for a stalled body: 301.4 s, the same as the default. - Vercel `ai`: a numeric
timeoutis a total deadline (an abort at 30 s even while pings flow).chunkMsis an idle timer between content chunks, but per the docs it "starts with the first meaningful output", so a stream that stalls before the first token (silent,ping) is never caught by it.firstChunkMscovers that case (documented; I didn't run it).
Retries multiply the hang
Server-side request counts (output-server.txt, 68 requests for 60 runs):
- Python and Node vendor SDKs: 1 request per run. Once headers arrive, a stall is never retried, even though
max_retriesdefaults to 2. You get one 600 s (or 300 s) hang, not three. - Vercel `ai`, `silent` variant: 3 requests, at 1.6 s, 304.5 s and 609.4 s. A body timeout before any content counts as a retryable call failure (
maxRetriesdefaults to 2), so the default worst case is about 3 × 300 s ≈ 15 min. This happened withchunkMs: 30000too. In thepartialvariant (content already streamed) it was not retried.
Two exception gotchas
1. anthropic-python documents "On timeout, the SDK raises an APITimeoutError" (platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#timeouts). That holds before headers. Mid-stream, the read timeout escapes unwrapped as httpx2.ReadTimeout. It is not a subclass of anthropic.APIError (output-exception-classes.txt), so except anthropic.APIError: lets it through. openai-python wraps the same thing as openai.APITimeoutError. 2. Vercel `ai` with `timeout`: fullStream emits an abort part, not an error part, and onError is not called (0 calls; onAbort gets 1). await result.text rejects with DOMException: The operation was aborted due to timeout (output-vercel-abort-text.txt). Code that only handles error parts treats the timeout as a normal end of stream.
Fix: an idle watchdog that counts only real events
None of the vendor SDKs has an idle-timeout option. Wrap the event iterator, and treat pings as no progress, since the SDK swallows them anyway:
async def idle_guard(aiter, seconds): it = aiter.__aiter__() while True: try: item = await asyncio.wait_for(it.__anext__(), seconds) except StopAsyncIteration: return except asyncio.TimeoutError: raise StreamIdle(f"no stream event for {seconds}s") from None yield item async with client.messages.stream(...) as s: # leaving the block closes the socket async for ev in idle_guard(s, 90): ...async function* idleGuard(iterable, ms, controller) { const it = iterable[Symbol.asyncIterator](); while (true) { let timer; const idle = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`stream idle ${ms} ms`)), ms); }); try { const r = await Promise.race([it.next(), idle]); if (r.done) return; yield r.value; } catch (e) { controller.abort(); throw e; } // otherwise the socket stays open finally { clearTimeout(timer); } }}const ac = new AbortController();const s = client.messages.stream({...}, { signal: ac.signal });for await (const ev of idleGuard(s, 90_000, ac)) { ... }Tested against all 3 variants with a 15 s idle limit (longer than the 10 s ping interval). Both SDKs in both languages fail at 15.0–15.1 s in every variant, including ping. The server logged "closed by client" for all 12 connections (output-watchdog-*.txt). Retry it yourself, because the SDKs won't. For Vercel ai, use timeout: { firstChunkMs, chunkMs } and handle the abort part.
Prior work
- anthropics/anthropic-sdk-typescript#959 "feat(streaming): add idleTimeout option for detecting stalled streams" was closed unmerged (2026-08-07). #998 (a ping-aware watchdog proposal, citing #749/#867 and Claude Code hangs) was closed.
- openai/openai-python #3270, #3287, #3368 (enable TCP keepalive for NAT-dropped non-streaming calls) were all closed unmerged. Those are about a *dead* TCP connection. This post covers a *live* connection with no content, which TCP keepalive cannot detect.
Repro
pip install -r requirements.txt && npm i # versions pinnedsh run_matrix.sh # 60 runs in parallel, ~12.5 min, logs/ (raw copy: output-matrix.txt)python3 server.py 18789 & PORT=18789 python watchdog.py ping; PORT=18789 node watchdog.mjs pingmacOS, 2026-12-01, all local and $0. Limits: this tests the client side only, against localhost. Real proxies and load balancers add their own idle timeouts, and Bun/Deno/edge runtimes don't use undici's 300 s default (not tested). The responses API paths weren't tested.