## Summary
Thread streams in `langgraph_sdk` now report why they ended. An `id:
null` error frame becomes the error `thread.output` raises, the sync
client no longer blocks forever when the server closes the stream, and a
stream the server rejects with a 4xx ends at once instead of being
retried.
## Problem
- A server sends `{"type": "error", "id": null, ...}` just before it
closes a thread stream whose read failed. The SDK dropped the frame, so
`thread.output` raised a generic "lifecycle stream ended before terminal
event" (async) or blocked forever (sync: the lifecycle watcher returned
without settling the run).
- A 403 or 404 on the stream request was retried like a network error,
then reported as `RuntimeError("Lifecycle transport failed: ...")` with
no status. A server that rejects a WebSocket after accepting it closes
with 4000 plus the HTTP status (4403, 4404, 4422), since a browser can't
read a refused upgrade's status. The shared stream counted each such
reconnect as a success and reconnected forever.
## Fix
- The lifecycle watcher fails the run with the frame's error on a clean
close (both clients). The shared stream logs the frame instead of
dropping it: projections still end when the stream closes, as before,
and `thread.output` carries the error.
- A 4xx other than 408 and 429, as a status or as a 4000+status close
code, ends the stream without retries. `thread.output` now raises that
`httpx.HTTPStatusError` or `websockets.exceptions.ConnectionClosedError`
instead of the generic `RuntimeError`.
- For a minted `thread_id`, the lifecycle watcher starts after
`run.start` creates the thread. Without this, the 4xx stop would turn a
stream opened under custom auth for a not-yet-created thread from
retried into failed. The sync client starts it under a lock, since
`run.start` can be called from several threads.
- Drops the first of two `SyncStreamController._reconnect_shared_stream`
definitions. It was shadowed by the second and never ran.
Not in this PR: over WebSocket the server closes with 1011 after an
error frame, which is still retried, while over SSE the close is clean
and fails the stream. Reconnecting after a clean close, as
`langchain-ai/langgraphjs#2812` does for the JS SDK, is a separate
change.
## Test plan
- [x] The 10 new behavior tests (async and sync: error frame, clean
close, 404, 4404 close, reconnect on 404, minted `thread_id`) fail on
`main` and pass here; a race test checks that two concurrent `run.start`
calls start one watcher.
- [x] `make test` in `libs/sdk-py`: 541 passed. `make lint` clean,
`check_sdk_methods.py` passes.
- [x] `RemoteGraph` v3 tests in `libs/langgraph`
(`test_remote_graph_v3.py`,
`test_stream_events_v3_kwarg_forwarding.py`): 94 passed against this
SDK.
- [x] Against a local server with custom auth: a thread the caller can't
read fails at once with 404 (SSE) or 4404 (WebSocket), and a new thread
works with a 1 s pause before `run.start`, which fails on `main`.
46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
"""Thread-stream failures, shared by the async and sync clients."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import httpx
|
|
from websockets.exceptions import ConnectionClosed, InvalidStatus
|
|
|
|
|
|
def protocol_error(response: dict[str, Any]) -> RuntimeError:
|
|
"""Build the error for a protocol `{"type": "error"}` envelope."""
|
|
code = response.get("error", "unknown")
|
|
message = response.get("message", "")
|
|
return RuntimeError(f"Protocol error [{code}]: {message}")
|
|
|
|
|
|
def stream_error_frame(event: Any) -> RuntimeError | None:
|
|
"""Return the error in an unsolicited `{"type": "error", "id": null}` frame.
|
|
|
|
The server sends one just before it closes a thread stream whose read failed.
|
|
"""
|
|
if (
|
|
isinstance(event, dict)
|
|
and event.get("type") == "error"
|
|
and event.get("id") is None
|
|
):
|
|
return protocol_error(event)
|
|
return None
|
|
|
|
|
|
def is_non_retryable_stream_error(error: BaseException | None) -> bool:
|
|
"""Whether reopening the stream would fail the same way.
|
|
|
|
True for a 4xx other than 408 and 429: the status of a refused stream request
|
|
or WebSocket upgrade, or a WebSocket close code of 4000 plus that status. A
|
|
server that rejects a WebSocket after accepting it closes with such a code,
|
|
because a browser can't read the status of a refused upgrade.
|
|
"""
|
|
if isinstance(error, (httpx.HTTPStatusError, InvalidStatus)):
|
|
status = error.response.status_code
|
|
elif isinstance(error, ConnectionClosed) and error.rcvd is not None:
|
|
status = error.rcvd.code - 4000
|
|
else:
|
|
return False
|
|
return 400 <= status < 500 and status not in (408, 429)
|