langgraph-api 0.19.0.dev5__py3-none-any.whl → 0.19.0.dev7__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 (48) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/api/meta.py +11 -2
  3. langgraph_api/api/runs.py +25 -6
  4. langgraph_api/api/threads.py +36 -4
  5. langgraph_api/config/__init__.py +25 -0
  6. langgraph_api/errors.py +27 -0
  7. langgraph_api/event_streaming/service.py +9 -7
  8. langgraph_api/event_streaming/session.py +18 -1
  9. langgraph_api/executor/__main__.py +18 -4
  10. langgraph_api/go_prometheus_metrics.py +52 -0
  11. langgraph_api/grpc/ops/runs.py +40 -25
  12. langgraph_api/grpc/ops/threads.py +48 -7
  13. langgraph_api/js/client.mts +17 -5
  14. langgraph_api/js/errors.py +9 -2
  15. langgraph_api/js/package.json +2 -2
  16. langgraph_api/js/remote.py +9 -1
  17. langgraph_api/js/src/utils/serde.mts +21 -0
  18. langgraph_api/js/yarn.lock +113 -113
  19. langgraph_api/metadata.py +4 -11
  20. langgraph_api/metrics_otlp.py +13 -1
  21. langgraph_api/models/run.py +1 -0
  22. langgraph_api/queue_entrypoint.py +5 -1
  23. langgraph_api/runtime/__init__.py +1 -0
  24. langgraph_api/runtime/lifespan.py +335 -0
  25. langgraph_api/runtime/metrics.py +26 -0
  26. langgraph_api/runtime/queue.py +457 -0
  27. langgraph_api/runtime/retry.py +87 -0
  28. langgraph_api/self_hosted_metrics.py +4 -1
  29. langgraph_api/serde.py +3 -1
  30. langgraph_api/stream.py +64 -5
  31. langgraph_api/utils/__init__.py +7 -3
  32. langgraph_api/validation.py +1 -0
  33. langgraph_api/web_identity.py +287 -0
  34. langgraph_api/worker.py +28 -9
  35. langgraph_api/worker_runtime.py +21 -0
  36. {langgraph_api-0.19.0.dev5.dist-info → langgraph_api-0.19.0.dev7.dist-info}/METADATA +1 -1
  37. {langgraph_api-0.19.0.dev5.dist-info → langgraph_api-0.19.0.dev7.dist-info}/RECORD +48 -41
  38. langgraph_grpc_common/proto/core_api_pb2.py +160 -158
  39. langgraph_grpc_common/proto/core_api_pb2.pyi +93 -9
  40. langgraph_grpc_common/proto/core_api_pb2_grpc.py +44 -0
  41. langgraph_grpc_common/proto/core_api_pb2_grpc.pyi +12 -0
  42. langgraph_grpc_common/proto/orchestrator_pb2.py +4 -4
  43. langgraph_grpc_common/proto/orchestrator_pb2.pyi +5 -1
  44. langgraph_runtime/__init__.py +3 -0
  45. openapi.json +43 -2
  46. {langgraph_api-0.19.0.dev5.dist-info → langgraph_api-0.19.0.dev7.dist-info}/WHEEL +0 -0
  47. {langgraph_api-0.19.0.dev5.dist-info → langgraph_api-0.19.0.dev7.dist-info}/entry_points.txt +0 -0
  48. {langgraph_api-0.19.0.dev5.dist-info → langgraph_api-0.19.0.dev7.dist-info}/licenses/LICENSE +0 -0
langgraph_api/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.19.0.dev5"
1
+ __version__ = "0.19.0.dev7"
langgraph_api/api/meta.py CHANGED
@@ -1,3 +1,4 @@
1
+ import langgraph._internal._constants as langgraph_constants
1
2
  import langgraph.version
2
3
  import structlog
3
4
  from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
@@ -6,6 +7,7 @@ from starlette.responses import JSONResponse, PlainTextResponse
6
7
  from langgraph_api import __version__, config, metadata
7
8
  from langgraph_api.api.mcp import MCP_SERVED
8
9
  from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
10
+ from langgraph_api.go_prometheus_metrics import merge_go_prometheus_text
9
11
  from langgraph_api.http_metrics import HTTP_METRICS_COLLECTOR
10
12
  from langgraph_api.route import ApiRequest
11
13
  from langgraph_api.schema import PoolStats, PostgresPoolStats, RedisPoolStats
@@ -13,6 +15,9 @@ from langgraph_api.tracing_session import ADDRESS_SUPPORT
13
15
  from langgraph_runtime.database import connect, pool_stats
