langgraph-api 0.20.0.dev1__py3-none-any.whl → 0.20.0.dev2__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.
@@ -92,6 +92,17 @@ def _synth_event_id(run_id: str, *parts: str) -> str:
92
92
  return f"synth:{run_id}:{suffix}"
93
93
 
94
94
 
95
+ def _source_time_ms() -> int:
96
+ """When the source event being normalized was published, in ms.
97
+
98
+ Its stream entry id starts with that time, so a session replaying the
99
+ run stamps each event as the live session did. Outside an ingest scope,
100
+ or for an id of another shape, it's the current time.
101
+ """
102
+ ms = (_CURRENT_STREAM_ID.get() or "").partition("-")[0]
103
+ return int(ms) if ms.isdigit() else int(time.time() * 1000)
104
+
105
+
95
106
  class ResumeGap(Exception):
96
107
  """Raised when a ``since`` cursor falls behind the session's buffer head.
97
108
 
@@ -914,7 +925,8 @@ class EventStreamingSession:
914
925
  Path 2 move together.
915
926
 
916
927
  ``timestamp`` lets Path 2 preserve the upstream transformer's
917
- timestamp; Path 1 omits it and gets a fresh server-side value.
928
+ timestamp. Path 1 omits it and gets the time its source event was
929
+ published (:func:`_source_time_ms`), which a replay keeps.
918
930
 
919
931
  ``event_id`` lets synthetic-event callers (lifecycle, input,
920
932
  checkpoint, message-finalize) pass a deterministic id derived
@@ -954,7 +966,7 @@ class EventStreamingSession:
954
966
  params: dict[str, Any] = {
955
967
  "namespace": namespace,
956
968
  "timestamp": (
957
- timestamp if isinstance(timestamp, int) else int(time.time() * 1000)
969
+ timestamp if isinstance(timestamp, int) else _source_time_ms()
958
970
  ),
959
971
  "data": normalized_data,
960
972
  }
@@ -18,7 +18,12 @@ from langgraph_grpc_common.proto import orchestrator_pb2, orchestrator_pb2_grpc
18
18
  from langgraph_api import config, web_identity
19
19
  from langgraph_api.asyncio import ValueEvent
20
20
  from langgraph_api.encryption.context import set_encryption_context
21
- from langgraph_api.errors import UserInterrupt, UserRollback, unknown_interrupt_error
21
+ from langgraph_api.errors import (
22
+ AgentDisabledError,
23
+ UserInterrupt,
24
+ UserRollback,
25
+ unknown_interrupt_error,
26
+ )
22
27
  from langgraph_api.graph import collect_graphs_from_env
23
28
  from langgraph_api.grpc.ops import encryption_context_from_proto
24
29
  from langgraph_api.grpc.ops.runs import proto_to_run
@@ -175,9 +180,11 @@ async def _run_graph(
175
180
  # carries its reason and ids.
176
181
  exception=_exception_dict(exc) if refusal is None else refusal,
177
182
  refused_resume=refusal is not None,
178
- checkpoint=await _failure_checkpoint(
179
- run, failed_attempts, tracker, temporary
180
- ),
183
+ # A disabled agent's run is refused before it starts, so on its first
184
+ # claim there is no state to read; a later claim reads what earlier ones wrote.
185
+ checkpoint=None
186
+ if isinstance(exc, AgentDisabledError) and attempt == 1
187
+ else await _failure_checkpoint(run, failed_attempts, tracker, temporary),
181
188
  )
182
189
 
183
190
 
@@ -118,6 +118,11 @@ def _metadata_interceptors() -> list[aio.ClientInterceptor]:
118
118
  # Shared gRPC client pools (main thread + thread-local for isolated loops).
119
119
  _client_pool: "GrpcClientPool | None" = None
120
120
  _thread_local = threading.local()
121
+ # Pools from an older generation are replaced on their next use.
122
+ _generation = 0
123
+ _GENERATION_CHANNEL_ARG = "langgraph.connection_generation"
124
+ _STALE_POOL_CLOSE_DELAY_SECS = 10.0
125
+ _closing_pools: set[asyncio.Task] = set()
121
126
 
122
127
 
123
128
  GRPC_HEALTHCHECK_TIMEOUT = 5.0
@@ -131,13 +136,16 @@ class GrpcClient:
131
136
  def __init__(
132
137
  self,
133
138
  server_address: str | None = None,
139
+ generation: int = 0,
134
140
  ):
135
141
  """Initialize the gRPC client.
136
142
 
137
143
  Args:
