langgraph/libs/sdk-py/langgraph_sdk/_sync/http.py
Elior Nataf Lackritz 9791c686ee
fix(sdk-py): rejoin a run stream that closes before the run ends (#9554)
Fixes #9016

A run stream whose response ends cleanly before the run does, say on a
proxy timeout or a server restart, looked like a finished run:
`HttpClient.stream` and `SyncHttpClient.stream` reconnect to the
`Location` only when the connection fails, so the caller got a cut
answer and no error. Servers generally send no `end` event when a run
ends, so a clean close alone cannot tell the cases apart, and
reconnecting on every clean close would end every finished run in five
empty reconnects and an error.

**The rule.** After a clean close, when the stream's `Location` is a
run's stream (`<prefix>/threads/{thread_id}/runs/{run_id}/stream`, any
query) and no `end` or `error` event arrived across reconnects, the
client sends `GET <prefix>/threads/{thread_id}/runs/{run_id}` with the
reconnect headers, but `Accept: application/json` and no
`Last-Event-ID`.

- `pending` or `running`, or a 429, 5xx or transport error (the restart
that closed the stream can fail the check too): handled like a dropped
connection, with the same `Last-Event-ID`, attempt budget, backoff and
warnings, so repeated closes with no new events end in the usual
max-attempts error.
- Any other status, a 4xx other than 429, or a body that isn't a run:
the stream ends as it does today. The check never raises and uses the
client's normal timeout.

Thread streams, streams without a `Location`, and the threadless
`/runs/{run_id}/stream` `Location` older servers send for stateless runs
are unchanged. A stateless run whose `Location` names its temporary
thread is checked like any other run: it rejoins while the run is
pending or running, and once the run ends and the thread is deleted the
check gets a 404 and the stream ends. As after a drop, runs created
without `stream_resumable=True` reconnect without a cursor and warn.

