langgraph-api 0.19.0.dev11__py3-none-any.whl → 0.20.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/api/mcp/_call_thread.py +60 -2
  3. langgraph_api/api/mcp/_constants.py +2 -0
  4. langgraph_api/api/mcp/_pauses.py +8 -0
  5. langgraph_api/api/mcp/_server.py +26 -2
  6. langgraph_api/cli.py +5 -3
  7. langgraph_api/config/__init__.py +22 -2
  8. langgraph_api/embedded_core.py +10 -8
  9. langgraph_api/feature_flags.py +3 -2
  10. langgraph_api/grpc/client.py +51 -20
  11. langgraph_api/grpc/ops/runs.py +12 -12
  12. langgraph_api/js/remote.py +54 -17
  13. langgraph_api/metrics_collector.py +8 -8
  14. langgraph_api/metrics_otlp.py +15 -11
  15. langgraph_api/models/run.py +1 -1
  16. langgraph_api/run_error_category.py +87 -0
  17. langgraph_api/runtime/encryption.py +227 -0
  18. langgraph_api/runtime/routes.py +452 -31
  19. langgraph_api/runtime/store.py +2 -0
  20. langgraph_api/schema.py +6 -5
  21. langgraph_api/self_hosted_metrics.py +22 -23
  22. langgraph_api/server.py +1 -1
  23. langgraph_api/stream.py +3 -4
  24. langgraph_api/worker.py +6 -2
  25. {langgraph_api-0.19.0.dev11.dist-info → langgraph_api-0.20.0.dev1.dist-info}/METADATA +3 -3
  26. {langgraph_api-0.19.0.dev11.dist-info → langgraph_api-0.20.0.dev1.dist-info}/RECORD +36 -34
  27. langgraph_grpc_common/checkpointer.py +1 -1
  28. langgraph_grpc_common/conversion/config.py +1 -3
  29. langgraph_grpc_common/proto/core_api_pb2.py +132 -132
  30. langgraph_grpc_common/proto/core_api_pb2.pyi +20 -18
  31. langgraph_grpc_common/store.py +16 -0
  32. langgraph_runtime/__init__.py +2 -1
  33. openapi.json +9 -9
  34. {langgraph_api-0.19.0.dev11.dist-info → langgraph_api-0.20.0.dev1.dist-info}/WHEEL +0 -0
  35. {langgraph_api-0.19.0.dev11.dist-info → langgraph_api-0.20.0.dev1.dist-info}/entry_points.txt +0 -0
  36. {langgraph_api-0.19.0.dev11.dist-info → langgraph_api-0.20.0.dev1.dist-info}/licenses/LICENSE +0 -0
langgraph_api/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.19.0.dev11"
1
+ __version__ = "0.20.0.dev1"
@@ -5,6 +5,7 @@ from dataclasses import dataclass
5
5
  from http import HTTPStatus
6
6
  from typing import TYPE_CHECKING
7
7
 
8
+ import anyio
8
9
  import httpx
9
10
  import jsonschema_rs
10
11
  import mcp_types as types
@@ -13,6 +14,8 @@ from mcp.shared.exceptions import MCPError
13
14
  from starlette.exceptions import HTTPException
14
15
 