14
16
  from langgraph_runtime.metrics import get_metrics
15
17
 
18
+ # A run's `strict_resume` works only on a langgraph that has the check.
19
+ STRICT_RESUME = hasattr(langgraph_constants, "CONFIG_KEY_STRICT_RESUME")
20
+
16
21
  if IS_POSTGRES_OR_GRPC_BACKEND:
17
22
  from langgraph_api.grpc.ops import Runs
18
23
  else:
@@ -91,6 +96,7 @@ async def meta_info(request: ApiRequest):
91
96
  "mcp": MCP_SERVED,
92
97
  "stream_namespaces": IS_POSTGRES_OR_GRPC_BACKEND,
93
98
  "stream_lifecycle": True,
99
+ "strict_resume": STRICT_RESUME,
94
100
  },
95
101
  "host": {
96
102
  "kind": metadata.HOST,
@@ -111,8 +117,11 @@ async def meta_metrics(request: ApiRequest):
111
117
 
112
118
  if metrics_format == "prometheus":
113
119
  # Served straight from the OTLP Prometheus client's registry (see
114
- # metrics_otlp._LSDPrometheusReader).
115
- return PlainTextResponse(generate_latest(), media_type=CONTENT_TYPE_LATEST)
120
+ # metrics_otlp._LSDPrometheusReader). In multi-process, Go owns queue
121
+ # depth / workers / run lifecycle — merge via Runs.PrometheusMetrics
122
+ # gRPC so scrapers (always hitting Python :8000/metrics) see them.
123
+ body = await merge_go_prometheus_text(generate_latest())
124
+ return PlainTextResponse(body, media_type=CONTENT_TYPE_LATEST)
116
125
 
117
126
  # JSON: hand-built snapshot of workers, queue depth, HTTP, and pool stats.
118
127
  worker_metrics = get_metrics()["workers"]
langgraph_api/api/runs.py CHANGED
@@ -28,6 +28,7 @@ from langgraph_api.utils import (
28
28
  get_pagination_headers,
29
29
  uuid7,
30
30
  validate_select_columns,
31
+ validate_stream_id,
31
32
  validate_timezone,
32
33
  validate_uuid,
33
34
  )
@@ -325,9 +326,9 @@ async def _join_with_outcome(
325
326
  # whose row still says running.
326
327
  continue
327
328
  ended = event[0] == b"end"
328
- # `metadata` only starts an attempt, so a join that saw just that still
329
- # needs the run's ending.
330
- joined_any = joined_any or event[0] != b"metadata"
329
+ # `metadata` only starts an attempt and a `gap` only says events are missing,
330
+ # so a join that saw just those still needs the run's ending.
331
+ joined_any = joined_any or event[0] not in (b"metadata", b"gap")
331
332
  yield event
332
333
  if ended or (joined_any and not end):
333
334
  return
@@ -785,13 +786,31 @@ async def join_run_stream(request: ApiRequest):
785
786
  for mode in parse_stream_mode_param(value)
786
787
  ]
787
788
 
788
- namespace_kwargs = stream_namespace_kwargs(request.query_params)
789
- last_event_id = request.headers.get("last-event-id") or None
789
+ join_kwargs: dict[str, Any] = dict(stream_namespace_kwargs(request.query_params))
790
+ last_event_id = validate_stream_id(
791
+ request.headers.get("last-event-id") or None,
792
+ "Invalid last-event-id: must be a valid Redis stream ID",
793
+ )
794
+ checkpoint_id = request.query_params.get("checkpoint_id")
795
+ # A real Last-Event-ID, sent on a reconnect, wins over checkpoint_id, which is then
796
+ # neither validated nor used.
797
+ if last_event_id not in (None, "-"):
798
+ checkpoint_id = None
799
+ elif checkpoint_id is not None:
800
+ checkpoint_id = validate_uuid(
801
+ checkpoint_id, "Invalid checkpoint_id: must be a UUID"
802
+ )
790
803
  # A resume replays what the client missed from the stream's cache, which
791
804
  # outlives a run deleted as it ends (a stateless run), so it skips this
792
805
  # check; the join still applies the auth filters before it replays.
793
806
  if last_event_id is None:
794
807
  await Runs.Stream.check_run_stream_auth(run_id, thread_id)
808
+ if checkpoint_id:
809
+ # Where the checkpoint goes unused, on the in-memory runtime or a core that
810
+ # predates it, "-" replays the whole run instead of streaming only new events.
811
+ last_event_id = "-"
812
+ if IS_POSTGRES_OR_GRPC_BACKEND:
813
+ join_kwargs["checkpoint_id"] = str(checkpoint_id)
795
814
  sub = await Runs.Stream.subscribe(run_id, thread_id)
796
815
 
797
816
  async def body():
@@ -804,7 +823,7 @@ async def join_run_stream(request: ApiRequest):
804
823
  stream_channel=cast("_StreamHandler", sub),
805
824
  stream_mode=stream_mode,
806
825
  last_event_id=last_event_id,
807
- **namespace_kwargs,
826
+ **join_kwargs,
808
827
  ):
