Files
langgraph/libs/langgraph/langgraph/pregel/_retry.py
T
Sydney RunkleandGitHub e533d00687 fix: execution info patching (#7406)
## Summary

- Fixes a bug where `runtime.execution_info` is `None` in the
distributed runtime (LangGraph Platform) because tasks are prepared by
the server and deserialized in the executor, bypassing the OSS
`_algo.py` code that normally creates `ExecutionInfo`
- Adds `_ensure_execution_info()` in `_retry.py` that lazily constructs
`ExecutionInfo` from the task config when it's missing, called in both
`run_with_retry` and `arun_with_retry`

## Why

PR #7363 introduced `ExecutionInfo` on `Runtime`, populated during task
preparation in `_algo.py`. However, on LangGraph Platform (distributed
runtime), tasks are serialized by the server and deserialized in a
separate executor process — `_algo.py` task prep never runs in that
context, so `execution_info` remains `None`. Any user code or tooling
relying on `runtime.execution_info` (e.g. for tracing, logging, or auth)
would fail with `None` fields.

The fix reconstructs `ExecutionInfo` from config keys (`checkpoint_id`,
`checkpoint_ns`, `task_id`, `thread_id`, `run_id`) that are already
present in the deserialized task config, so no server-side changes are
needed.

## Test plan

- [x] `_ensure_execution_info` is a no-op when `execution_info` already
exists
- [x] `_ensure_execution_info` creates `ExecutionInfo` from config when
missing
- [x] Falls back to `task.id` when `CONFIG_KEY_TASK_ID` is absent from
config
- [x] End-to-end `run_with_retry` test simulating the distributed
runtime scenario (runtime with `execution_info=None`)
2026-04-03 14:53:57 -04:00

319 lines
12 KiB
Python

from __future__ import annotations
import asyncio
import logging
import random
import sys
import time
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import replace
from typing import Any
from langchain_core.runnables import RunnableConfig
from langgraph._internal._config import patch_configurable, recast_checkpoint_ns
from langgraph._internal._constants import (
CONF,
CONFIG_KEY_CHECKPOINT_ID,
CONFIG_KEY_CHECKPOINT_NS,
CONFIG_KEY_RESUMING,
CONFIG_KEY_RUNTIME,
CONFIG_KEY_TASK_ID,
CONFIG_KEY_THREAD_ID,
NS_SEP,
)
from langgraph.errors import GraphBubbleUp, ParentCommand
from langgraph.runtime import ExecutionInfo, Runtime
from langgraph.types import Command, PregelExecutableTask, RetryPolicy
logger = logging.getLogger(__name__)
SUPPORTS_EXC_NOTES = sys.version_info >= (3, 11)
def _ensure_execution_info(
runtime: Runtime, config: RunnableConfig, task: PregelExecutableTask
) -> Runtime:
"""Ensure runtime has execution_info, creating one from config if needed.
In the distributed runtime (LangGraph Platform), tasks are prepared by the
server and deserialized in the executor, bypassing the OSS _algo.py code
that normally creates ExecutionInfo. This function fills in execution_info
from the task config when it's missing.
"""
if runtime.execution_info is not None:
return runtime
configurable = config.get(CONF, {})
return runtime.override(
execution_info=ExecutionInfo(
checkpoint_id=configurable.get(CONFIG_KEY_CHECKPOINT_ID) or "",
checkpoint_ns=configurable.get(CONFIG_KEY_CHECKPOINT_NS) or "",
task_id=configurable.get(CONFIG_KEY_TASK_ID) or task.id,
thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
run_id=str(rid) if (rid := config.get("run_id")) else None,
),
)
def _checkpoint_ns_for_parent_command(ns: str) -> str:
"""Return the checkpoint namespace for the parent graph.
The checkpoint namespace is a `|`-separated path. Each segment is usually
of the form `name:task_id` (e.g. `parent_first:<uuid>|node:<uuid>`), but the
runtime may also insert a purely-numeric segment (e.g. `|1`) to disambiguate
concurrent tasks (e.g. `parent_first:<uuid>|1|node:<uuid>`).
Numeric segments are not real path levels, so we drop them before computing
the parent namespace.
"""
parts = ns.split(NS_SEP)
# Drop any trailing numeric selectors for the current frame (e.g. `...|node:<id>|1`).
while parts and parts[-1].isdigit():
parts.pop()
# Drop the current frame segment itself (e.g. the `node:<id>`).
if parts:
parts.pop()
# Drop any trailing numeric selectors for the parent frame (e.g. `...|1|node:<id>`).
while parts and parts[-1].isdigit():
parts.pop()
return NS_SEP.join(parts)
def run_with_retry(
task: PregelExecutableTask,
retry_policy: Sequence[RetryPolicy] | None,
configurable: dict[str, Any] | None = None,
) -> None:
"""Run a task with retries."""
retry_policy = task.retry_policy or retry_policy
attempts = 0
node_first_attempt_time = time.time()
config = task.config
if configurable is not None:
config = patch_configurable(config, configurable)
runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
if isinstance(runtime, Runtime):
runtime = _ensure_execution_info(runtime, config, task)
config = patch_configurable(
config,
{
CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
node_first_attempt_time=node_first_attempt_time,
)
},
)
while True:
runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
if isinstance(runtime, Runtime):
config = patch_configurable(
config,
{
CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
# node_attempt is execution count (1-indexed): 1 on first run,
# then 2, 3, ... on subsequent retries.
node_attempt=attempts + 1,
)
},
)
try:
# clear any writes from previous attempts
task.writes.clear()
# run the task
return task.proc.invoke(task.input, config)
except ParentCommand as exc:
ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
cmd = exc.args[0]
# strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
# this command is for the current graph, handle it
for w in task.writers:
w.invoke(cmd, config)
break
elif cmd.graph == Command.PARENT:
# this command is for the parent graph, assign it to the parent.
exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
# bubble up
raise
except GraphBubbleUp:
# if interrupted, end
raise
except Exception as exc:
if SUPPORTS_EXC_NOTES:
exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
if not retry_policy:
raise
# Check which retry policy applies to this exception
matching_policy = None
for policy in retry_policy:
if _should_retry_on(policy, exc):
matching_policy = policy
break
if not matching_policy:
raise
# attempts tracks failed tries only; it increments after a failure.
attempts += 1
# check if we should give up
if attempts >= matching_policy.max_attempts:
raise
# sleep before retrying
interval = matching_policy.initial_interval
# Apply backoff factor based on attempt count
interval = min(
matching_policy.max_interval,
interval * (matching_policy.backoff_factor ** (attempts - 1)),
)
# Apply jitter if configured
sleep_time = (
interval + random.uniform(0, 1) if matching_policy.jitter else interval
)
time.sleep(sleep_time)
# log the retry
logger.info(
f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
exc_info=exc,
)
# signal subgraphs to resume (if available)
config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
async def arun_with_retry(
task: PregelExecutableTask,
retry_policy: Sequence[RetryPolicy] | None,
stream: bool = False,
match_cached_writes: Callable[[], Awaitable[Sequence[PregelExecutableTask]]]
| None = None,
configurable: dict[str, Any] | None = None,
) -> None:
"""Run a task asynchronously with retries."""
retry_policy = task.retry_policy or retry_policy
attempts = 0
node_first_attempt_time = time.time()
config = task.config
if configurable is not None:
config = patch_configurable(config, configurable)
runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
if isinstance(runtime, Runtime):
runtime = _ensure_execution_info(runtime, config, task)
config = patch_configurable(
config,
{
CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
node_first_attempt_time=node_first_attempt_time,
)
},
)
if match_cached_writes is not None and task.cache_key is not None:
for t in await match_cached_writes():
if t is task:
# if the task is already cached, return
return
while True:
runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
if isinstance(runtime, Runtime):
config = patch_configurable(
config,
{
CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
# node_attempt is execution count (1-indexed): 1 on first run,
# then 2, 3, ... on subsequent retries.
node_attempt=attempts + 1,
)
},
)
try:
# clear any writes from previous attempts
task.writes.clear()
# run the task
if stream:
async for _ in task.proc.astream(task.input, config):
pass
# if successful, end
break
else:
return await task.proc.ainvoke(task.input, config)
except ParentCommand as exc:
ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
cmd = exc.args[0]
# strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
# this command is for the current graph, handle it
for w in task.writers:
w.invoke(cmd, config)
break
elif cmd.graph == Command.PARENT:
# this command is for the parent graph, assign it to the parent.
exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
# bubble up
raise
except GraphBubbleUp:
# if interrupted, end
raise
except Exception as exc:
if SUPPORTS_EXC_NOTES:
exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
if not retry_policy:
raise
# Check which retry policy applies to this exception
matching_policy = None
for policy in retry_policy:
if _should_retry_on(policy, exc):
matching_policy = policy
break
if not matching_policy:
raise
# attempts tracks failed tries only; it increments after a failure.
# The next execution's node_attempt is derived as attempts + 1.
attempts += 1
# check if we should give up
if attempts >= matching_policy.max_attempts:
raise
# sleep before retrying
interval = matching_policy.initial_interval
# Apply backoff factor based on attempt count
interval = min(
matching_policy.max_interval,
interval * (matching_policy.backoff_factor ** (attempts - 1)),
)
# Apply jitter if configured
sleep_time = (
interval + random.uniform(0, 1) if matching_policy.jitter else interval
)
await asyncio.sleep(sleep_time)
# log the retry
logger.info(
f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
exc_info=exc,
)
# signal subgraphs to resume (if available)
config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
def _should_retry_on(retry_policy: RetryPolicy, exc: Exception) -> bool:
"""Check if the given exception should be retried based on the retry policy."""
if isinstance(retry_policy.retry_on, Sequence):
return isinstance(exc, tuple(retry_policy.retry_on))
elif isinstance(retry_policy.retry_on, type) and issubclass(
retry_policy.retry_on, Exception
):
return isinstance(exc, retry_policy.retry_on)
elif callable(retry_policy.retry_on):
return retry_policy.retry_on(exc) # type: ignore[call-arg]
else:
raise TypeError(
"retry_on must be an Exception class, a list or tuple of Exception classes, or a callable"
)