**Cost.** One extra GET at the end of every run stream that ends without
an `end` or `error` event. It returns the whole run record, `kwargs`
(the run's input) included, so a run started with a large input
downloads it again. With a server that sends neither event, that is
every run stream, so the iterator finishes about one round trip later.

**Tests.** The new tests mock the transport, and `main` stops at the
first clean close. 38 of the 50 new cases fail on `main`; the 12
no-check cases pass on both.

Thanks to @Bruce-Yii for the report and root cause, and to
@anushamukka9, whose #9023 proposed reconnecting after a clean close;
this version asks the run first.

Paired JS change: https://github.com/langchain-ai/langgraphjs/pull/3185
2026-11-02 19:57:22 +00:00

393 lines
15 KiB
Python

"""Synchronous HTTP client for LangGraph API."""
from __future__ import annotations
import logging
import sys
import time
import warnings
from collections.abc import Callable, Iterator, Mapping
from typing import Any, cast
import httpx
import orjson
from langgraph_sdk._shared.utilities import (
_orjson_default,
_reconnect_delay,
_run_check_headers,
_run_url_from_stream_location,
_validate_reconnect_location,
)
from langgraph_sdk.errors import (
InternalServerError,
RateLimitError,
_raise_for_status_typed,
)
from langgraph_sdk.schema import QueryParamTypes, StreamPart
from langgraph_sdk.sse import SSEDecoder, iter_lines_raw
logger = logging.getLogger(__name__)
class SyncHttpClient:
"""Handle synchronous requests to the LangGraph API.
Provides error messaging and content handling enhancements above the
underlying httpx client, mirroring the interface of [HttpClient](#HttpClient)
but for sync usage.
Attributes:
client (httpx.Client): Underlying HTTPX sync client.
"""
def __init__(self, client: httpx.Client) -> None:
self.client = client
def get(
self,
path: str,
*,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> Any:
"""Send a `GET` request."""
r = self.client.get(path, params=params, headers=headers)
if on_response:
on_response(r)
_raise_for_status_typed(r)
return _decode_json(r)
def post(
self,
path: str,
*,
json: dict[str, Any] | list | None,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> Any:
"""Send a `POST` request."""
if json is not None:
request_headers, content = _encode_json(json)
else:
request_headers, content = {}, b""
if headers:
request_headers.update(headers)
r = self.client.post(
path, headers=request_headers, content=content, params=params
)
if on_response:
on_response(r)
_raise_for_status_typed(r)
return _decode_json(r)
def put(
self,
path: str,
*,
json: dict,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> Any:
"""Send a `PUT` request."""
request_headers, content = _encode_json(json)
if headers:
request_headers.update(headers)
r = self.client.put(
path, headers=request_headers, content=content, params=params
)
if on_response:
on_response(r)
_raise_for_status_typed(r)
return _decode_json(r)
def patch(
self,
path: str,
*,
json: dict,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> Any:
"""Send a `PATCH` request."""
request_headers, content = _encode_json(json)
if headers:
request_headers.update(headers)
r = self.client.patch(
path, headers=request_headers, content=content, params=params
)
if on_response:
on_response(r)
_raise_for_status_typed(r)
return _decode_json(r)
def delete(
self,
path: str,
*,
json: Any | None = None,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> None:
"""Send a `DELETE` request."""
r = self.client.request(
"DELETE", path, json=json, params=params, headers=headers
)
if on_response:
on_response(r)
_raise_for_status_typed(r)
def request_reconnect(
self,
path: str,
method: str,
*,
json: dict[str, Any] | None = None,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
reconnect_limit: int = 5,
) -> Any:
"""Send a request that reconnects to its Location header if the response is
cut off, with backoff between attempts."""
request_headers, content = _encode_json(json)
if headers:
request_headers.update(headers)
with self.client.stream(
method, path, headers=request_headers, content=content, params=params
) as r:
if on_response:
on_response(r)
try:
r.raise_for_status()
except httpx.HTTPStatusError as e:
body = r.read().decode()
if sys.version_info >= (3, 11):
e.add_note(body)
else:
logger.error(f"Error from langgraph-api: {body}", exc_info=e)
raise e
loc = r.headers.get("location")
if reconnect_limit <= 0 or not loc:
return _decode_json(r)
_validate_reconnect_location(self.client.base_url, loc)
try:
return _decode_json(r)
except httpx.HTTPError:
warnings.warn(
f"Request failed, attempting reconnect to Location: {loc}",
stacklevel=2,
)
r.close()
for attempt in range(reconnect_limit):
time.sleep(_reconnect_delay(attempt, base=1.0, cap=5.0))
# A restart or a deploy looks like a refused connection, a
# dropped body, a 429 or a 5xx; other errors won't go away.
try:
return self.request_reconnect(
loc,
"GET",
headers=headers,
# don't pass on_response so it's only called once
reconnect_limit=0,
)
except httpx.HTTPStatusError as err:
status = err.response.status_code
if attempt == reconnect_limit - 1 or (
status != 429 and status < 500
):
raise
except httpx.TransportError:
if attempt == reconnect_limit - 1:
raise
def stream(
self,
path: str,
method: str,
*,
json: dict[str, Any] | None = None,
params: QueryParamTypes | None = None,
headers: Mapping[str, str] | None = None,
on_response: Callable[[httpx.Response], None] | None = None,
) -> Iterator[StreamPart]:
"""Stream the results of a request using SSE."""
if json is not None:
request_headers, content = _encode_json(json)
else:
request_headers, content = {}, None
request_headers["Accept"] = "text/event-stream"
request_headers["Cache-Control"] = "no-store"
if headers:
request_headers.update(headers)
reconnect_headers = {
key: value
for key, value in request_headers.items()
if key.lower() not in {"content-length", "content-type"}
}
last_event_id: str | None = None
reconnect_path: str | None = None
reconnect_attempts = 0
max_reconnect_attempts = 5
run_ended = False
while True:
current_headers = dict(
request_headers if reconnect_path is None else reconnect_headers
)
if last_event_id is not None:
current_headers = {
key: value
for key, value in current_headers.items()
if key.lower() != "last-event-id"
}
if last_event_id:
current_headers["Last-Event-ID"] = last_event_id
if reconnect_path is not None and not any(
key.lower() == "last-event-id" and value
for key, value in current_headers.items()
):
warnings.warn(
"Reconnecting without a Last-Event-ID, so events sent while "
"disconnected are not replayed. Only runs created with "
"stream_resumable=True send the event IDs a reconnect resumes "
"from.",
stacklevel=2,
)
current_method = method if reconnect_path is None else "GET"
current_content = content if reconnect_path is None else None
current_params = params if reconnect_path is None else None
reconnect_cause: httpx.HTTPError | None = None
try:
with self.client.stream(
current_method,
reconnect_path or path,
headers=current_headers,
content=current_content,
params=current_params,
) as res:
if reconnect_path is None and on_response:
on_response(res)
# check status
_raise_for_status_typed(res)
# check content type
content_type = res.headers.get("content-type", "").partition(";")[0]
if "text/event-stream" not in content_type:
raise httpx.TransportError(
"Expected response header Content-Type to contain 'text/event-stream', "
f"got {content_type!r}"
)
reconnect_location = res.headers.get("location")
if reconnect_location:
_validate_reconnect_location(
self.client.base_url, reconnect_location
)
reconnect_path = reconnect_location
decoder = SSEDecoder(last_event_id=last_event_id)
try:
for line in iter_lines_raw(res):
sse = decoder.decode(cast(bytes, line).rstrip(b"\n"))
if sse is not None:
if decoder.last_event_id is not None:
last_event_id = decoder.last_event_id
if sse.event or decoder.has_data:
# Progress since the last drop earns a fresh
# set of reconnect attempts.
reconnect_attempts = 0
run_ended |= sse.event in ("end", "error")
yield sse
except httpx.HTTPError as err:
# httpx.TransportError inherits from HTTPError, so transient
# disconnects during streaming land here.
if reconnect_path is None:
raise
reconnect_cause = err
else:
if sse := decoder.decode(b""):
if decoder.last_event_id is not None:
last_event_id = decoder.last_event_id
if sse.event or decoder.has_data:
# See async stream implementation for rationale on
# skipping empty flush events.
run_ended |= sse.event in ("end", "error")
yield sse
except (httpx.TransportError, RateLimitError, InternalServerError) as err:
# A reconnect that can't open (connection refused, 429, 5xx or a
# non-SSE body) usually means the server is restarting or
# mid-deploy, so retry it like a drop. Before the server sends a
# Location there is nothing to reconnect to, so raise.
if reconnect_path is None:
raise
reconnect_cause = err
# A run's stream closes cleanly both when the run ends and when a
# proxy timeout or a server restart cuts it. Without an `end` or
# `error` event the two look the same, so ask the run.
if reconnect_cause is None and reconnect_path is not None and not run_ended:
reconnect_cause = _check_run(
self.client, reconnect_path, reconnect_headers
)
if reconnect_cause is not None:
reconnect_attempts += 1
if reconnect_attempts > max_reconnect_attempts:
raise httpx.TransportError(
"Exceeded maximum SSE reconnection attempts"
) from reconnect_cause
time.sleep(_reconnect_delay(reconnect_attempts - 1, base=1.0, cap=5.0))
continue
break
def _encode_json(json: Any) -> tuple[dict[str, str], bytes | None]:
if json is None:
return {}, None
body = orjson.dumps(
json,
_orjson_default,
orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
)
content_length = str(len(body))
content_type = "application/json"
headers = {"Content-Length": content_length, "Content-Type": content_type}
return headers, body
def _decode_json(r: httpx.Response) -> Any:
body = r.read()
return orjson.loads(body) if body else None
def _check_run(
client: httpx.Client, stream_location: str, headers: Mapping[str, str]
) -> httpx.HTTPError | None:
run_url = _run_url_from_stream_location(stream_location)
if run_url is None:
return None
try:
r = client.get(run_url, headers=_run_check_headers(headers))
if r.status_code == 429 or r.status_code >= 500:
_raise_for_status_typed(r)
status = _decode_json(r)["status"] if r.is_success else None
except (httpx.TransportError, RateLimitError, InternalServerError) as err:
# The restart that closed the stream can fail the check too, so retry
# it like a drop.
return err
except Exception:
# Anything else must not turn a normal end of stream into an error.
return None
if status in ("pending", "running"):
return httpx.TransportError(
"Stream closed while the run was still pending or running"
)
return None