809
828
  yield event, message, stream_id
810
829
  finally:
@@ -1,5 +1,6 @@
1
1
  import re
2
2
  from contextlib import aclosing
3
+ from datetime import UTC, datetime
3
4
  from typing import TYPE_CHECKING, Any, get_args
4
5
 
5
6
  from starlette.exceptions import HTTPException
@@ -106,6 +107,11 @@ async def create_thread(
106
107
  return ApiResponse(thread)
107
108
 
108
109
 
110
+ def _raw_values_kwargs(raw_values: bool = True) -> dict[str, bool]:
111
+ """Have the gRPC ops relay thread values undecoded; in-memory ops always decode."""
112
+ return {"raw_values": raw_values} if IS_POSTGRES_OR_GRPC_BACKEND else {}
113
+
114
+
109
115
  def _exclude_metadata_kwargs(payload: dict) -> dict:
110
116
  """Normalize `exclude_metadata` (object or list of objects) into ops kwargs."""
111
117
  exclude_metadata = payload.get("exclude_metadata")
@@ -116,6 +122,27 @@ def _exclude_metadata_kwargs(payload: dict) -> dict:
116
122
  return {"exclude_metadata": exclude_metadata}
117
123
 
118
124
 
125
+ _THREAD_TIME_RANGE_FIELDS = ("created_after", "created_before")
126
+
127
+
128
+ def _time_range_kwargs(payload: dict) -> dict:
129
+ """Parse ISO 8601 time-range bounds into ops kwargs. Naive values are UTC."""
130
+ kwargs = {}
131
+ for field in _THREAD_TIME_RANGE_FIELDS:
132
+ raw = payload.get(field)
133
+ if raw is None:
134
+ continue
135
+ try:
136
+ parsed = datetime.fromisoformat(raw)
137
+ except (TypeError, ValueError):
138
+ raise HTTPException(
139
+ status_code=422,
140
+ detail=f"Invalid {field}: must be an ISO 8601 datetime",
141
+ ) from None
142
+ kwargs[field] = parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
143
+ return kwargs
144
+
145
+
119
146
  @retry_db
120
147
  async def search_threads(
121
148
  request: ApiRequest,
@@ -153,7 +180,7 @@ async def search_threads(
153
180
  # it would extract from ciphertext (wrong) and we'll redo it anyway.
154
181
  storage_extract = None if needs_python_extract else extract
155
182
 
156
- exclude_kwargs = _exclude_metadata_kwargs(payload)
183
+ filter_kwargs = {**_exclude_metadata_kwargs(payload), **_time_range_kwargs(payload)}
157
184
  async with connect() as conn:
158
185
  threads_iter, next_offset = await Threads.search(
159
186
  conn,
@@ -167,7 +194,9 @@ async def search_threads(
167
194
  sort_order=payload.get("sort_order"),
168
195
  select=storage_select,
169
196
  extract=storage_extract,
170
- **exclude_kwargs,
197
+ # Python-side extraction reads the values, so it needs them decoded.
198
+ **_raw_values_kwargs(not (extract and needs_python_extract)),
199
+ **filter_kwargs,
171
200
  )
172
201
  threads, response_headers = await get_pagination_headers(
173
202
  threads_iter, next_offset, offset
@@ -196,13 +225,14 @@ async def count_threads(
196
225
  ):
197
226
  """Count threads."""
198
227
  payload = await request.json(ThreadCountRequest)
228
+ filter_kwargs = {**_exclude_metadata_kwargs(payload), **_time_range_kwargs(payload)}
199
229
  async with connect() as conn:
200
230
  count = await Threads.count(
201
231
  conn,
202
232
  status=payload.get("status"),
203
233
  values=payload.get("values"),
204
234
  metadata=payload.get("metadata"),
205
- **_exclude_metadata_kwargs(payload),
235
+ **filter_kwargs,
206
236
  )
207
237
  return ApiResponse(count)
208
238
 
@@ -504,7 +534,9 @@ async def get_thread(
504
534
  include_ttl = "ttl" in include_fields
505
535
 
506
536
  async with connect() as conn:
507
- thread = await Threads.get(conn, thread_id, include_ttl=include_ttl)
537
+ thread = await Threads.get(
538
+ conn, thread_id, include_ttl=include_ttl, **_raw_values_kwargs()
539
+ )
508
540
 
509
541
  thread_data = await fetchone(thread)
510
542
  return ApiResponse(thread_data)
@@ -3,6 +3,7 @@ from collections.abc import Sequence
3
3
  from enum import StrEnum
4
4
  from os import environ, getenv
5
5
  from typing import TYPE_CHECKING, Annotated, Literal, TypeVar, cast
6
+ from urllib.parse import urlsplit
6
7
 
7
8
  import structlog
8
9
  from langgraph.version import __version__ as langgraph_version
@@ -653,6 +654,13 @@ else:
653
654
  ),
654
655
  )
655
656
 
657
+
658
+ def langsmith_api_url(path: str) -> str:
659
+ """Return the LangSmith API URL for a /v1 path, since self-hosted endpoints already end in /api/v1."""
660
+ base = (LANGSMITH_AUTH_ENDPOINT or "").rstrip("/")
661
+ return base + ("" if urlsplit(base).path.endswith("/api/v1") else "/v1") + path
662
+
663
+
656
664
  # Webhooks
657
665
 
658
666
 
@@ -691,6 +699,18 @@ LANGSMITH_API_KEY = env(
691
699
  LANGSMITH_CONTROL_PLANE_API_KEY = env(
692
700
  "LANGSMITH_CONTROL_PLANE_API_KEY", cast=str, default=LANGSMITH_API_KEY
693
701
  )
702
+ # IAM role assumed through the AWS SDK's web identity variables; the API key must be bound to an agent.
703
+ LANGSMITH_AWS_ROLE_ARN = env("LANGSMITH_AWS_ROLE_ARN", cast=str, default=None)
704
+ # Entra app or managed identity reached through azure-identity's workload identity variables; both must be set.
705
+ LANGSMITH_AZURE_CLIENT_ID = env("LANGSMITH_AZURE_CLIENT_ID", cast=str, default=None)
706
+ LANGSMITH_AZURE_TENANT_ID = env("LANGSMITH_AZURE_TENANT_ID", cast=str, default=None)
707
+ # Google workload identity provider (//iam.googleapis.com/... resource name), and an optional service account to impersonate.
708
+ LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER = env(
709
+ "LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER", cast=str, default=None
710
+ )
711
+ LANGSMITH_GCP_SERVICE_ACCOUNT = env(
712
+ "LANGSMITH_GCP_SERVICE_ACCOUNT", cast=str, default=None
713
+ )
694
714
 
695
715
 
696
716
  # if langsmith api key is set, enable tracing unless explicitly disabled
@@ -900,7 +920,12 @@ __all__ = [
900
920
  "LANGSMITH_API_KEY",
901
921
  "LANGSMITH_AUTH_ENDPOINT",
902
922
  "LANGSMITH_AUTH_VERIFY_TENANT_ID",
923
+ "LANGSMITH_AWS_ROLE_ARN",
924
+ "LANGSMITH_AZURE_CLIENT_ID",
925
+ "LANGSMITH_AZURE_TENANT_ID",
903
926
  "LANGSMITH_CONTROL_PLANE_API_KEY",
927
+ "LANGSMITH_GCP_SERVICE_ACCOUNT",
928
+ "LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER",
904
929
  "LANGSMITH_TENANT_ID",
905
930
  "LSD_DD_API_KEY",
906
931
  "LSD_DD_ENDPOINT",
langgraph_api/errors.py CHANGED
@@ -1,5 +1,8 @@
1
+ from typing import Any
2
+
1
3
  import jsonschema_rs
2
4
  import structlog
5
+ from langgraph import errors as langgraph_errors
3
6
  from langgraph.errors import EmptyInputError, InvalidUpdateError
4
7
  from starlette.exceptions import HTTPException
5
8
  from starlette.requests import Request
@@ -9,6 +12,30 @@ from langgraph_api.js.errors import RemoteException
9
12
 
10
13
  logger = structlog.stdlib.get_logger(__name__)
11
14
 
15
+ UNKNOWN_INTERRUPT_ERROR = "UnknownInterruptError"
16
+
17
+
18
+ def unknown_interrupt_error(exc: BaseException) -> dict[str, Any] | None:
19
+ """The error payload when strict resume refused an answer, else None.
20
+
21
+ Its message and ids describe the answer the client sent, so they reach
22
+ the client in full. A JS graph's error arrives as a RemoteException, which
23
+ carries only the class name.
24
+ """
25
+ if isinstance(exc, RemoteException):
26
+ return exc.dict() if exc.error == UNKNOWN_INTERRUPT_ERROR else None
27
+ # Absent before langgraph 1.2.20, which has no strict resume to raise it.
28
+ error_class = getattr(langgraph_errors, UNKNOWN_INTERRUPT_ERROR, None)
29
+ if error_class is None or not isinstance(exc, error_class):
30
+ return None
31
+ return {
32
+ "error": UNKNOWN_INTERRUPT_ERROR,
33
+ "message": str(exc),
34
+ "reason": getattr(exc, "reason", None),
35
+ "interrupt_ids": list(getattr(exc, "interrupt_ids", ())),
36
+ "pending_ids": list(getattr(exc, "pending_ids", ())),
37
+ }
38
+
12
39
 
13
40
  def is_body_allowed_for_status_code(status_code: int | None) -> bool:
14
41
  if status_code is None:
@@ -130,16 +130,16 @@ DEFAULT_MULTITASK_STRATEGY = "enqueue"
130
130
 
131
131
 
132
132
  def _multitask_strategy_from_run_start(params: dict[str, Any]) -> str:
133
- """Resolve the per-run ``multitaskStrategy`` from ``run.start`` params.
133
+ """Resolve the per-run multitask strategy from ``run.start`` params.
134
134
 
135
- The SDK forwards the caller's ``multitaskStrategy`` on every
136
- ``run.start`` (one of ``reject`` | ``rollback`` | ``interrupt`` |
137
- ``enqueue``). Honor it when it is one of the recognized strategies,
138
- otherwise fall back to ``DEFAULT_MULTITASK_STRATEGY`` (the legacy
139
- stream-endpoint default). This mirrors the JS reference server's
135
+ ``multitask_strategy`` is the protocol's spelling; older JS SDKs send only
136
+ ``multitaskStrategy``, so that name still works. Honor one of the
137
+ recognized strategies (``reject`` | ``rollback`` | ``interrupt`` |
138
+ ``enqueue``), otherwise fall back to ``DEFAULT_MULTITASK_STRATEGY`` (the
139
+ legacy stream-endpoint default). This mirrors the JS reference server's
140
140
  lenient normalization so both behave identically.
141
141
  """
142
- strategy = params.get("multitaskStrategy")
142
+ strategy = params.get("multitask_strategy", params.get("multitaskStrategy"))
143
143
  if isinstance(strategy, str) and strategy in VALID_MULTITASK_STRATEGIES:
144
144
  return strategy
145
145
  return DEFAULT_MULTITASK_STRATEGY
@@ -740,6 +740,7 @@ class ThreadRunManager:
740
740
  "goto": params.get("goto"),
741
741
  "config": params.get("config"),
742
742
  "metadata": params.get("metadata"),
743
+ "strict_resume": params.get("strict_resume"),
743
744
  },
744
745
  )
745
746
  except ProtocolV2UnsupportedError as exc:
@@ -892,6 +893,7 @@ class ThreadRunManager:
892
893
  "multitask_strategy": _multitask_strategy_from_run_start(params),
893
894
  "langsmith_tracer": _langsmith_tracer_from_run_start(params),
894
895
  "durability": None,
896
+ "strict_resume": params.get("strict_resume") is True,
895
897
  }
896
898
 
897
899
  run_id = make_uuid7()
@@ -502,6 +502,7 @@ class EventStreamingSession:
502
502
  return
503
503
  if event_name == "error":
504
504
  self._terminal_lifecycle_emitted = True
505
+ details: dict[str, Any] | None = None
505
506
  try:
506
507
  error_data = orjson.loads(message_bytes)
507
508
  if _is_record(error_data) and error_data.get("error") == "UserRollback":
@@ -519,10 +520,23 @@ class EventStreamingSession:
519
520
  if _is_record(error_data)
520
521
  else str(error_data)
521
522
  )
523
+ if (
524
+ _is_record(error_data)
525
+ and error_data.get("error") == "UnknownInterruptError"
526
+ ):
527
+ details = {
528
+ key: error_data[key]
529
+ for key in ("reason", "interrupt_ids", "pending_ids")
530
+ if key in error_data
531
+ }
522
532
  except Exception:
523
533
  error_msg = message_bytes.decode("utf-8", errors="replace")
524
534
  await self._emit_namespace_lifecycle(
525
- [], "failed", graph_name=self._root_graph_name, error=error_msg
535
+ [],
536
+ "failed",
537
+ graph_name=self._root_graph_name,
538
+ error=error_msg,
539
+ details=details,
526
540
  )
527
541
  return
528
542
 
@@ -1483,6 +1497,7 @@ class EventStreamingSession:
1483
1497
  graph_name: str | None = None,
1484
1498
  error: str | None = None,
1485
1499
  cause: dict[str, Any] | None = None,
1500
+ details: dict[str, Any] | None = None,
1486
1501
  ) -> None:
1487
1502
  key = to_namespace_key(namespace)
1488
1503
  if namespace and key not in self._namespaces:
@@ -1521,6 +1536,8 @@ class EventStreamingSession:
1521
1536
  lifecycle_data["error"] = error
1522
1537
  if cause is not None:
1523
1538
  lifecycle_data["cause"] = cause
1539
+ if details:
1540
+ lifecycle_data.update(details)
1524
1541
  await self._push_event(
1525
1542
  self._create_event(
1526
1543
  "lifecycle",
@@ -15,9 +15,10 @@ os.environ.setdefault("DISABLE_TRUSTSTORE", "true")
15
15
  import grpc.aio as grpc_aio
16
16
  from langgraph_grpc_common.proto import orchestrator_pb2, orchestrator_pb2_grpc
17
17
 
18
+ from langgraph_api import config, web_identity
18
19
  from langgraph_api.asyncio import ValueEvent
19
20
  from langgraph_api.encryption.context import set_encryption_context
20
- from langgraph_api.errors import UserInterrupt, UserRollback
21
+ from langgraph_api.errors import UserInterrupt, UserRollback, unknown_interrupt_error
21
22
  from langgraph_api.graph import collect_graphs_from_env
22
23
  from langgraph_api.grpc.ops import encryption_context_from_proto
23
24
  from langgraph_api.grpc.ops.runs import proto_to_run
@@ -29,6 +30,7 @@ from langgraph_api.worker_runtime import (
29
30
  cleanup_custom_checkpointer_for_run,
30
31
  fetch_checkpoint_after_failure,
31
32
  fetch_missing_checkpoint,
33
+ resumes_strictly,
32
34
  stream_run,
33
35
  )
34
36
 
@@ -76,6 +78,7 @@ def _done_msg(
76
78
  message: str = "",
77
79
  checkpoint: dict[str, Any] | None = None,
78
80
  exception: dict[str, Any] | None = None,
81
+ refused_resume: bool = False,
79
82
  ) -> orchestrator_pb2.ExecutorMessage:
80
83
  return orchestrator_pb2.ExecutorMessage(
81
84
  done=orchestrator_pb2.Done(
@@ -83,6 +86,7 @@ def _done_msg(
83
86
  message=message,
84
87
  checkpoint_json=json_dumpb(checkpoint) if checkpoint is not None else b"",
85
88
  exception_json=json_dumpb(exception) if exception is not None else b"",
89
+ refused_resume=refused_resume,
86
90
  )
87
91
  )
88
92
 
@@ -122,8 +126,12 @@ async def _run_graph(
122
126
  set_encryption_context(encryption_context or {})
123
127
  tracker = RunCheckpointTracker()
124
128
  temporary = run["kwargs"].get("temporary", False)
129
+ strict = False
125
130
  try:
126
- async for mode, payload in stream_run(run, attempt, cancel, tracker=tracker):
131
+ strict = await resumes_strictly(run, attempt)
132
+ async for mode, payload in stream_run(
133
+ run, attempt, cancel, tracker=tracker, strict_resume=strict
134
+ ):
127
135
  packet = await asyncio.to_thread(json_dumpb, payload)
128
136
  yield orchestrator_pb2.ExecutorMessage(
129
137
  chunk=orchestrator_pb2.Chunk(mode=mode, packet=packet)
@@ -159,10 +167,14 @@ async def _run_graph(
159
167
  exception=_exception_dict(exc),
160
168
  )
161
169
  return
170
+ refusal = unknown_interrupt_error(exc) if strict else None
162
171
  yield _done_msg(
163
172
  status=STATUS_ERROR,
164
173
  message=str(exc),
165
- exception=_exception_dict(exc),
174
+ # The core publishes this as the run's error event, so a refusal
175
+ # carries its reason and ids.
176
+ exception=_exception_dict(exc) if refusal is None else refusal,
177
+ refused_resume=refusal is not None,
166
178
  checkpoint=await _failure_checkpoint(
167
179
  run, failed_attempts, tracker, temporary
168
180
  ),
@@ -281,6 +293,9 @@ async def _bootstrap() -> None:
281
293
  # get_client() with no URL imports langgraph_api.server itself.
282
294
  set_event_loop(asyncio.get_running_loop())
283
295
 
296
+ # Executors skip API lifespan, so they need their own token files before graphs use a cloud SDK.
297
+ await web_identity.start()
298
+
284
299
  from langgraph_runtime import database # noqa: PLC0415
285
300
 
286
301
  await database.start_pool()
@@ -319,7 +334,6 @@ def _configure_logging() -> None:
319
334
 
320
335
  async def amain() -> None:
321
336
  _configure_logging()
322
- from langgraph_api import config # noqa: PLC0415
323
337
 
324
338
  # Role flag before bootstrap so graph registration / other shared code
325
339
  # can skip API-only work (mirrors queue_entrypoint + IS_QUEUE_ENTRYPOINT).
@@ -0,0 +1,52 @@
1
+ """Merge Go core Prometheus text into the Python /metrics scrape.
2
+
3
+ In multi-process mode, queue depth / workers / run lifecycle counters live in
4
+ the Go core-server registry. Scrapers always hit Python :8000/metrics; those
5
+ handlers call ``merge_go_prometheus_text``, which fetches the registry over the
6
+ existing core gRPC channel (same path as PoolStats).
7
+
8
+ Go's ``PrometheusMetrics`` RPC dumps the isPublic registry only — trust that
9
+ filter. ``EXPOSE_INTERNAL_METRICS_PROMETHEUS`` still gates Python's own scrape
10
+ partition; wiring it through to also dump Go internals is a follow-up on the
11
+ Go side.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import structlog
17
+ from google.protobuf.empty_pb2 import Empty # ty: ignore[unresolved-import]
18
+
19
+ from langgraph_api import config
20
+
21
+ logger = structlog.stdlib.get_logger(__name__)
22
+
23
+
24
+ async def fetch_go_prometheus_text() -> bytes | None:
25
+ """Fetch Go Prometheus exposition text via gRPC, or None on any failure."""
26
+ try:
27
+ from langgraph_api.grpc.client import get_shared_client # noqa: PLC0415
28
+
29
+ client = await get_shared_client()
30
+ response = await client.runs.PrometheusMetrics(Empty())
31
+ body = response.body
32
+ return bytes(body) if body else None
33
+ except Exception as exc:
34
+ await logger.awarning(
35
+ "Failed to fetch Go Prometheus metrics for /metrics merge",
36
+ exc_info=exc,
37
+ )
38
+ return None
39
+
40
+
41
+ async def merge_go_prometheus_text(python_body: bytes) -> bytes:
42
+ """Append Go public registry text when multi-process; else python_body."""
43
+ if config.DISPATCH_MODE != config.DispatchMode.MULTI_PROCESS:
44
+ return python_body
45
+
46
+ go_body = await fetch_go_prometheus_text()
47
+ if not go_body:
48
+ return python_body
49
+
50
+ if python_body and not python_body.endswith(b"\n"):
51
+ python_body += b"\n"
52
+ return python_body + go_body
@@ -229,7 +229,6 @@ class GrpcStreamHandler:
229
229
  def __init__(self, run_id: UUID, thread_id: UUID):
230
230
  self.run_id = run_id
231
231
  self.thread_id = thread_id
232
- self.join_requested = False
233
232
  self._stream = None
234
233
  self._closed = False
235
234
 
@@ -283,6 +282,7 @@ class GrpcStreamHandler:
283
282
  cancel_on_disconnect: bool = False,
284
283
  last_event_id: str | None = None,
285
284
  namespaces: list[str] | None = None,
285
+ checkpoint_id: str | None = None,
286
286
  ):
287
287
  """Send JoinRunRequest and yield events.
288
288
 
@@ -304,12 +304,12 @@ class GrpcStreamHandler:
304
304
  join_kwargs["last_event_id"] = last_event_id
305
305
  if namespaces:
306
306
  join_kwargs["namespaces"] = namespaces
307
+ if checkpoint_id is not None:
308
+ join_kwargs["checkpoint_id"] = checkpoint_id
307
309
 
308
310
  # Send JoinRunRequest
309
311
  join_msg = pb.StreamRunClientMessage(join=pb.JoinRunRequest(**join_kwargs))
310
312
  await self._stream.write(join_msg)
311
- # Only after the write: a write cancelled midway may never reach the core.
312
- self.join_requested = True
313
313
 
314
314
  # Half-close: signal we're done sending client messages.
315
315
  # Required for bidirectional streaming so the server knows to stop
@@ -360,28 +360,40 @@ async def _cancel_dropped_join(
360
360
  ctx: Any,
361
361
  filters: list[pb.AuthFilter] | None,
362
362
  ) -> None:
363
- # Same filters and reason as the core's own cancel when a joined stream drops.
364
- # No filters means the drop interrupted the stream's own read check.
365
- if filters is None:
366
- filters = await Runs.Stream.handle_event(
367
- ctx, "read", Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id)
368
- )
369
- client = await get_shared_client()
370
363
  try:
371
- await client.runs.Cancel(
372
- pb.CancelRunRequest(
373
- filters=filters,
374
- action=enum_cancel_run_action.interrupt,
375
- reason="client disconnected from the run stream (on_disconnect=cancel)",
376
- run_ids=pb.CancelRunIdsTarget(
377
- thread_id=pb.UUID(value=str(thread_id)),
378
- run_ids=[pb.UUID(value=str(run_id))],
379
- ),
380
- )
364
+ async with asyncio.timeout(10):
365
+ # Same filters and reason as the core's own cancel when a joined stream drops.
366
+ # No filters means the drop interrupted the stream's own read check.
367
+ if filters is None:
368
+ filters = await Runs.Stream.handle_event(
369
+ ctx,
370
+ "read",
371
+ Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id),
372
+ )
373
+ client = await get_shared_client()
374
+ try:
375
+ await client.runs.Cancel(
376
+ pb.CancelRunRequest(
377
+ filters=filters,
378
+ action=enum_cancel_run_action.interrupt,
379
+ reason="client disconnected from the run stream (on_disconnect=cancel)",
380
+ run_ids=pb.CancelRunIdsTarget(
381
+ thread_id=pb.UUID(value=str(thread_id)),
382
+ run_ids=[pb.UUID(value=str(run_id))],
383
+ ),
384
+ )
385
+ )
386
+ except AioRpcError as e:
387
+ if e.code() != StatusCode.NOT_FOUND:
388
+ raise
389
+ except TimeoutError:
390
+ await logger.awarning(
391
+ "Timed out trying to cancel run on disconnect; investigate whether the run is still running",
392
+ run_id=run_id,
393
+ thread_id=thread_id,
394
+ timeout_seconds=10,
381
395
  )
382
- except AioRpcError as e:
383
- if e.code() != StatusCode.NOT_FOUND:
384
- raise
396
+ raise
385
397
 
386
398
 
387
399
  def _map_multitask_strategy(
@@ -495,6 +507,8 @@ def _proto_kwargs_to_dict(kwargs: pb.RunKwargs) -> dict:
495
507
  else True,
496
508
  "durability": kwargs.durability if kwargs.HasField("durability") else None,
497
509
  }
510
+ if kwargs.HasField("strict_resume") and kwargs.strict_resume:
511
+ result["strict_resume"] = True
498
512
  return result
499
513
 
500
514
 
@@ -1179,6 +1193,7 @@ class Runs(Authenticated):
1179
1193
  stream_mode: list[str] | None = None,
1180
1194
  last_event_id: str | None = None,
1181
1195
  namespaces: list[str] | None = None,
1196
+ checkpoint_id: str | None = None,
1182
1197
  ctx: Any = None,
1183
1198
  ):
1184
1199
  """Join the run stream and start receiving events.
@@ -1204,6 +1219,7 @@ class Runs(Authenticated):
1204
1219
  cancel_on_disconnect=cancel_on_disconnect,
1205
1220
  last_event_id=last_event_id,
1206
1221
  namespaces=namespaces,
1222
+ checkpoint_id=checkpoint_id,
1207
1223
  ):
1208
1224
  yield (event_bytes, message_bytes, stream_id_bytes)
1209
1225
  except AioRpcError as e:
@@ -1213,8 +1229,7 @@ class Runs(Authenticated):
1213
1229
  # Convert all other gRPC errors to HTTP exceptions
1214
1230
  _handle_grpc_error(e)
1215
1231
  except asyncio.CancelledError:
1216
- # The core can cancel on disconnect only after it receives the join request.
1217
- if cancel_on_disconnect and not handler.join_requested:
1232
+ if cancel_on_disconnect:
1218
1233
  create_task(
1219
1234
  _cancel_dropped_join(run_id, thread_id, ctx, auth_filters),
1220
1235
  ignore_exceptions=(HTTPException,),