138
144
  server_address: The gRPC server address (default: localhost:50051)
145
+ generation: The reset_shared_clients generation it belongs to
139
146
  """
140
147
  self.server_address = server_address or config.LSD_GRPC_SERVER_ADDRESS
148
+ self.generation = generation
141
149
  self._channel: aio.Channel | None = None
142
150
  self._assistants_stub: AssistantsStub | None = None
143
151
  self._runs_stub: RunsStub | None = None
@@ -178,6 +186,10 @@ class GrpcClient:
178
186
  ("grpc.initial_reconnect_backoff_ms", 100),
179
187
  ("grpc.max_reconnect_backoff_ms", 1000),
180
188
  ]
189
+ if self.generation:
190
+ # Channels with identical options share TCP connections, so a reset
191
+ # must differ in an option to dial afresh.
192
+ options.append((_GENERATION_CHANNEL_ARG, self.generation))
181
193
 
182
194
  self._channel = aio.insecure_channel(
183
195
  self.server_address,
@@ -311,6 +323,7 @@ class GrpcClientPool:
311
323
  self._current_index = 0
312
324
  self._init_lock = asyncio.Lock()
313
325
  self._initialized = False
326
+ self.generation = _generation
314
327
 
315
328
  async def _initialize(self):
316
329
  """Initialize the pool of clients."""
@@ -325,7 +338,9 @@ class GrpcClientPool:
325
338
  )
326
339
 
327
340
  for _ in range(self.pool_size):
328
- client = GrpcClient(server_address=self.server_address)
341
+ client = GrpcClient(
342
+ server_address=self.server_address, generation=self.generation
343
+ )
329
344
  await client.connect()
330
345
  self.clients.append(client)
331
346
 
@@ -370,6 +385,9 @@ async def get_shared_client() -> GrpcClient:
370
385
  """
371
386
  if threading.current_thread() is not threading.main_thread():
372
387
  pool = getattr(_thread_local, "grpc_pool", None)
388
+ if pool is not None and pool.generation != _generation:
389
+ _close_later(pool)
390
+ pool = None
373
391
  if pool is None:
374
392
  pool = GrpcClientPool(
375
393
  pool_size=1,
@@ -379,6 +397,9 @@ async def get_shared_client() -> GrpcClient:
379
397
  return await pool.get_client()
380
398
 
381
399
  global _client_pool
400
+ if _client_pool is not None and _client_pool.generation != _generation:
401
+ _close_later(_client_pool)
402
+ _client_pool = None
382
403
  if _client_pool is None:
383
404
  _client_pool = GrpcClientPool(
384
405
  pool_size=config.GRPC_CLIENT_POOL_SIZE,
@@ -387,6 +408,28 @@ async def get_shared_client() -> GrpcClient:
387
408
  return await _client_pool.get_client()
388
409
 
389
410
 
411
+ def reset_shared_clients() -> None:
412
+ """Make every gRPC client pool dial afresh on its next use.
413
+
414
+ For when the process's connections are dead though it kept running, as
415
+ after resuming from a memory snapshot. Each thread's pool is replaced the
416
+ next time that thread asks for a client; RPCs already on the old pool get
417
+ a grace period before it closes.
418
+ """
419
+ global _generation
420
+ _generation += 1
421
+
422
+
423
+ def _close_later(pool: "GrpcClientPool") -> None:
424
+ async def close() -> None:
425
+ await asyncio.sleep(_STALE_POOL_CLOSE_DELAY_SECS)
426
+ await pool.close()
427
+
428
+ task = asyncio.get_running_loop().create_task(close())
429
+ _closing_pools.add(task)
430
+ task.add_done_callback(_closing_pools.discard)
431
+
432
+
390
433
  def _get_go_core_exit_detail() -> str | None:
391
434
  """Return a diagnostic message if the Go core-api-grpc process has exited."""
392
435
  pid_str = os.environ.get("CORE_API_GRPC_PID")
langgraph_api/http.py CHANGED
@@ -2,6 +2,7 @@ import asyncio
2
2
  import contextlib
3
3
 
4
4
  import httpx
5
+ from httpx._utils import get_environment_proxies
5
6
  from tenacity import (
6
7
  retry,
7
8
  retry_if_exception,
@@ -74,16 +75,41 @@ _http_client: JsonHttpClient | None = None
74
75
  _loopback_client: JsonHttpClient | None = None
75
76
 
76
77
 
78
+ def environment_proxy_mounts(
79
+ *, retries: int, limits: httpx.Limits
80
+ ) -> dict[str, httpx.AsyncHTTPTransport | None]:
81
+ """Proxy-aware transports for an explicit-transport httpx client.
82
+
83
+ httpx only reads HTTP_PROXY / HTTPS_PROXY / NO_PROXY when no explicit
84
+ transport is given. Our clients pass one for ``retries``, so build one
85
+ transport per proxy pattern from the environment ourselves. NO_PROXY hosts
86
+ map to ``None`` so they fall through to the client's direct transport. With
87
+ no proxy variables set this is empty and the client is unchanged. Only
88
+ http(s) proxies are mounted: a SOCKS URL in ``ALL_PROXY`` needs the optional
89
+ ``socksio`` package, and it was ignored before this helper existed, so keep
90
+ ignoring it rather than failing at startup.
91
+ """
92
+ mounts: dict[str, httpx.AsyncHTTPTransport | None] = {}
93
+ for pattern, proxy in get_environment_proxies().items():
94
+ if proxy is None:
95
+ mounts[pattern] = None
96
+ elif proxy.startswith(("http://", "https://")):
97
+ mounts[pattern] = httpx.AsyncHTTPTransport(
98
+ retries=retries, limits=limits, proxy=httpx.Proxy(proxy)
99
+ )
100
+ return mounts
101
+
102
+
77
103
  async def start_http_client() -> JsonHttpClient:
78
104
  global _http_client
105
+ limits = httpx.Limits(max_keepalive_connections=10, keepalive_expiry=60.0)
79
106
  _http_client = JsonHttpClient(
80
107
  client=httpx.AsyncClient(
81
108
  transport=httpx.AsyncHTTPTransport(
82
109
  retries=2, # this applies only to ConnectError, ConnectTimeout
83
- limits=httpx.Limits(
84
- max_keepalive_connections=10, keepalive_expiry=60.0
85
- ),
110
+ limits=limits,
86
111
  ),
112
+ mounts=environment_proxy_mounts(retries=2, limits=limits),
87
113
  ),
88
114
  )
89
115
  return _http_client
@@ -34,6 +34,12 @@ def start_store() -> None:
34
34
  )
35
35
 
36
36
 
37
+ async def reconnect_after_resume() -> None:
38
+ """Close the store's connection after a resume from a memory snapshot; the next call opens a new one."""
39
+ if (store := getattr(_STORE, "store", None)) is not None:
40
+ await store.aclose()
41
+
42
+
37
43
  def get_store_config() -> api_config.StoreConfig:
38
44
  return _STORE_CONFIG
39
45
 
@@ -0,0 +1,114 @@
1
+ """The process that runs in an app's sandboxes: python -m langgraph_api.sandbox_entrypoint
2
+
3
+ It does two jobs. It serves the API on ``PORT`` (default 8000), and it runs the
4
+ attempts core-api hands it through an inbox (see ``sandbox_worker``). In the
5
+ app's sandbox function only the API is used. In a thread's sandbox only the
6
+ inbox is used.
7
+
8
+ Because the process is the same in both, one memory snapshot of it, taken once
9
+ it is ready, can start either kind of sandbox already warm.
10
+
11
+ It keeps these files in ``LANGGRAPH_EXECUTOR_DIR`` (default
12
+ ``/tmp/langgraph-executor``):
13
+
14
+ - ``daemon.lock``: locked while the process runs, so a sandbox runs only one.
15
+ - ``daemon.pid``: the process ID.
16
+ - ``daemon.addr``: the core-api address the process connects to.
17
+ - ``ready``: written once the API is up and the inbox is being checked.
18
+ - ``inbox/<id>.json``: attempts from core-api.
19
+
20
+ The handoff command reads ``daemon.pid`` and ``daemon.addr`` to decide whether
21
+ to start the process, or to restart it because it connects to a different
22
+ core-api.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import contextlib
29
+ import fcntl
30
+ import logging
31
+ import os
32
+ import sys
33
+ import time
34
+ from pathlib import Path
35
+
36
+ from langgraph_api import sandbox_server, sandbox_worker
37
+
38
+ PROCESS_STARTED = time.monotonic()
39
+
40
+ logger = logging.getLogger("langgraph_api.sandbox_entrypoint")
41
+
42
+ EXECUTOR_DIR = Path(os.environ.get("LANGGRAPH_EXECUTOR_DIR", "/tmp/langgraph-executor"))
43
+
44
+
45
+ def take_lock(directory: Path) -> int | None:
46
+ """Lock the directory for this process.
47
+
48
+ Return the lock's file descriptor, or None if another process holds it.
49
+ """
50
+ directory.mkdir(parents=True, exist_ok=True)
51
+ fd = os.open(directory / "daemon.lock", os.O_RDWR | os.O_CREAT, 0o600)
52
+ try:
53
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
54
+ except BlockingIOError:
55
+ os.close(fd)
56
+ return None
57
+ (directory / "daemon.pid").write_text(str(os.getpid()))
58
+ return fd
59
+
60
+
61
+ async def amain() -> int:
62
+ from langgraph_api import config # noqa: PLC0415
63
+
64
+ sandbox_server.configure_logging()
65
+ if take_lock(EXECUTOR_DIR) is None:
66
+ logger.info("Another entrypoint process already runs in this sandbox")
67
+ return 0
68
+ ready = EXECUTOR_DIR / "ready"
69
+ ready.unlink(missing_ok=True)
70
+ # The handoff restarts this process if core-api's address has changed.
71
+ (EXECUTOR_DIR / "daemon.addr").write_text(config.LSD_GRPC_SERVER_ADDRESS or "")
72
+
73
+ serving = await sandbox_server.start_api_server()
74
+ if serving is None:
75
+ return 1
76
+
77
+ inbox = EXECUTOR_DIR / "inbox"
78
+ inbox.mkdir(parents=True, exist_ok=True)
79
+ stop, started = asyncio.Event(), asyncio.Event()
80
+ worker = asyncio.create_task(
81
+ sandbox_worker.serve(
82
+ inbox,
83
+ sandbox_worker.run_assignment,
84
+ resumed=sandbox_worker.reconnect_after_resume,
85
+ stop=stop,
86
+ started=started,
87
+ )
88
+ )
89
+ # A memory snapshot may be taken as soon as ready appears, and the worker
90
+ # must already be timing the gap that marks a resume.
91
+ await started.wait()
92
+ ready.write_text(str(os.getpid()))
93
+ logger.info("Ready in %.0f ms", (time.monotonic() - PROCESS_STARTED) * 1000)
94
+ try:
95
+ await serving
96
+ finally:
97
+ stop.set()
98
+ await worker
99
+ return 0
100
+
101
+
102
+ def main() -> None:
103
+ # The process runs only the attempts handed to it, so the API server must
104
+ # not claim runs with its own queue. Set before langgraph_api.config loads.
105
+ os.environ["N_JOBS_PER_WORKER"] = "0"
106
+ # Start a new session so this process keeps running after the handoff command exits.
107
+ with contextlib.suppress(OSError):
108
+ os.setsid()
109
+ with contextlib.suppress(KeyboardInterrupt):
110
+ sys.exit(asyncio.run(amain()))
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
@@ -0,0 +1,48 @@
1
+ """The sandbox entrypoint's API server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ from pathlib import Path
9
+
10
+ logger = logging.getLogger("langgraph_api.sandbox_server")
11
+
12
+ LOG_CONFIG = Path("/api/logging.json")
13
+ STARTUP_POLL_SECS = 0.05
14
+
15
+
16
+ def configure_logging() -> None:
17
+ """Configure logging from the image's logging.json, or like the executor if that file is missing."""
18
+ if not LOG_CONFIG.exists():
19
+ from langgraph_api.executor.__main__ import _configure_logging # noqa: PLC0415
20
+
21
+ _configure_logging()
22
+
23
+
24
+ async def start_api_server() -> asyncio.Task[None] | None:
25
+ """Start the API server on PORT.
26
+
27
+ Return its task once it accepts requests, or None if it exits before that.
28
+ """
29
+ import uvicorn # noqa: PLC0415
30
+
31
+ server = uvicorn.Server(
32
+ uvicorn.Config(
33
+ "langgraph_api.server:app",
34
+ host=os.environ.get("LANGGRAPH_SERVER_HOST", ""),
35
+ port=int(os.environ.get("PORT", "8000")),
36
+ log_config=str(LOG_CONFIG) if LOG_CONFIG.exists() else None,
37
+ access_log=False,
38
+ timeout_graceful_shutdown=3600,
39
+ timeout_keep_alive=int(os.environ.get("UVICORN_TIMEOUT_KEEP_ALIVE", "75")),
40
+ )
41
+ )
42
+ serving = asyncio.create_task(server.serve())
43
+ while not server.started:
44
+ if serving.done():
45
+ logger.error("API server exited before it started")
46
+ return None
47
+ await asyncio.sleep(STARTUP_POLL_SECS)
48
+ return serving