streaming: `ping` events keep a stalled stream alive; an event-idle timeout would let callers tell "stalled" from "slow"
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 35/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- python
- Ambito
- api, networking
Direzione di ricerca
Start in anthropic/_streaming.py at the if sse.event == "ping": continue checks near lines 93 and 222, in the sync and async decoders. Run the repro script in the issue, which should report zero content events and no exception after 20 s. Done means an event-idle timeout that raises APITimeoutError when no content event arrives within the limit, with pings ignored, and tests covering both sync and async paths. The option's design is still open, so confirm the approach with maintainers first.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
What happens
A server that answers the request and then sends nothing but event: ping keeps a
messages.create(stream=True) call open indefinitely. With timeout=2.0 and max_retries=0, after
20 seconds the call is still iterating, has received zero content events, and has raised nothing.
One connection. Three runs on each of two machines.
The ping frames never reach caller code: the decoder drops them, so a caller sees an iterator that
simply has not yielded.
Why a caller-side overall deadline does not cover this
A legitimate long generation can run for minutes, so a total deadline has to be sized for the worst
case, and then it cuts healthy streams short. Sizing it tight enough to catch a stalled stream cuts
normal ones.
From outside the SDK, "the provider is slow" and "the server or a gateway in front of it keeps
sending ping while generation has stopped" produce the same picture: an iterator that is not
yielding. The information that would separate them — the keep-alive bytes — is consumed inside the
SDK and not exposed.
The two failure modes need different responses. A slow stream should be waited on; a dead one should
be retried or abandoned. Callers currently have only their own wall clock, which cannot tell them
apart.
What I'm asking for
An option that times the gap between content events and ignores keep-alives, for example:
stream = client.messages.create(..., stream=True, idle_timeout=30.0)
which raises APITimeoutError once 30 s pass with no content event, regardless of how many ping
frames arrived in that window. A long generation that keeps producing tokens stays alive; a stream
that has nothing but pings ends with an exception the caller can act on.
Exposing the keep-alives to the iterator would work as well, if that is easier to maintain — callers
could then count them.
Where this lives in the code
anthropic/_streaming.py:93and:222—if sse.event == "ping": continue, in the sync and async
decoders. This is the step that makes keep-alives invisible to the caller.- The read timeout sits on the transport (
httpx2), which counts bytes. Apingevery 50 ms resets it.
The docs
From https://platform.claude.com/docs/en/api/sdks/python (read 2026-11-02):
By default requests time out after 10 minutes.
The SDK will throw a
ValueErrorif a non-streaming request is expected to take longer than
approximately 10 minutes. Passingstream=Trueor overriding thetimeoutoption at the client or
request level disables this error.
Measured against a stream that sends only ping: the read timeout is enforced, the call keeps
running as long as the pings keep arriving, and the 10-minute figure plays no part.
Reproduction
Standalone, no network beyond loopback, stdlib server plus the SDK client. Save as repro.py and run
it; it exits after 20 s:
import http.server
import threading
import time
import anthropic
PINGS = 0
EVENTS = []
ERRORS = []
WALL = 20.0
class PingOnly(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self):
global PINGS
self.rfile.read(int(self.headers.get("content-length", 0)))
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
self.end_headers()
while True:
self.wfile.write(b'event: ping\ndata: {"type": "ping"}\n\n')
self.wfile.flush()
PINGS += 1
time.sleep(0.05)
def log_message(self, format, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), PingOnly)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_address[1]}"
def consume():
client = anthropic.Anthropic(base_url=base, api_key="unused", timeout=2.0, max_retries=0)
try:
stream = client.messages.create(
model="claude-opus-5-5",
max_tokens=16,
messages=[{"role": "user", "content": "hi"}],
stream=True,
)
for event in stream:
EVENTS.append(event.type)
except Exception as exc:
ERRORS.append(type(exc).__name__)
worker = threading.Thread(target=consume, daemon=True)
worker.start()
worker.join(WALL)
print(f"still running after {WALL:.0f}s: {worker.is_alive()}")
print(f"content events received: {len(EVENTS)}")
print(f"exceptions: {ERRORS}")
print(f"pings sent by the server: {PINGS}")
Output, anthropic 2.3.0 / httpx2 2.16.0:
Windows 11, Python 3.11: still running after 20s: True content events: 0 exceptions: [] pings: 393-395 (3 runs)
Linux, Python 3.13: still running after 20s: True content events: 0 exceptions: [] pings: 396-397 (3 runs)
- Lingua principale
- Python
- Stelle
- 4.1k
- Fork
- 915
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Preparare l'ambiente
Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.
- Nessun Dockerfile né file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di anthropics/anthropic-sdk-python
-
beta_tool validation errors reach the model as "Invalid arguments for function X" with no detailForse già presa @mangeshraut712 l’ha presa 32 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
anthropics/anthropic-sdk-python#2033 · 3 commenti ·
-
`AnthropicBedrock` 2.x sends `anthropic_version: 2026-10-21`, which Bedrock rejects for Claude Sonnet 4.5, Opus 4.5 and Opus 4.6Forse già presa @charan-rathore l’ha presa 36 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 70/100
anthropics/anthropic-sdk-python#2031 · 1 commento ·
-
Three symlink tests in test_agent_toolset.py are missing the needs_symlinks markerForse già presa @okxint l’ha presa 82 giorni fa. Aperta
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 92/100
anthropics/anthropic-sdk-python#1915 · 3 commenti ·
-
Messages.parse (and AsyncMessages.parse) don't take cache_control?Forse già presa @AlphaFDE l’ha presa 86 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
anthropics/anthropic-sdk-python#1907 · 2 commenti ·
-
Windows: os.fchmod in credential write-back bricks the OAuth refresh tokenForse già presa @OllieinCanada l’ha presa 98 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
anthropics/anthropic-sdk-python#1868 · 1 commento ·
Tutte le issue di anthropics/anthropic-sdk-python
Issue simili
-
bug harness
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
mruangutai/harness#2687 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
modal-labs/modal-client#4158 ·
-
good first issue
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 Mezza giornata Idoneità per principianti 72/100
The-Swarm-Corporation/swarms-rs#168 ·
I maintainer di solito rispondono entro 1 giorno
-
[BUG] SMTP listener now binds to EMAIL_PORT instead of 2525 since the gunicorn switch 5.0.3-ls373Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
linuxserver/docker-healthchecks#137 · 1 commento ·