15
16
  from langgraph_api.api.mcp._constants import (
17
+ ABANDONED_RUN_CANCEL_SECONDS,
18
+ ABANDONED_RUN_STOP_SECONDS,
16
19
  BREAKPOINT_MESSAGE,
17
20
  FINISHED_CALL_TTL_MINUTES,
18
21
  PAUSED_CALL_TTL_MINUTES,
@@ -40,6 +43,11 @@ if TYPE_CHECKING:
40
43
  logger = structlog.stdlib.get_logger(__name__)
41
44
 
42
45
 
46
+ @dataclass(slots=True)
47
+ class _Attempt:
48
+ failed: bool = False
49
+
50
+
43
51
  @dataclass(frozen=True, slots=True)
44
52
  class CallThread:
45
53
  client: LangGraphClient
@@ -127,6 +135,54 @@ class CallThread:
127
135
  return False
128
136
  return True
129
137
 
138
+ async def cancel_runs(self) -> bool:
139
+ """Cancel the thread's active runs; False if the cancels didn't all land."""
140
+ active: list[str] = []
141
+ attempts: list[_Attempt] = []
142
+ with anyio.move_on_after(ABANDONED_RUN_CANCEL_SECONDS) as cancelling:
143
+ async with self._best_effort(
144
+ "Could not list an abandoned MCP call's runs"
145
+ ) as listing:
146
+ attempts.append(listing)
147
+ runs = await self.client.runs.list(self.thread_id, headers=self.headers)
148
+ active = [
149
+ r["run_id"] for r in runs if r["status"] in ("pending", "running")
150
+ ]
151
+ for run_id in active:
152
+ async with self._best_effort(
153
+ "Could not cancel an abandoned MCP call's run"
154
+ ) as cancel:
155
+ attempts.append(cancel)
156
+ await self.client.runs.cancel(
157
+ self.thread_id, run_id, headers=self.headers
158
+ )
159
+ if cancelling.cancelled_caught:
160
+ await logger.awarning(
161
+ "Could not cancel an abandoned MCP call's runs in time",
162
+ thread_id=self.thread_id,
163
+ timeout_seconds=ABANDONED_RUN_CANCEL_SECONDS,
164
+ )
165
+ return False
166
+ if any(attempt.failed for attempt in attempts):
167
+ return False
168
+ # Every cancel is recorded by now, so giving up on a run that is slow to
169
+ # stop still stops it.
170
+ with anyio.move_on_after(ABANDONED_RUN_STOP_SECONDS) as stopping:
171
+ for run_id in active:
172
+ async with self._best_effort(
173
+ "Could not wait for an abandoned MCP call's run"
174
+ ):
175
+ await self.client.runs.join(
176
+ self.thread_id, run_id, headers=self.headers
177
+ )
178
+ if stopping.cancelled_caught:
179
+ await logger.awarning(
180
+ "An abandoned MCP call's run did not stop in time",
181
+ thread_id=self.thread_id,
182
+ timeout_seconds=ABANDONED_RUN_STOP_SECONDS,
183
+ )
184
+ return True
185
+
130
186
  async def delete(self) -> None:
131
187
  async with self._best_effort("Could not delete a finished MCP call's thread"):
132
188
  await self.client.threads.delete(self.thread_id, headers=self.headers)
@@ -144,11 +200,13 @@ class CallThread:
144
200
  return Binding.stored((await self.get())["metadata"])
145
201
 
146
202
  @asynccontextmanager
147
- async def _best_effort(self, failure: str) -> AsyncIterator[None]:
203
+ async def _best_effort(self, failure: str) -> AsyncIterator[_Attempt]:
204
+ attempt = _Attempt()
148
205
  try:
149
- yield
206
+ yield attempt
150
207
  except httpx.HTTPStatusError as error:
151
208
  if error.response.status_code != HTTPStatus.NOT_FOUND:
209
+ attempt.failed = True
152
210
  await logger.awarning(
153
211
  failure,
154
212
  thread_id=self.thread_id,
@@ -23,3 +23,5 @@ BREAKPOINT_MESSAGE = (
23
23
  )
24
24
  PAUSED_CALL_TTL_MINUTES = 24 * 60
25
25
  FINISHED_CALL_TTL_MINUTES = 10
26
+ ABANDONED_RUN_CANCEL_SECONDS = 5
27
+ ABANDONED_RUN_STOP_SECONDS = 5
@@ -189,6 +189,14 @@ class ElicitingCall:
189
189
  return await self._settle(await self.thread.run(self.params))
190
190
  except UnaskableInterrupt as error:
191
191
  return await self._unaskable(error)
192
+ except anyio.get_cancelled_exc_class():
193
+ # Deleting a thread doesn't stop its run, so a run cut off by the
194
+ # client would keep executing with nowhere to report. A thread whose
195
+ # runs couldn't be cancelled is left for its TTL to remove.
196
+ with anyio.CancelScope(shield=True):
197
+ if await self.thread.cancel_runs():
198
+ await self.release()
199
+ raise
192
200
  except BaseException:
193
201
  with anyio.CancelScope(shield=True):
194
202
  await self.release()
@@ -4,7 +4,9 @@ from typing import TYPE_CHECKING
4
4
 
5
5
  from mcp.server.caching import CacheHint
6
6
  from mcp.server.lowlevel import Server
7
+ from mcp.server.streamable_http import CONTENT_TYPE_SSE
7
8
  from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
9
+ from starlette.datastructures import Headers
8
10
 
9
11
  from langgraph_api import __version__
10
12
  from langgraph_api.api.mcp._calls import ToolCallParams
@@ -47,14 +49,36 @@ SERVER.add_request_handler("tools/call", ToolCallParams, _call_tool)
47
49
 
48
50
 
49
51
  async def serve(scope: Scope, receive: Receive, send: Send) -> None:
52
+ trimmed = _with_trimmed_headers(scope)
50
53
  manager = StreamableHTTPSessionManager(
51
54
  SERVER,
52
55
  stateless=True,
53
- json_response=True,
56
+ # An SSE response sends keepalive pings while a long tool call runs, so
57
+ # proxies with idle timeouts don't cut it off before the result arrives.
58
+ json_response=not _names_event_stream(Headers(scope=trimmed)),
54
59
  max_request_body_size=HTTP_MAX_REQUEST_BODY_BYTES,
55
60
  )
56
61
  async with manager.run():
57
- await manager.handle_request(_with_trimmed_headers(scope), receive, send)
62
+ await manager.handle_request(trimmed, receive, send)
63
+
64
+
65
+ def _names_event_stream(headers: Headers) -> bool:
66
+ for media_range in headers.get("accept", "").split(","):
67
+ media_type, *params = (part.strip().lower() for part in media_range.split(";"))
68
+ if media_type == CONTENT_TYPE_SSE and _quality(params) > 0:
69
+ return True
70
+ return False
71
+
72
+
73
+ def _quality(params: list[str]) -> float:
74
+ for param in params:
75
+ name, _, value = param.partition("=")
76
+ if name.strip() == "q":
77
+ try:
78
+ return float(value.strip())
79
+ except ValueError:
80
+ return 0.0
81
+ return 1.0
58
82
 
59
83
 
60
84
  def _with_trimmed_headers(scope: Scope) -> Scope:
langgraph_api/cli.py CHANGED
@@ -306,9 +306,11 @@ def run_server(
306
306
  return env_vars[name]
307
307
  return os.getenv(name, default)
308
308
 
309
- use_core = runtime_edition == "inmem" and _env(
310
- "FF_INMEM_CORE", "false"
311
- ).lower() in ("true", "1", "yes")
309
+ use_core = runtime_edition == "inmem" and _env("FF_INMEM_CORE", "true").lower() in (
310
+ "true",
311
+ "1",
312
+ "yes",
313
+ )
312
314
  if use_core:
313
315
  to_patch[embedded_core.ADDRESS_ENV] = ""
314
316
  core = (
@@ -4,6 +4,7 @@ from enum import StrEnum
4
4
  from os import environ, getenv
5
5
  from typing import TYPE_CHECKING, Annotated, Literal, TypeVar, cast
6
6
  from urllib.parse import urlsplit
7
+ from uuid import UUID
7
8
 
8
9
  import structlog
9
10
  from langgraph.version import __version__ as langgraph_version
@@ -323,6 +324,25 @@ LSD_GRPC_SERVER_ADDRESS = env(
323
324
  default="localhost:50051",
324
325
  )
325
326
 
327
+
328
+ def _parse_tenant_id(value: str | None) -> str | None:
329
+ if not value:
330
+ return None
331
+ tenant_id = UUID(value)
332
+ if tenant_id.int == 0:
333
+ raise ValueError("LANGGRAPH_CORE_TENANT_ID must not be the nil UUID.")
334
+ return str(tenant_id)
335
+
336
+
337
+ LANGGRAPH_CORE_TENANT_ID = env(
338
+ "LANGGRAPH_CORE_TENANT_ID", cast=_parse_tenant_id, default=None
339
+ )
340
+ LANGGRAPH_CORE_TENANT_KEY = env("LANGGRAPH_CORE_TENANT_KEY", cast=str, default=None)
341
+ if bool(LANGGRAPH_CORE_TENANT_ID) != bool(LANGGRAPH_CORE_TENANT_KEY):
342
+ raise ValueError(
343
+ "LANGGRAPH_CORE_TENANT_ID and LANGGRAPH_CORE_TENANT_KEY must be set together."
344
+ )
345
+
326
346
  # Python gRPC server settings (for encryption/checkpointer services called by Go)
327
347
  # By default, binds to loopback interface only for security.
328
348
  # Set PYTHON_GRPC_BIND_HOST=0.0.0.0 to allow external connections (e.g., for CI testing).
@@ -567,7 +587,6 @@ STREAM_PUBLISH_RETRY_JITTER = env(
567
587
 
568
588
  FF_ASYNC_PUBLISH_QUEUE = env("FF_ASYNC_PUBLISH_QUEUE", cast=bool, default=False)
569
589
  FF_CRONS_ENABLED = env("FF_CRONS_ENABLED", cast=bool, default=True)
570
- FF_LOG_DROPPED_EVENTS = env("FF_LOG_DROPPED_EVENTS", cast=bool, default=False)
571
590
  FF_LOG_QUERY_AND_PARAMS = env("FF_LOG_QUERY_AND_PARAMS", cast=bool, default=False)
572
591
  # Opt-in handling of drained runs: the server's control signalling to the
573
592
  # graph and its handling of drained runs, together. On, a Postgres-backed
@@ -896,7 +915,6 @@ __all__ = [
896
915
  "DISPATCH_MODE",
897
916
  "EXPOSE_INTERNAL_METRICS_PROMETHEUS",
898
917
  "FF_CRONS_ENABLED",
899
- "FF_LOG_DROPPED_EVENTS",
900
918
  "FF_LOG_QUERY_AND_PARAMS",
901
919
  "FF_PYSPY_PROFILING_ENABLED",
902
920
  "FF_PYSPY_PROFILING_MAX_DURATION_SECS",
@@ -916,6 +934,8 @@ __all__ = [
916
934
  "LANGGRAPH_AUTH",
917
935
  "LANGGRAPH_AUTH_TYPE",
918
936
  "LANGGRAPH_CLOUD_LICENSE_KEY",
937
+ "LANGGRAPH_CORE_TENANT_ID",
938
+ "LANGGRAPH_CORE_TENANT_KEY",
919
939
  "LANGGRAPH_LOGS_ENABLED",
920
940
  "LANGGRAPH_LOGS_ENDPOINT",
921
941
  "LANGGRAPH_METRICS_ENABLED",
@@ -25,7 +25,7 @@ SQLITE_PATH = os.path.join(".langgraph_api", "core.sqlite")
25
25
  # Local data formats this version no longer reads. Add a pattern whenever a
26
26
  # change drops local dev data instead of migrating it.
27
27
  DROPPED_LOCAL_DATA = (
28
- "*.pckl", # Python in-memory runtime
28
+ ".langgraph_*.pckl", # Python in-memory runtime
29
29
  )
30
30
 
31
31
 
@@ -73,13 +73,15 @@ def start(sqlite_path: str | None = None) -> Iterator[str]:
73
73
  try:
74
74
  yield _wait_for_address(process, address_file)
75
75
  finally:
76
- if process.poll() is None:
77
- process.terminate()
78
- try:
79
- process.wait(timeout=5)
80
- except subprocess.TimeoutExpired:
81
- process.kill()
82
- process.wait()
76
+ # Closing stdin shuts core down gracefully on every OS; terminate()
77
+ # would be a hard kill on Windows.
78
+ if process.stdin:
79
+ process.stdin.close()
80
+ try:
81
+ process.wait(timeout=5)
82
+ except subprocess.TimeoutExpired:
83
+ process.kill()
84
+ process.wait()
83
85
 
84
86
 
85
87
  def _core_log_level(level: str) -> str:
@@ -20,8 +20,9 @@ USE_DURABILITY = LANGGRAPH_PY_MINOR >= (0, 6)
20
20
  _RUNTIME_EDITION = os.getenv("LANGGRAPH_RUNTIME_EDITION", "inmem")
21
21
  IS_POSTGRES_BACKEND = _RUNTIME_EDITION == "postgres"
22
22
  IS_INMEM_BACKEND = _RUNTIME_EDITION == "inmem"
23
- # Opt-in: run the in-memory runtime on Go core with SQLite.
24
- INMEM_USES_CORE = IS_INMEM_BACKEND and os.getenv("FF_INMEM_CORE", "false").lower() in (
23
+ # The in-memory runtime runs on Go core with SQLite;
24
+ # FF_INMEM_CORE=false falls back to the Python runtime.
25
+ INMEM_USES_CORE = IS_INMEM_BACKEND and os.getenv("FF_INMEM_CORE", "true").lower() in (
25
26
  "true",
26
27
  "1",
27
28
  "yes",
@@ -24,6 +24,8 @@ from langgraph_api.logging import worker_config
24
24
  logger = structlog.stdlib.get_logger(__name__)
25
25
 
26
26
  _REQUEST_ID_METADATA_KEY = "x-request-id"
27
+ _TENANT_ID_METADATA_KEY = "x-langgraph-tenant-id"
28
+ _TENANT_KEY_METADATA_KEY = "x-langgraph-tenant-key"
27
29
 
28
30
 
29
31
  class _RequestIdCallDetails:
@@ -54,34 +56,63 @@ class _RequestIdCallDetails:
54
56
  self.compression = getattr(original, "compression", None)
55
57
 
56
58
 
57
- class _RequestIdInterceptor(
58
- aio.UnaryUnaryClientInterceptor,
59
- aio.UnaryStreamClientInterceptor,
60
- aio.StreamStreamClientInterceptor,
61
- ):
62
- """Injects x-request-id from the current logging context into outgoing gRPC metadata."""
63
-
64
- def _inject(
65
- self, client_call_details: aio.ClientCallDetails
66
- ) -> aio.ClientCallDetails:
67
- ctx = worker_config.get()
68
- request_id: str | None = ctx.get("request_id") if ctx else None
69
- if not request_id:
70
- return client_call_details
71
- metadata = list(client_call_details.metadata or [])
59
+ def _with_call_metadata(
60
+ client_call_details: aio.ClientCallDetails,
61
+ ) -> aio.ClientCallDetails:
62
+ """Attach the request ID and configured tenant credentials to outgoing calls."""
63
+ ctx = worker_config.get()
64
+ request_id: str | None = ctx.get("request_id") if ctx else None
65
+ tenant_id = config.LANGGRAPH_CORE_TENANT_ID
66
+ if not request_id and not tenant_id:
67
+ return client_call_details
68
+ metadata = list(client_call_details.metadata or [])
69
+ if request_id:
72
70
  metadata.append((_REQUEST_ID_METADATA_KEY, request_id))
73
- return _RequestIdCallDetails(client_call_details, metadata)
71
+ if tenant_id:
72
+ metadata.append((_TENANT_ID_METADATA_KEY, tenant_id))
73
+ tenant_key = config.LANGGRAPH_CORE_TENANT_KEY
74
+ if tenant_key is None:
75
+ raise ValueError("LANGGRAPH_CORE_TENANT_KEY is required with a tenant ID")
76
+ metadata.append((_TENANT_KEY_METADATA_KEY, tenant_key))
77
+ return _RequestIdCallDetails(client_call_details, metadata)
78
+
74
79
 
80
+ # grpc.aio registers only the first matching interceptor interface per instance.
81
+ class _UnaryUnaryMetadata(aio.UnaryUnaryClientInterceptor):
75
82
  async def intercept_unary_unary(self, continuation, client_call_details, request):
76
- return await continuation(self._inject(client_call_details), request)
83
+ return await continuation(_with_call_metadata(client_call_details), request)
84
+
77
85
 
86
+ class _UnaryStreamMetadata(aio.UnaryStreamClientInterceptor):
78
87
  async def intercept_unary_stream(self, continuation, client_call_details, request):
79
- return await continuation(self._inject(client_call_details), request)
88
+ return await continuation(_with_call_metadata(client_call_details), request)
89
+
90
+
91
+ class _StreamUnaryMetadata(aio.StreamUnaryClientInterceptor):
92
+ async def intercept_stream_unary(
93
+ self, continuation, client_call_details, request_iterator
94
+ ):
95
+ return await continuation(
96
+ _with_call_metadata(client_call_details), request_iterator
97
+ )
98
+
80
99
 
100
+ class _StreamStreamMetadata(aio.StreamStreamClientInterceptor):
81
101
  async def intercept_stream_stream(
82
102
  self, continuation, client_call_details, request_iterator
83
103
  ):
84
- return await continuation(self._inject(client_call_details), request_iterator)
104
+ return await continuation(
105
+ _with_call_metadata(client_call_details), request_iterator
106
+ )
107
+
108
+
109
+ def _metadata_interceptors() -> list[aio.ClientInterceptor]:
110
+ return [
111
+ _UnaryUnaryMetadata(),
112
+ _UnaryStreamMetadata(),
113
+ _StreamUnaryMetadata(),
114
+ _StreamStreamMetadata(),
115
+ ]
85
116
 
86
117
 
87
118
  # Shared gRPC client pools (main thread + thread-local for isolated loops).
@@ -151,7 +182,7 @@ class GrpcClient:
151
182
  self._channel = aio.insecure_channel(
152
183
  self.server_address,
153
184
  options=options,
154
- interceptors=[_RequestIdInterceptor()],
185
+ interceptors=_metadata_interceptors(),
155
186
  )
156
187
 
157
188
  self._assistants_stub = AssistantsStub(self._channel)
@@ -1015,15 +1015,15 @@ class Runs(Authenticated):
1015
1015
  stats["by_priority"] = [
1016
1016
  {
1017
1017
  "priority": level.priority,
1018
- "n_pending": level.n_pending,
1019
- "pending_runs_wait_time_max_secs": (
1020
- level.pending_runs_wait_time_max_secs
1021
- if level.HasField("pending_runs_wait_time_max_secs")
1018
+ "n_startable": level.n_startable,
1019
+ "startable_runs_wait_time_max_secs": (
1020
+ level.startable_runs_wait_time_max_secs
1021
+ if level.HasField("startable_runs_wait_time_max_secs")
1022
1022
  else None
1023
1023
  ),
1024
- "pending_runs_wait_time_med_secs": (
1025
- level.pending_runs_wait_time_med_secs
1026
- if level.HasField("pending_runs_wait_time_med_secs")
1024
+ "startable_runs_wait_time_med_secs": (
1025
+ level.startable_runs_wait_time_med_secs
1026
+ if level.HasField("startable_runs_wait_time_med_secs")
1027
1027
  else None
1028
1028
  ),
1029
1029
  "n_running": level.n_running,
@@ -1285,11 +1285,11 @@ class Runs(Authenticated):
1285
1285
  event: Event type (e.g. 'values', 'updates', 'messages', etc.)
1286
1286
  message: Event payload (serialized JSON or raw bytes)
1287
1287
  thread_id: The thread ID
1288
- resumable: If true, message will be cached with TTL for resumable streaming
1289
- publisher_id: With `seq`, lets the Lua publish scripts drop a
1290
- retried publish instead of adding it twice; publishes outside
1291
- those scripts, such as a plain Pub/Sub publish, ignore both.
1292
- Pass both or neither.
1288
+ resumable: Whether the in-memory runtime keeps the message for a
1289
+ resumed stream. Redis keeps every message for its TTL.
1290
+ publisher_id: With `seq`, lets the Redis publish script drop a
1291
+ retried publish instead of adding it twice; the in-memory
1292
+ runtime ignores both. Pass both or neither.
1293
1293
  seq: The event's number within the publisher; retries resend it
1294
1294
  """
1295
1295
  run_id_pb = (
@@ -12,7 +12,7 @@ import sys
12
12
  import tempfile
13
13
  import time
14
14
  from collections import deque
15
- from collections.abc import AsyncIterator, Callable, Iterator, Mapping
15
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
16
16
  from inspect import signature
17
17
  from typing import Any, Literal, Self, cast
18
18
 
@@ -860,6 +860,59 @@ async def _put_writes(checkpointer: Any, payload: dict) -> None:
860
860
  )
861
861
 
862
862
 
863
+ async def _wait_for_disconnect(request: Request) -> None:
864
+ while (await request.receive())["type"] != "http.disconnect":
865
+ pass
866
+
867
+
868
+ async def _await_until_disconnect(
869
+ request: Request, awaitable: Awaitable[Any]
870
+ ) -> tuple[bool, Any]:
871
+ """Await `awaitable`, cancelling it if the client goes away first.
872
+
873
+ Starlette does not cancel a plain request handler when the client
874
+ disconnects, so a JS fetch that times out would otherwise leave its
875
+ checkpointer/store call (and the gRPC call under it) running.
876
+ """
877
+ task = asyncio.ensure_future(awaitable)
878
+ watcher = asyncio.create_task(_wait_for_disconnect(request))
879
+ try:
880
+ done, _ = await asyncio.wait(
881
+ {task, watcher}, return_when=asyncio.FIRST_COMPLETED
882
+ )
883
+ finally:
884
+ watcher.cancel()
885
+ if not task.done():
886
+ task.cancel()
887
+ with contextlib.suppress(asyncio.CancelledError):
888
+ await task
889
+ if task not in done:
890
+ return False, None
891
+ return True, task.result()
892
+
893
+
894
+ def wrap_handler(cb: Callable[[dict], Awaitable[Any]]):
895
+ async def wrapped(request: Request):
896
+ try:
897
+ payload = orjson.loads(await request.body())
898
+ completed, result = await _await_until_disconnect(request, cb(payload))
899
+ if not completed:
900
+ await logger.awarning(
901
+ "Client disconnected, cancelled remote handler",
902
+ path=request.url.path,
903
+ )
904
+ return ApiResponse({"error": "client disconnected"}, status_code=499)
905
+ return ApiResponse(result)
906
+ except ValueError as exc:
907
+ await logger.aexception("ValueError calling remote handler", exc_info=exc)
908
+ return ApiResponse({"error": str(exc)}, status_code=400)
909
+ except Exception as exc:
910
+ await logger.aexception("Error calling remote handler", exc_info=exc)
911
+ return ApiResponse({"error": str(exc)}, status_code=500)
912
+
913
+ return wrapped
914
+
915
+
863
916
  # Setup a HTTP server on top of CHECKPOINTER_SOCKET unix socket
864
917
  # used by `client.mts` to communicate with the Python checkpointer
865
918
  async def run_remote_checkpointer():
@@ -1045,22 +1098,6 @@ async def run_remote_checkpointer():
1045
1098
 
1046
1099
  return [list(ns) for ns in result]
1047
1100
 
1048
- def wrap_handler(cb):
1049
- async def wrapped(request: Request):
1050
- try:
1051
- payload = orjson.loads(await request.body())
1052
- return ApiResponse(await cb(payload))
1053
- except ValueError as exc:
1054
- await logger.aexception(
1055
- "ValueError calling remote handler", exc_info=exc
1056
- )
1057
- return ApiResponse({"error": str(exc)}, status_code=400)
1058
- except Exception as exc:
1059
- await logger.aexception("Error calling remote handler", exc_info=exc)
1060
- return ApiResponse({"error": str(exc)}, status_code=500)
1061
-
1062
- return wrapped
1063
-
1064
1101
  remote = Starlette(
1065
1102
  routes=[
1066
1103
  Route(
@@ -40,18 +40,18 @@ from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
40
40
  from langgraph_api.metrics_otlp import (
41
41
  COUNTER_PG_POOL_REQUESTS_ERRORS,
42
42
  COUNTER_PG_POOL_REQUESTS_QUEUED,
43
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MAX,
44
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MED,
45
- GAUGE_NUM_DUE_PENDING_RUNS,
46
43
  GAUGE_NUM_PENDING_RUNS,
47
44
  GAUGE_NUM_RUNNING_RUNS,
48
45
  GAUGE_NUM_RUNNING_RUNS_BY_PRIORITY,
46
+ GAUGE_NUM_STARTABLE_RUNS,
49
47
  GAUGE_PG_POOL_AVAILABLE,
50
48
  GAUGE_PG_POOL_MAX,
51
49
  GAUGE_PG_POOL_SIZE,
52
50
  GAUGE_REDIS_POOL_AVAILABLE,
53
51
  GAUGE_REDIS_POOL_MAX,
54
52
  GAUGE_REDIS_POOL_SIZE,
53
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MAX,
54
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MED,
55
55
  GAUGE_WORKERS_ACTIVE,
56
56
  GAUGE_WORKERS_AVAILABLE,
57
57
  GAUGE_WORKERS_MAX,
@@ -113,16 +113,16 @@ async def _collect_queue_and_workers(reporter) -> None:
113
113
  for level in stats.get("by_priority", ()):
114
114
  attributes = {"priority": str(level["priority"])}
115
115
  reporter.record_gauge(
116
- GAUGE_NUM_DUE_PENDING_RUNS, level["n_pending"], attributes
116
+ GAUGE_NUM_STARTABLE_RUNS, level["n_startable"], attributes
117
117
  )
118
118
  reporter.record_gauge(
119
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MAX,
120
- level["pending_runs_wait_time_max_secs"] or 0,
119
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MAX,
120
+ level["startable_runs_wait_time_max_secs"] or 0,
121
121
  attributes,
122
122
  )
123
123
  reporter.record_gauge(
124
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MED,
125
- level["pending_runs_wait_time_med_secs"] or 0,
124
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MED,
125
+ level["startable_runs_wait_time_med_secs"] or 0,
126
126
  attributes,
127
127
  )
128
128
  reporter.record_gauge(
@@ -284,29 +284,32 @@ GAUGE_NUM_RUNNING_RUNS = def_gauge(
284
284
  lsd_web_metric=True,
285
285
  description="The number of runs currently running.",
286
286
  )
287
- # One series per priority level, labelled "priority" with the level as text, over pending
288
- # runs that are already due (num_pending_runs also counts delayed runs). Recorded only on a
287
+ # One series per priority level, labelled "priority" with the level as text, over the runs
288
+ # that can start: each thread's oldest pending run that is due, on threads with nothing
289
+ # running (num_pending_runs also counts delayed and blocked runs). Recorded only on a
289
290
  # deployment with a priority callback.
290
- GAUGE_NUM_DUE_PENDING_RUNS = def_gauge(
291
- "num_due_pending_runs",
291
+ GAUGE_NUM_STARTABLE_RUNS = def_gauge(
292
+ "num_startable_runs",
292
293
  METRIC_TIER_INFO,
293
294
  lsd_web_metric=True,
294
- description="The number of pending runs that are due, by priority level.",
295
+ description="The number of runs that can start now, by priority level.",
295
296
  )
296
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MAX = def_gauge(
297
- "due_pending_runs_wait_time_max",
297
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MAX = def_gauge(
298
+ "startable_runs_wait_time_max",
298
299
  METRIC_TIER_INFO,
299
300
  lsd_web_metric=True,
300
301
  description=(
301
- "The longest wait of a pending run that is due, by priority level, in seconds."
302
+ "The longest wait of a run that can start, since it was due, by priority level,"
303
+ " in seconds."
302
304
  ),
303
305
  )
304
- GAUGE_DUE_PENDING_RUNS_WAIT_TIME_MED = def_gauge(
305
- "due_pending_runs_wait_time_med",
306
+ GAUGE_STARTABLE_RUNS_WAIT_TIME_MED = def_gauge(
307
+ "startable_runs_wait_time_med",
306
308
  METRIC_TIER_INFO,
307
309
  lsd_web_metric=True,
308
310
  description=(
309
- "The median wait of pending runs that are due, by priority level, in seconds."
311
+ "The median wait of runs that can start, since they were due, by priority level,"
312
+ " in seconds."
310
313
  ),
311
314
  )
312
315
  # A separate name from num_running_runs, whose readers take max() across series and
@@ -555,6 +558,7 @@ class OTelMetricsReporter:
555
558
  if os.getenv("DEEPAGENTS_VERSION", "") != ""
556
559
  else "false",
557
560
  "deployment_type": os.getenv("LSD_DEPLOYMENT_TYPE", ""),
561
+ "env": os.getenv("LSD_ENV", ""),
558
562
  }
559
563
  )
560
564
 
@@ -115,7 +115,7 @@ class RunCreateDict(TypedDict):
115
115
  stream_subgraphs: bool | None
116
116
  """Stream output from subgraphs. By default, streams only the top graph."""
117
117
  stream_resumable: bool | None
118
- """Whether to persist the stream chunks in order to resume the stream later."""
118
+ """Whether to keep the run's stream events so a client can rejoin the run. Deployments keep every run's events for `RESUMABLE_STREAM_TTL_SECONDS` (2 minutes by default) regardless of this field. The in-memory runtime (`langgraph dev`) keeps them only when it is true."""
119
119
  feedback_keys: list[str] | None
120
120
  """Pass one or more feedback_keys if you want to request short-lived signed URLs
121
121
  for submitting feedback to LangSmith with this key for this run."""