Compare commits

..
Author SHA1 Message Date
Christian Bromann 2d33866447 fix 2026-04-01 10:15:59 -07:00
Christian Bromann c78866a2c4 fix(langgraph): update readme 2026-04-01 10:13:25 -07:00
30 changed files with 1298 additions and 3201 deletions
-161
View File
@@ -1,161 +0,0 @@
"""Create a tarball of project source for remote builds."""
import os
import pathlib
import tarfile
import tempfile
from contextlib import contextmanager
import click
import pathspec
from langgraph_cli.config import Config, _assemble_local_deps
_WARN_SIZE = 50 * 1024 * 1024 # 50 MB
_MAX_SIZE = 200 * 1024 * 1024 # 200 MB
_ALWAYS_EXCLUDE = [
"__pycache__/",
".git/",
".venv/",
"venv/",
"node_modules/",
".tox/",
".mypy_cache/",
]
def _build_ignore_spec(directory: pathlib.Path) -> pathspec.PathSpec:
"""Build a PathSpec combining built-in exclusions with .dockerignore and .gitignore.
Always excludes common non-source directories (_ALWAYS_EXCLUDE). On top of
that, patterns from .dockerignore and .gitignore (if present) are merged in.
"""
lines: list[str] = list(_ALWAYS_EXCLUDE)
for name in (".dockerignore", ".gitignore"):
ignore_file = directory / name
if ignore_file.is_file():
lines.extend(ignore_file.read_text(encoding="utf-8").splitlines())
return pathspec.PathSpec.from_lines("gitwildmatch", lines)
def _tar_filter(tarinfo: tarfile.TarInfo) -> tarfile.TarInfo | None:
"""Strip symlinks, hardlinks, and traversal paths from archive."""
if tarinfo.issym() or tarinfo.islnk():
return None
if ".." in tarinfo.name.split("/"):
return None
return tarinfo
def _add_directory(
tar: tarfile.TarFile,
source_dir: pathlib.Path,
arcname_prefix: str | None,
ignore_spec: pathspec.PathSpec,
) -> None:
"""Recursively add a directory to the tarball under the given prefix.
If arcname_prefix is None, files are added at the archive root.
Paths matching ignore_spec are excluded.
"""
for root, dirs, files in os.walk(source_dir):
rel_root = os.path.relpath(root, source_dir).replace(os.sep, "/")
dirs[:] = [
d
for d in dirs
if not ignore_spec.match_file(
f"{rel_root}/{d}/" if rel_root != "." else f"{d}/"
)
]
for f in files:
full_path = os.path.join(root, f)
rel = os.path.relpath(full_path, source_dir).replace(os.sep, "/")
if ignore_spec.match_file(rel):
continue
arcname = f"{arcname_prefix}/{rel}" if arcname_prefix else rel
info = tar.gettarinfo(full_path, arcname=arcname)
filtered = _tar_filter(info)
if filtered is None:
continue
with open(full_path, "rb") as fobj:
tar.addfile(filtered, fobj)
@contextmanager
def create_archive(
config_path: pathlib.Path,
config: Config,
):
"""Context manager that creates a .tar.gz archive of the project source.
Uses _assemble_local_deps to discover local dependencies referenced in
langgraph.json, including those outside config.parent (monorepo case).
The archive preserves the real filesystem layout relative to the common
ancestor of config.parent and all external dependency directories, so that
relative references (e.g. `../shared-lib`) resolve correctly after
extraction.
Yields (archive_path, file_size, config_relative_path). The temporary
directory holding the archive is cleaned up automatically on exit.
"""
config_path = config_path.resolve()
context_dir = config_path.parent
local_deps = _assemble_local_deps(config_path, config)
extra_contexts = local_deps.additional_contexts or []
dirs_to_include = [context_dir] + list(extra_contexts)
common = context_dir
for d in extra_contexts:
common = pathlib.Path(os.path.commonpath([common, d]))
tmp_dir = tempfile.mkdtemp(prefix="langgraph-deploy-")
try:
archive_path = os.path.join(tmp_dir, "source.tar.gz")
added_dirs: set[str] = set()
with tarfile.open(archive_path, "w:gz") as tar:
for dir_path in dirs_to_include:
rel = dir_path.relative_to(common)
prefix = str(rel).replace(os.sep, "/") if str(rel) != "." else None
key = prefix or ""
if key in added_dirs:
continue
added_dirs.add(key)
ignore_spec = _build_ignore_spec(dir_path)
_add_directory(
tar, dir_path, arcname_prefix=prefix, ignore_spec=ignore_spec
)
file_size = os.path.getsize(archive_path)
config_rel = str(config_path.relative_to(common)).replace(os.sep, "/")
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
if config_rel not in names:
raise click.ClickException(
f"Archive validation failed: {config_rel} not found in archive"
)
if file_size > _MAX_SIZE:
raise click.ClickException(
f"Source archive is {file_size / 1_048_576:.1f} MB, which exceeds the 200 MB limit. "
"Add large files to .dockerignore or .gitignore (model weights, data sets, etc.)."
)
if file_size > _WARN_SIZE:
click.secho(
f" Warning: source archive is {file_size / 1_048_576:.1f} MB. "
"Consider adding large files to .dockerignore or .gitignore.",
fg="yellow",
)
yield archive_path, file_size, config_rel
finally:
import shutil
shutil.rmtree(tmp_dir, ignore_errors=True)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-128
View File
@@ -1,14 +1,10 @@
import copy
import json
import pathlib
import platform
import shutil
from collections.abc import Callable, Sequence
from typing import Literal, NamedTuple
import click.exceptions
import langgraph_cli.config
from langgraph_cli.exec import subp_exec
ROOT = pathlib.Path(__file__).parent.resolve()
@@ -49,54 +45,6 @@ def _parse_version(version: str) -> Version:
)
def can_build_locally() -> tuple[bool, str | None]:
"""Return whether local deployment builds can run on this machine.
Checks:
- Docker binary is installed
- Docker daemon is running
- Buildx is available when cross-compilation is required (non-x86_64)
"""
if shutil.which("docker") is None:
return (
False,
"Docker is required but not installed.\n"
"Install Docker Desktop: https://docs.docker.com/get-docker/",
)
try:
import subprocess
docker_info = subprocess.run(
["docker", "info"],
capture_output=True,
timeout=10,
)
if docker_info.returncode != 0:
return (
False,
"Docker is installed but not running.\nStart Docker and try again.",
)
if platform.machine() != "x86_64":
buildx = subprocess.run(
["docker", "buildx", "version"],
capture_output=True,
timeout=10,
)
if buildx.returncode != 0:
return (
False,
"Docker Buildx is required but not installed.\n"
"Your machine architecture ("
+ platform.machine()
+ ") requires Buildx to cross-compile images for linux/amd64.\n"
"Install Buildx: https://docs.docker.com/build/install-buildx/",
)
return True, None
except Exception:
return False, "Unable to verify local Docker build support."
def check_capabilities(runner) -> DockerCapabilities:
# check docker available
if shutil.which("docker") is None:
@@ -328,79 +276,3 @@ def compose(
)
compose_str = dict_to_yaml(compose_content)
return compose_str
def build_docker_image(
runner,
set: Callable[[str], None],
config: pathlib.Path,
config_json: dict,
base_image: str | None,
api_version: str | None,
pull: bool,
tag: str,
passthrough: Sequence[str] = (),
install_command: str | None = None,
build_command: str | None = None,
docker_command: Sequence[str] | None = None,
extra_flags: Sequence[str] = (),
verbose: bool = True,
):
"""Build a Docker image from a LangGraph config."""
# pull latest images
if pull:
runner.run(
subp_exec(
"docker",
"pull",
langgraph_cli.config.docker_tag(config_json, base_image, api_version),
verbose=verbose,
)
)
set("Building...")
# apply options
args = [
"-f",
"-", # stdin
"-t",
tag,
]
# determine build context: use current directory for JS projects, config parent for Python
is_js_project = config_json.get("node_version") and not config_json.get(
"python_version"
)
# build/install commands only apply to JS projects for now
# without install/build command, JS projects will follow the old behavior
if is_js_project and (build_command or install_command):
build_context = str(pathlib.Path.cwd())
else:
build_context = str(config.parent)
# Deep copy to avoid mutating the caller's config (config_to_docker
# rewrites graph paths to container-internal paths in place).
config_json = copy.deepcopy(config_json)
stdin, additional_contexts = langgraph_cli.config.config_to_docker(
config_path=config,
config=config_json,
base_image=base_image,
api_version=api_version,
install_command=install_command,
build_command=build_command,
build_context=build_context,
)
# add additional_contexts
if additional_contexts:
for k, v in additional_contexts.items():
args.extend(["--build-context", f"{k}={v}"])
cmd = tuple(docker_command) if docker_command else ("docker", "build")
runner.run(
subp_exec(
*cmd,
*args,
*extra_flags,
*passthrough,
build_context,
input=stdin,
verbose=verbose,
)
)
+59
View File
@@ -0,0 +1,59 @@
"""Helpers for the ``langgraph logs`` CLI command."""
from __future__ import annotations
from datetime import datetime, timezone
import click
from langgraph_cli.host_backend import HostBackendClient
def resolve_deployment_id(
client: HostBackendClient,
deployment_id: str | None,
name: str | None,
) -> str:
"""Resolve a deployment ID from --deployment-id or --name."""
if deployment_id:
return deployment_id
if not name:
raise click.UsageError("Either --deployment-id or --name is required.")
existing = client.list_deployments(name_contains=name)
if isinstance(existing, dict):
for dep in existing.get("resources", []):
if isinstance(dep, dict) and dep.get("name") == name:
found_id = dep.get("id")
if found_id:
return str(found_id)
raise click.ClickException(f"Deployment '{name}' not found.")
def format_timestamp(ts) -> str:
"""Convert a timestamp (epoch ms or string) to a readable string."""
if isinstance(ts, (int, float)):
dt = datetime.fromtimestamp(ts / 1000, tz=timezone.utc)
return dt.strftime("%Y-%m-%d %H:%M:%S")
return str(ts) if ts else ""
def format_log_entry(entry: dict) -> str:
"""Format a single log entry for display."""
ts = format_timestamp(entry.get("timestamp", ""))
level = entry.get("level", "")
message = entry.get("message", "")
if ts and level:
return f"[{ts}] [{level}] {message}"
elif ts:
return f"[{ts}] {message}"
return message
def level_fg(level: str) -> str | None:
"""Return click color for a log level."""
level_upper = level.upper() if level else ""
if level_upper in {"ERROR", "CRITICAL"}:
return "red"
if level_upper == "WARNING":
return "yellow"
return None
+1 -57
View File
@@ -70,25 +70,7 @@ class HostBackendClient:
f"Failed to decode response from {path}: {err}"
) from None
def create_deployment(
self,
name: str,
deployment_type: str,
source: str,
config_path: str | None = None,
secrets: list[dict[str, str]] | None = None,
) -> dict[str, Any]:
"""Create a deployment."""
payload: dict[str, Any] = {
"name": name,
"source": source,
"source_config": {"deployment_type": deployment_type},
"source_revision_config": {},
}
if source == "internal_source" and config_path:
payload["source_revision_config"]["langgraph_config_path"] = config_path
if secrets is not None:
payload["secrets"] = secrets
def create_deployment(self, payload: dict[str, Any]) -> dict[str, Any]:
return self._request("POST", "/v2/deployments", payload)
def list_deployments(self, name_contains: str = "") -> dict[str, Any]:
@@ -110,13 +92,6 @@ class HostBackendClient:
f"/v2/deployments/{deployment_id}/push-token",
)
def request_upload_url(self, deployment_id: str) -> dict[str, Any]:
"""Get a signed GCS URL for uploading the source tarball."""
return self._request(
"POST",
f"/v2/deployments/{deployment_id}/upload-url",
)
def update_deployment(
self,
deployment_id: str,
@@ -124,7 +99,6 @@ class HostBackendClient:
secrets: list[dict[str, str]] | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"revision_source": "internal_docker",
"source_revision_config": {"image_uri": image_uri},
}
if secrets is not None:
@@ -135,36 +109,6 @@ class HostBackendClient:
payload,
)
def update_deployment_internal_source(
self,
deployment_id: str,
source_tarball_path: str,
config_path: str,
secrets: list[dict[str, str]] | None = None,
install_command: str | None = None,
build_command: str | None = None,
) -> dict[str, Any]:
"""Trigger a remote build revision with the uploaded tarball."""
payload: dict[str, Any] = {
"revision_source": "internal_source",
"source_revision_config": {
"source_tarball_path": source_tarball_path,
"langgraph_config_path": config_path,
},
}
source_config: dict[str, Any] = {}
if install_command is not None:
source_config["install_command"] = install_command
if build_command is not None:
source_config["build_command"] = build_command
if source_config:
payload["source_config"] = source_config
if secrets is not None:
payload["secrets"] = secrets
return self._request("PATCH", f"/v2/deployments/{deployment_id}", payload)
def list_revisions(self, deployment_id: str, limit: int = 1) -> dict[str, Any]:
return self._request(
"GET",
-9
View File
@@ -18,9 +18,6 @@ class Progress:
self._show_elapsed = elapsed
# use this to make sure we don't kill thread when we set msg to ""
self._stop = threading.Event()
# signalled when the spinner has no text on screen
self._line_clear = threading.Event()
self._line_clear.set()
self.spinner_generator = self.spinning_cursor()
def spinner_iteration(self):
@@ -46,16 +43,13 @@ class Progress:
start = time.monotonic()
while not self._stop.is_set():
if not self.message:
self._line_clear.set()
time.sleep(self.delay)
continue
if self._show_elapsed:
self.message = self._format_elapsed(time.monotonic() - start)
message = self.message
if not message:
self._line_clear.set()
continue
self._line_clear.clear()
sys.stdout.write(next(self.spinner_generator) + " " + message)
sys.stdout.flush()
time.sleep(self.delay)
@@ -66,7 +60,6 @@ class Progress:
+ "\b" * (len(message) + 2)
)
sys.stdout.flush()
self._line_clear.set()
def __enter__(self) -> Callable[[str], None]:
if sys.stdout.isatty():
@@ -76,8 +69,6 @@ class Progress:
def set_message(message):
self.message = message
self._base_message = message or self._base_message
if not message:
self._line_clear.wait(timeout=0.5)
return set_message
else:
+65 -1
View File
@@ -1,4 +1,4 @@
"""General-purpose utilities shared across the LangGraph CLI."""
from collections.abc import Sequence
import click
@@ -25,3 +25,67 @@ def warn_non_wolfi_distro(config_json: dict) -> None:
fg="yellow",
)
click.secho("") # Empty line for better readability
def _extract_deployment_url(deployment: dict[str, object]) -> str:
source_config = deployment.get("source_config")
if isinstance(source_config, dict):
custom_url = source_config.get("custom_url")
if isinstance(custom_url, str) and custom_url:
return custom_url
return "-"
def format_deployments_table(deployments: Sequence[dict[str, object]]) -> str:
headers = ("Deployment ID", "Deployment Name", "Deployment URL")
rows = [
(
str(deployment.get("id", "-") or "-"),
str(deployment.get("name", "-") or "-"),
_extract_deployment_url(deployment),
)
for deployment in deployments
]
widths = [
max(len(headers[index]), *(len(row[index]) for row in rows))
for index in range(len(headers))
]
def format_row(row: Sequence[str]) -> str:
return " ".join(value.ljust(widths[index]) for index, value in enumerate(row))
lines = [format_row(headers), format_row(tuple("-" * width for width in widths))]
lines.extend(format_row(row) for row in rows)
return "\n".join(lines)
def format_revisions_table(revisions: Sequence[dict[str, object]]) -> str:
headers = ("Revision ID", "Status", "Created At")
latest_deployed_seen = False
rows = []
for revision in revisions:
status = str(revision.get("status", "-") or "-")
if status == "DEPLOYED":
if latest_deployed_seen:
status = "REPLACED"
else:
latest_deployed_seen = True
rows.append(
(
str(revision.get("id", "-") or "-"),
status,
str(revision.get("created_at", "-") or "-"),
)
)
widths = [
max(len(headers[index]), *(len(row[index]) for row in rows))
for index in range(len(headers))
]
def format_row(row: Sequence[str]) -> str:
return " ".join(value.ljust(widths[index]) for index, value in enumerate(row))
lines = [format_row(headers), format_row(tuple("-" * width for width in widths))]
lines.extend(format_row(row) for row in rows)
return "\n".join(lines)
-1
View File
@@ -15,7 +15,6 @@ dependencies = [
"click>=8.1.7",
"httpx>=0.24.0",
"langgraph-sdk>=0.1.0 ; python_version >= '3.11'",
"pathspec>=0.11.0",
"python-dotenv>=0.8.0",
]
[tool.hatch.version]
+9 -9
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from click.testing import CliRunner
import langgraph_cli.deploy as deploy_module
import langgraph_cli.cli as cli_module
from langgraph_cli.cli import cli, prepare_args_and_stdin
from langgraph_cli.config import Config, _get_pip_cleanup_lines, validate_config
from langgraph_cli.docker import DEFAULT_POSTGRES_URI, DockerCapabilities, Version
@@ -346,7 +346,7 @@ def test_deploy_list_command(monkeypatch) -> None:
]
}
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -386,7 +386,7 @@ def test_deploy_list_command_no_results(monkeypatch) -> None:
def list_deployments(self, name_contains: str = ""):
return {"resources": []}
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -432,7 +432,7 @@ def test_deploy_revisions_list_command(monkeypatch) -> None:
]
}
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -473,7 +473,7 @@ def test_deploy_revisions_list_command_no_results(monkeypatch) -> None:
def list_revisions(self, deployment_id: str, limit: int = 1):
return {"resources": []}
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -506,7 +506,7 @@ def test_deploy_revisions_list_command_with_explicit_limit(monkeypatch) -> None:
captured["limit"] = str(limit)
return {"resources": []}
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -552,7 +552,7 @@ def test_deploy_delete_command(monkeypatch) -> None:
captured["deployment_id"] = deployment_id
return None
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -594,7 +594,7 @@ def test_deploy_delete_command_cancelled(monkeypatch) -> None:
deleted = True
return None
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
@@ -629,7 +629,7 @@ def test_deploy_delete_command_force(monkeypatch) -> None:
captured["deployment_id"] = deployment_id
return None
monkeypatch.setattr(deploy_module, "HostBackendClient", FakeClient)
monkeypatch.setattr(cli_module, "HostBackendClient", FakeClient)
result = runner.invoke(
cli,
-299
View File
@@ -1,299 +0,0 @@
import os
import tarfile
from unittest.mock import patch
import click
import pytest
from langgraph_cli.archive import (
_add_directory,
_build_ignore_spec,
_tar_filter,
create_archive,
)
# ---------------------------------------------------------------------------
# _tar_filter
# ---------------------------------------------------------------------------
class TestTarFilter:
def _make_info(self, name: str, *, type_: int = tarfile.REGTYPE) -> tarfile.TarInfo:
info = tarfile.TarInfo(name=name)
info.type = type_
return info
def test_regular_file_passes(self):
info = self._make_info("src/main.py")
assert _tar_filter(info) is info
def test_symlink_rejected(self):
info = self._make_info("link", type_=tarfile.SYMTYPE)
assert _tar_filter(info) is None
def test_hardlink_rejected(self):
info = self._make_info("link", type_=tarfile.LNKTYPE)
assert _tar_filter(info) is None
def test_path_traversal_rejected(self):
info = self._make_info("../../etc/passwd")
assert _tar_filter(info) is None
def test_path_traversal_in_middle_rejected(self):
info = self._make_info("src/../../../etc/passwd")
assert _tar_filter(info) is None
def test_dotdot_as_name_component_rejected(self):
info = self._make_info("foo/../bar")
assert _tar_filter(info) is None
def test_dotdot_in_filename_allowed(self):
"""A file literally named 'foo..bar' is not traversal."""
info = self._make_info("foo..bar")
assert _tar_filter(info) is info
def test_directory_passes(self):
info = self._make_info("src/", type_=tarfile.DIRTYPE)
assert _tar_filter(info) is info
# ---------------------------------------------------------------------------
# _build_ignore_spec
# ---------------------------------------------------------------------------
class TestBuildIgnoreSpec:
def test_always_excludes_builtins(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("__pycache__/")
assert spec.match_file(".git/")
assert spec.match_file(".venv/")
assert spec.match_file("venv/")
assert spec.match_file("node_modules/")
assert spec.match_file(".tox/")
assert spec.match_file(".mypy_cache/")
def test_regular_file_not_excluded(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert not spec.match_file("main.py")
assert not spec.match_file("src/app.py")
def test_merges_dockerignore(self, tmp_path):
(tmp_path / ".dockerignore").write_text("*.log\nbuild/\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("server.log")
assert spec.match_file("build/")
# builtins still present
assert spec.match_file("__pycache__/")
def test_merges_gitignore(self, tmp_path):
(tmp_path / ".gitignore").write_text("*.pyc\ndist/\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("module.pyc")
assert spec.match_file("dist/")
def test_merges_both_ignore_files(self, tmp_path):
(tmp_path / ".dockerignore").write_text("*.log\n")
(tmp_path / ".gitignore").write_text("*.pyc\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("app.log")
assert spec.match_file("mod.pyc")
def test_no_ignore_files_only_builtins(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("__pycache__/")
assert not spec.match_file("README.md")
# ---------------------------------------------------------------------------
# _add_directory
# ---------------------------------------------------------------------------
class TestAddDirectory:
def _create_project(self, tmp_path):
"""Create a small project structure for testing."""
(tmp_path / "main.py").write_text("print('hello')")
(tmp_path / "lib").mkdir()
(tmp_path / "lib" / "util.py").write_text("x = 1")
(tmp_path / "__pycache__").mkdir()
(tmp_path / "__pycache__" / "main.cpython-311.pyc").write_bytes(b"\x00")
return tmp_path
def test_adds_files_without_prefix(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "main.py" in names
assert "lib/util.py" in names
def test_excludes_pycache(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert not any("__pycache__" in n for n in names)
def test_adds_files_with_prefix(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix="myapp", ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "myapp/main.py" in names
assert "myapp/lib/util.py" in names
def test_respects_custom_ignore_patterns(self, tmp_path):
project = self._create_project(tmp_path)
(project / ".gitignore").write_text("lib/\n")
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "main.py" in names
assert "lib/util.py" not in names
# ---------------------------------------------------------------------------
# create_archive (integration)
# ---------------------------------------------------------------------------
class TestCreateArchive:
def _make_project(self, tmp_path):
"""Set up a minimal project directory with a config file."""
project = tmp_path / "myproject"
project.mkdir()
config_file = project / "langgraph.json"
config_file.write_text('{"dependencies": ["."]}')
(project / "app.py").write_text("print('hello')")
(project / "__pycache__").mkdir()
(project / "__pycache__" / "app.cpython-311.pyc").write_bytes(b"\x00")
return config_file
@patch("langgraph_cli.archive._assemble_local_deps")
def test_yields_archive_with_config(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, file_size, config_rel):
assert os.path.isfile(archive_path)
assert archive_path.endswith(".tar.gz")
assert file_size > 0
assert config_rel == "langgraph.json"
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert "langgraph.json" in names
assert "app.py" in names
@patch("langgraph_cli.archive._assemble_local_deps")
def test_excludes_pycache(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, _size, _rel):
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert not any("__pycache__" in n for n in names)
@patch("langgraph_cli.archive._assemble_local_deps")
def test_cleans_up_tmp_dir_on_normal_exit(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, _size, _rel):
tmp_dir = os.path.dirname(archive_path)
assert os.path.isdir(tmp_dir)
assert not os.path.exists(tmp_dir)
@patch("langgraph_cli.archive._assemble_local_deps")
def test_cleans_up_tmp_dir_on_exception(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with pytest.raises(RuntimeError, match="boom"):
with create_archive(config_file, {}) as (archive_path, _size, _rel):
tmp_dir = os.path.dirname(archive_path)
raise RuntimeError("boom")
assert not os.path.exists(tmp_dir)
@patch("langgraph_cli.archive._assemble_local_deps")
@patch("langgraph_cli.archive._MAX_SIZE", 10)
def test_raises_on_oversized_archive(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with pytest.raises(click.ClickException, match="exceeds the 200 MB limit"):
with create_archive(config_file, {}):
pass
@patch("langgraph_cli.archive._assemble_local_deps")
def test_handles_extra_contexts(self, mock_deps, tmp_path):
"""Monorepo case: project + sibling dependency directory."""
from langgraph_cli.config import LocalDeps
project = tmp_path / "myproject"
project.mkdir()
config_file = project / "langgraph.json"
config_file.write_text('{"dependencies": [".", "../shared"]}')
(project / "app.py").write_text("print('hello')")
shared = tmp_path / "shared"
shared.mkdir()
(shared / "lib.py").write_text("y = 2")
mock_deps.return_value = LocalDeps(
pip_reqs=[],
real_pkgs={},
faux_pkgs={},
additional_contexts=[shared],
)
with create_archive(config_file, {}) as (archive_path, _size, config_rel):
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert "myproject/app.py" in names
assert "shared/lib.py" in names
assert config_rel == "myproject/langgraph.json"
@@ -6,14 +6,12 @@ import click
import httpx
import pytest
from langgraph_cli.deploy import (
from langgraph_cli.cli import (
_call_host_backend_with_optional_tenant,
_docker_config_for_token,
_env_without_deployment_name,
_normalize_image_name,
_normalize_image_tag,
_parse_env_from_config,
_resolve_env_path,
normalize_image_name,
normalize_image_tag,
)
from langgraph_cli.host_backend import HostBackendClient, HostBackendError
@@ -42,47 +40,47 @@ class TestDockerConfigForToken:
class TestNormalizeImageName:
def test_simple_name(self):
assert normalize_image_name("myapp") == "myapp"
assert _normalize_image_name("myapp") == "myapp"
def test_uppercase_lowered(self):
assert normalize_image_name("MyApp") == "myapp"
assert _normalize_image_name("MyApp") == "myapp"
def test_special_chars_replaced(self):
assert normalize_image_name("my app!@#v2") == "my-app-v2"
assert _normalize_image_name("my app!@#v2") == "my-app-v2"
def test_dots_and_hyphens_kept(self):
assert normalize_image_name("my-app.v2") == "my-app.v2"
assert _normalize_image_name("my-app.v2") == "my-app.v2"
def test_leading_trailing_stripped(self):
assert normalize_image_name("--my-app..") == "my-app"
assert _normalize_image_name("--my-app..") == "my-app"
def test_empty_string_returns_app(self):
assert normalize_image_name("") == "app"
assert _normalize_image_name("") == "app"
def test_none_returns_app(self):
assert normalize_image_name(None) == "app"
assert _normalize_image_name(None) == "app"
def test_all_invalid_chars_returns_app(self):
assert normalize_image_name("!!!") == "app"
assert _normalize_image_name("!!!") == "app"
class TestNormalizeImageTag:
def test_valid_tag(self):
assert normalize_image_tag("v1.2.3") == "v1.2.3"
assert _normalize_image_tag("v1.2.3") == "v1.2.3"
def test_empty_defaults_to_latest(self):
assert normalize_image_tag("") == "latest"
assert _normalize_image_tag("") == "latest"
def test_alphanumeric_and_special(self):
assert normalize_image_tag("my_tag-1.0") == "my_tag-1.0"
assert _normalize_image_tag("my_tag-1.0") == "my_tag-1.0"
def test_invalid_chars_raises(self):
with pytest.raises(click.UsageError, match="Image tag may only contain"):
normalize_image_tag("v1.0:bad")
_normalize_image_tag("v1.0:bad")
def test_spaces_raises(self):
with pytest.raises(click.UsageError, match="Image tag may only contain"):
normalize_image_tag("has space")
_normalize_image_tag("has space")
class TestParseEnvFromConfig:
@@ -139,51 +137,6 @@ class TestParseEnvFromConfig:
assert result["EMPTY"] == ""
class TestResolveEnvPath:
def test_inline_env_dict_returns_none(self, tmp_path):
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({"env": {"FOO": "bar"}}, config_path) is None
def test_relative_env_path_resolves(self, tmp_path):
env_file = tmp_path / "custom.env"
env_file.write_text("FOO=bar\n")
config_path = tmp_path / "langgraph.json"
config_path.touch()
resolved = _resolve_env_path({"env": "custom.env"}, config_path)
assert resolved == env_file.resolve()
def test_missing_env_file_returns_none(self, tmp_path):
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({"env": "missing.env"}, config_path) is None
def test_default_env_is_cwd_dotenv(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({}, config_path) == tmp_path / ".env"
class TestEnvWithoutDeploymentName:
def test_removes_deployment_name_only(self):
env = {
"LANGSMITH_DEPLOYMENT_NAME": "my-deploy",
"KEEP_ME": "value",
}
cleaned = _env_without_deployment_name(env)
assert "LANGSMITH_DEPLOYMENT_NAME" not in cleaned
assert cleaned["KEEP_ME"] == "value"
# Original dict should be unchanged.
assert env["LANGSMITH_DEPLOYMENT_NAME"] == "my-deploy"
def test_noop_when_deployment_name_absent(self):
env = {"FOO": "bar"}
assert _env_without_deployment_name(env) == {"FOO": "bar"}
class TestCallHostBackendWithOptionalTenant:
def _make_client(self, handler):
c = HostBackendClient("https://api.example.com", "test-key")
@@ -121,9 +121,7 @@ def test_request_transport_error_raises():
def test_create_deployment(client):
result = client.create_deployment(
name="my-deploy", deployment_type="dev", source="internal_docker"
)
result = client.create_deployment({"name": "my-deploy"})
assert result == {"ok": True}
@@ -1,4 +1,4 @@
from langgraph_cli.deploy import format_log_entry, format_timestamp, level_fg
from langgraph_cli.helpers import format_log_entry, format_timestamp, level_fg
class TestFormatTimestamp:
+3 -2
View File
@@ -1,11 +1,12 @@
from unittest.mock import patch
from langgraph_cli.deploy import (
from langgraph_cli.util import (
_extract_deployment_url,
clean_empty_lines,
format_deployments_table,
format_revisions_table,
warn_non_wolfi_distro,
)
from langgraph_cli.util import clean_empty_lines, warn_non_wolfi_distro
def test_clean_empty_lines():
+1 -3
View File
@@ -1,5 +1,5 @@
version = 1
revision = 4
revision = 3
requires-python = ">=3.10"
resolution-markers = [
"python_full_version >= '3.11'",
@@ -985,7 +985,6 @@ dependencies = [
{ name = "click" },
{ name = "httpx" },
{ name = "langgraph-sdk", marker = "python_full_version >= '3.11'" },
{ name = "pathspec" },
{ name = "python-dotenv" },
]
@@ -1027,7 +1026,6 @@ requires-dist = [
{ name = "langgraph-api", marker = "python_full_version >= '3.11' and extra == 'inmem'", specifier = ">=0.5.35,<0.8.0" },
{ name = "langgraph-runtime-inmem", marker = "python_full_version >= '3.11' and extra == 'inmem'", specifier = ">=0.7" },
{ name = "langgraph-sdk", marker = "python_full_version >= '3.11'", specifier = ">=0.1.0" },
{ name = "pathspec", specifier = ">=0.11.0" },
{ name = "python-dotenv", specifier = ">=0.8.0" },
]
provides-extras = ["inmem"]
+1 -19
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from collections import ChainMap
from collections.abc import Mapping, Sequence
from collections.abc import Sequence
from os import getenv
from typing import Any, cast
@@ -308,22 +308,4 @@ def ensure_config(*configs: RunnableConfig | None) -> RunnableConfig:
for k, v in config.items():
if _is_not_empty(v) and k not in CONFIG_KEYS:
empty[CONF][k] = v
_empty_metadata = empty["metadata"]
for key, value in empty[CONF].items():
if _exclude_as_metadata(key, value, _empty_metadata):
continue
_empty_metadata[key] = value
return empty
_OMIT = ("key", "token", "secret", "password", "auth")
def _exclude_as_metadata(key: str, value: Any, metadata: Mapping[str, Any]) -> bool:
key_lower = key.casefold()
return (
key.startswith("__")
or not isinstance(value, (str, int, float, bool))
or key in metadata
or any(substr in key_lower for substr in _OMIT)
)
+3 -28
View File
@@ -45,7 +45,6 @@ from langgraph._internal._constants import (
CONFIG_KEY_SCRATCHPAD,
CONFIG_KEY_SEND,
CONFIG_KEY_TASK_ID,
CONFIG_KEY_THREAD_ID,
ERROR,
INTERRUPT,
NO_WRITES,
@@ -71,7 +70,7 @@ from langgraph.pregel._call import get_runnable_for_task, identifier
from langgraph.pregel._io import read_channels
from langgraph.pregel._log import logger
from langgraph.pregel._read import INPUT_CACHE_KEY_TYPE, PregelNode
from langgraph.runtime import DEFAULT_RUNTIME, ExecutionInfo, Runtime
from langgraph.runtime import DEFAULT_RUNTIME, Runtime
from langgraph.types import (
All,
CacheKey,
@@ -669,13 +668,6 @@ def prepare_single_task(
runtime = runtime.override(
previous=checkpoint["channel_values"].get(PREVIOUS, None),
store=store,
execution_info=ExecutionInfo(
checkpoint_id=checkpoint["id"],
checkpoint_ns=task_checkpoint_ns,
task_id=task_id,
thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
run_id=str(rid) if (rid := config.get("run_id")) else None,
),
)
additional_config = {
"metadata": metadata,
@@ -821,16 +813,7 @@ def prepare_push_task_functional(
stop,
)
runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
runtime = runtime.override(
store=store,
execution_info=ExecutionInfo(
checkpoint_id=checkpoint["id"],
checkpoint_ns=task_checkpoint_ns,
task_id=task_id,
thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
run_id=str(rid) if (rid := config.get("run_id")) else None,
),
)
runtime = runtime.override(store=store)
return PregelExecutableTask(
name,
call.input,
@@ -983,15 +966,7 @@ def prepare_push_task_send(
)
runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
runtime = runtime.override(
store=store,
previous=checkpoint["channel_values"].get(PREVIOUS, None),
execution_info=ExecutionInfo(
checkpoint_id=checkpoint["id"],
checkpoint_ns=task_checkpoint_ns,
task_id=task_id,
thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
run_id=str(rid) if (rid := config.get("run_id")) else None,
),
store=store, previous=checkpoint["channel_values"].get(PREVIOUS, None)
)
additional_config: RunnableConfig = {
"metadata": metadata,
+5 -50
View File
@@ -136,12 +136,7 @@ from langgraph.pregel._validate import validate_graph, validate_keys
from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
from langgraph.pregel.debug import get_bolded_text, get_colored_text, tasks_w_writes
from langgraph.pregel.protocol import PregelProtocol, StreamChunk, StreamProtocol
from langgraph.runtime import (
DEFAULT_RUNTIME,
BaseUser,
Runtime,
ServerInfo,
)
from langgraph.runtime import DEFAULT_RUNTIME, ExecutionInfo, Runtime
from langgraph.types import (
All,
CachePolicy,
@@ -2650,18 +2645,14 @@ class Pregel(
if durability is not None:
config[CONF][CONFIG_KEY_DURABILITY] = durability_
# build server_info from metadata + parent runtime
parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
server_info = _build_server_info(config, parent_runtime)
runtime = Runtime(
context=_coerce_context(self.context_schema, context),
store=store,
stream_writer=stream_writer,
previous=None,
execution_info=None,
server_info=server_info,
execution_info=ExecutionInfo(),
)
parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
runtime = parent_runtime.merge(runtime)
config[CONF][CONFIG_KEY_RUNTIME] = runtime
@@ -3023,18 +3014,14 @@ class Pregel(
if durability is not None:
config[CONF][CONFIG_KEY_DURABILITY] = durability_
# build server_info from metadata + parent runtime
parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
server_info = _build_server_info(config, parent_runtime)
runtime = Runtime(
context=_coerce_context(self.context_schema, context),
store=store,
stream_writer=stream_writer,
previous=None,
execution_info=None,
server_info=server_info,
execution_info=ExecutionInfo(),
)
parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
runtime = parent_runtime.merge(runtime)
config[CONF][CONFIG_KEY_RUNTIME] = runtime
@@ -3656,38 +3643,6 @@ def _coerce_checkpoint_values(payload: Any, mapper: Callable[[Any], Any]) -> Non
payload["values"] = mapper(payload["values"])
def _build_server_info(
config: RunnableConfig, parent_runtime: Runtime[Any]
) -> ServerInfo | None:
"""Build ServerInfo from config metadata and configurable.
The server puts assistant_id/graph_id in config metadata and the
authenticated user dict in configurable["langgraph_auth_user"].
"""
metadata = config.get("metadata") or {}
configurable = config.get(CONF) or {}
assistant_id = metadata.get("assistant_id")
graph_id = metadata.get("graph_id")
# Read authenticated user from configurable (set by LangGraph Server).
# We prefer isinstance(BaseUser) but fall back to hasattr("identity")
# because the server's ProxyUser provides `permissions` via __getattr__,
# which Python's runtime_checkable Protocol check doesn't see.
auth_user_data = configurable.get("langgraph_auth_user")
user: BaseUser | None = None
if auth_user_data is not None:
if isinstance(auth_user_data, BaseUser) or hasattr(auth_user_data, "identity"):
user = cast(BaseUser, auth_user_data)
if assistant_id is not None or graph_id is not None or user is not None:
return ServerInfo(
assistant_id=str(assistant_id) if assistant_id else "",
graph_id=str(graph_id) if graph_id else "",
user=user,
)
return None
def _coerce_context(
context_schema: type[ContextT] | None, context: Any
) -> ContextT | None:
+8 -64
View File
@@ -1,10 +1,9 @@
from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import Any, Generic, cast
from typing import Any, Generic, NamedTuple, cast
from langgraph.store.base import BaseStore
from langgraph_sdk.auth.types import BaseUser
from typing_extensions import TypedDict, Unpack
from langgraph._internal._constants import CONF, CONFIG_KEY_RUNTIME
@@ -12,38 +11,12 @@ from langgraph.config import get_config
from langgraph.types import _DC_KWARGS, StreamWriter
from langgraph.typing import ContextT
__all__ = (
"BaseUser",
"ExecutionInfo",
"Runtime",
"ServerInfo",
"get_runtime",
)
__all__ = ("ExecutionInfo", "Runtime", "get_runtime")
@dataclass(frozen=True, slots=True)
class ExecutionInfo:
class ExecutionInfo(NamedTuple):
"""Read-only execution info/metadata for the execution of current thread/run/node."""
checkpoint_id: str
"""The checkpoint ID for the current execution."""
checkpoint_ns: str
"""The checkpoint namespace for the current execution."""
task_id: str
"""The task ID for the current execution."""
thread_id: str | None = None
"""The thread ID for the current execution.
None when running without a checkpointer (i.e., no persistence)."""
run_id: str | None = None
"""The run ID for the current execution.
None when `run_id` is not provided in the RunnableConfig."""
node_attempt: int = 1
"""Current node execution attempt number (1-indexed)."""
@@ -52,26 +25,7 @@ class ExecutionInfo:
def patch(self, **overrides: Any) -> ExecutionInfo:
"""Return a new execution info object with selected fields replaced."""
return replace(self, **overrides)
@dataclass(frozen=True, slots=True)
class ServerInfo:
"""Metadata injected by LangGraph Server. None when running open-source LangGraph without LangSmith deployments."""
assistant_id: str
"""The assistant ID for the current execution."""
graph_id: str
"""The graph ID for the current execution."""
user: BaseUser | None = None
"""The authenticated user, if any.
This implements the `BaseUser` protocol from `langgraph_sdk.auth.types`,
which supports both attribute access (e.g. `user.identity`) and dict-like
access (e.g. `user["identity"]`).
"""
return self._replace(**overrides)
def _no_op_stream_writer(_: Any) -> None: ...
@@ -83,7 +37,6 @@ class _RuntimeOverrides(TypedDict, Generic[ContextT], total=False):
stream_writer: StreamWriter
previous: Any
execution_info: ExecutionInfo
server_info: ServerInfo | None
@dataclass(**_DC_KWARGS)
@@ -177,13 +130,8 @@ class Runtime(Generic[ContextT]):
Only available with the functional API when a checkpointer is provided.
"""
execution_info: ExecutionInfo | None = field(default=None)
"""Read-only execution information/metadata for the current node run.
None before task preparation populates it."""
server_info: ServerInfo | None = field(default=None)
"""Metadata injected by LangGraph Server. None when running open-source LangGraph without LangSmith deployments."""
execution_info: ExecutionInfo = field(default_factory=ExecutionInfo)
"""Read-only execution information/metadata for the current node run."""
def merge(self, other: Runtime[ContextT]) -> Runtime[ContextT]:
"""Merge two runtimes together.
@@ -197,8 +145,7 @@ class Runtime(Generic[ContextT]):
if other.stream_writer is not _no_op_stream_writer
else self.stream_writer,
previous=self.previous if other.previous is None else other.previous,
execution_info=other.execution_info or self.execution_info,
server_info=other.server_info or self.server_info,
execution_info=other.execution_info,
)
def override(
@@ -209,9 +156,6 @@ class Runtime(Generic[ContextT]):
def patch_execution_info(self, **overrides: Any) -> Runtime[ContextT]:
"""Return a new runtime with selected execution_info fields replaced."""
if self.execution_info is None:
msg = "Cannot patch execution_info before it has been set"
raise RuntimeError(msg)
return replace(
self,
execution_info=self.execution_info.patch(**overrides),
@@ -223,7 +167,7 @@ DEFAULT_RUNTIME = Runtime(
store=None,
stream_writer=_no_op_stream_writer,
previous=None,
execution_info=None,
execution_info=ExecutionInfo(),
)
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph"
version = "1.1.5"
version = "1.1.4"
description = "Building stateful, multi-actor applications with LLMs"
authors = []
requires-python = ">=3.10"
@@ -27,7 +27,7 @@ dependencies = [
"langchain-core>=0.1",
"langgraph-checkpoint>=2.1.0,<5.0.0",
"langgraph-sdk>=0.3.0,<0.4.0",
"langgraph-prebuilt>=1.0.9,<1.1.0",
"langgraph-prebuilt>=1.0.8,<1.1.0",
"xxhash>=3.5.0",
"pydantic>=2.7.4",
]
-63
View File
@@ -1,7 +1,6 @@
from unittest.mock import Mock, patch
import pytest
from langgraph.checkpoint.memory import MemorySaver
from typing_extensions import TypedDict
from langgraph.graph import START, StateGraph
@@ -394,65 +393,3 @@ def test_graph_with_max_attempts_exceeded():
graph.invoke({"foo": ""})
mock_sleep.assert_called_with(0.01)
def test_execution_info_identity_fields_populated_on_retry():
"""Test that thread_id, task_id, run_id, etc. are populated in execution_info during retries."""
class State(TypedDict):
foo: str
attempt_count = 0
captured_infos: list[dict] = []
def failing_node(state: State, runtime: Runtime):
nonlocal attempt_count
attempt_count += 1
info = runtime.execution_info
captured_infos.append(
{
"thread_id": info.thread_id,
"run_id": info.run_id,
"node_attempt": info.node_attempt,
"node_first_attempt_time": info.node_first_attempt_time,
"checkpoint_ns": info.checkpoint_ns,
}
)
if attempt_count < 2:
raise ValueError("Intentional failure")
return {"foo": "success"}
retry_policy = RetryPolicy(
max_attempts=3,
initial_interval=0.01,
jitter=False,
retry_on=ValueError,
)
graph = (
StateGraph(State)
.add_node("failing_node", failing_node, retry_policy=retry_policy)
.add_edge(START, "failing_node")
.compile(checkpointer=MemorySaver())
)
with patch("time.sleep"):
result = graph.invoke(
{"foo": ""},
config={"configurable": {"thread_id": "retry-thread"}},
)
assert result["foo"] == "success"
assert len(captured_infos) == 2
# Both attempts should have the same thread_id and first_attempt_time
assert captured_infos[0]["thread_id"] == "retry-thread"
assert captured_infos[1]["thread_id"] == "retry-thread"
assert (
captured_infos[0]["node_first_attempt_time"]
== captured_infos[1]["node_first_attempt_time"]
)
# node_attempt should increment
assert captured_infos[0]["node_attempt"] == 1
assert captured_infos[1]["node_attempt"] == 2
+1 -258
View File
@@ -2,12 +2,11 @@ from dataclasses import dataclass
from typing import Any
import pytest
from langgraph.checkpoint.memory import MemorySaver
from pydantic import BaseModel, ValidationError
from typing_extensions import TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import ExecutionInfo, Runtime, ServerInfo, get_runtime
from langgraph.runtime import Runtime, get_runtime
def test_injected_runtime() -> None:
@@ -390,259 +389,3 @@ def test_context_coercion_pydantic_validation_errors() -> None:
compiled.invoke(
{"message": "test"}, context={"api_key": "sk_test", "timeout": "not_an_int"}
)
# --- ExecutionInfo unit tests ---
def test_execution_info_defaults_and_patch() -> None:
info = ExecutionInfo(checkpoint_id="c1", checkpoint_ns="ns1", task_id="t1")
assert info.checkpoint_id == "c1"
assert info.checkpoint_ns == "ns1"
assert info.task_id == "t1"
assert info.thread_id is None
assert info.run_id is None
assert info.node_attempt == 1
assert info.node_first_attempt_time is None
# patch returns new instance, original unchanged
patched = info.patch(thread_id="th1", node_attempt=3, task_id="tk1")
assert patched.thread_id == "th1"
assert patched.node_attempt == 3
assert patched.task_id == "tk1"
assert info.node_attempt == 1
assert info.task_id == "t1"
# frozen
with pytest.raises(AttributeError):
info.thread_id = "t2" # type: ignore[misc]
# --- ServerInfo / Runtime unit tests ---
def test_server_info_and_runtime_merge() -> None:
si = ServerInfo(assistant_id="asst-1", graph_id="graph-1")
assert si.assistant_id == "asst-1"
assert si.user is None
# frozen
with pytest.raises(AttributeError):
si.assistant_id = "asst-2" # type: ignore[misc]
# runtime default is None
assert Runtime().server_info is None
# merge preserves server_info from self when other has None
r1 = Runtime(server_info=si)
merged = r1.merge(Runtime())
assert merged.server_info is si
# merge takes server_info from other when present
si2 = ServerInfo(assistant_id="asst-2", graph_id="graph-2")
merged2 = r1.merge(Runtime(server_info=si2))
assert merged2.server_info is si2
# --- Integration tests ---
def _make_capture_graph(
capture: dict[str, Any],
*,
checkpointer: Any = None,
) -> Any:
"""Helper: build a simple graph that captures runtime info."""
class State(TypedDict):
message: str
def capture_node(state: State, runtime: Runtime) -> dict[str, Any]:
capture["execution_info"] = runtime.execution_info
capture["server_info"] = runtime.server_info
return {"message": "done"}
graph = StateGraph(state_schema=State)
graph.add_node("capture", capture_node)
graph.add_edge(START, "capture")
graph.add_edge("capture", END)
return graph.compile(checkpointer=checkpointer)
def test_execution_info_populated_in_graph() -> None:
"""execution_info fields are populated when running with a checkpointer."""
captured: dict[str, Any] = {}
compiled = _make_capture_graph(captured, checkpointer=MemorySaver())
compiled.invoke(
{"message": "hi"},
config={"configurable": {"thread_id": "t-123"}},
)
info = captured["execution_info"]
assert info.thread_id == "t-123"
assert info.task_id is not None
assert info.checkpoint_id is not None
assert info.checkpoint_ns is not None
assert info.node_attempt == 1
assert isinstance(info.node_first_attempt_time, float)
@pytest.mark.anyio
async def test_execution_info_populated_in_graph_async() -> None:
"""execution_info fields are populated in async execution."""
captured: dict[str, Any] = {}
compiled = _make_capture_graph(captured, checkpointer=MemorySaver())
await compiled.ainvoke(
{"message": "hi"},
config={"configurable": {"thread_id": "t-xyz"}},
)
info = captured["execution_info"]
assert info.thread_id == "t-xyz"
assert info.node_attempt == 1
assert isinstance(info.node_first_attempt_time, float)
def test_server_info_from_metadata() -> None:
"""server_info is built from assistant_id/graph_id in config metadata."""
captured: dict[str, Any] = {}
compiled = _make_capture_graph(captured)
compiled.invoke(
{"message": "hi"},
config={"metadata": {"assistant_id": "asst-abc", "graph_id": "my-graph"}},
)
si = captured["server_info"]
assert si is not None
assert si.assistant_id == "asst-abc"
assert si.graph_id == "my-graph"
assert si.user is None
def test_server_info_none_without_metadata() -> None:
"""server_info is None when no assistant_id/graph_id in metadata."""
captured: dict[str, Any] = {}
compiled = _make_capture_graph(captured)
compiled.invoke({"message": "hi"})
assert captured["server_info"] is None
def test_server_info_user_from_auth_user() -> None:
"""server_info.user is populated from configurable['langgraph_auth_user'].
Tests both a proper BaseUser protocol object and a starlette-style proxy
that provides `permissions` via __getattr__ (which the Protocol isinstance
check may not see).
"""
class _ProxyUser:
"""Mimics langgraph_api's ProxyUser: identity/display_name as properties,
permissions via __getattr__."""
def __init__(self, data: dict[str, Any]) -> None:
self._data = data
@property
def identity(self) -> str:
return self._data["identity"]
@property
def display_name(self) -> str:
return self._data.get("display_name", self.identity)
@property
def is_authenticated(self) -> bool:
return True
def __getattr__(self, name: str) -> Any:
return self._data[name]
def __getitem__(self, key: str) -> Any:
return self._data[key]
def __contains__(self, key: str) -> bool:
return key in self._data
def __iter__(self) -> Any:
return iter(self._data)
proxy = _ProxyUser(
{
"identity": "proxy-user",
"display_name": "Proxy User",
"is_authenticated": True,
"permissions": ["read"],
}
)
assert not isinstance(proxy, dict)
assert hasattr(proxy, "identity")
captured: dict[str, Any] = {}
compiled = _make_capture_graph(captured)
compiled.invoke(
{"message": "hi"},
config={
"configurable": {"langgraph_auth_user": proxy},
"metadata": {"assistant_id": "asst-proxy", "graph_id": "graph-proxy"},
},
)
si = captured["server_info"]
assert si is not None
assert si.assistant_id == "asst-proxy"
assert si.user is not None
assert si.user.identity == "proxy-user"
assert si.user["display_name"] == "Proxy User"
def test_execution_info_inherited_by_subgraph() -> None:
"""execution_info is correctly populated for subgraph nodes, including namespace."""
captured_main: dict[str, Any] = {}
captured_sub: dict[str, Any] = {}
class State(TypedDict, total=False):
message: str
def subgraph_node(state: State, runtime: Runtime) -> dict[str, str]:
captured_sub["execution_info"] = runtime.execution_info
return {"message": "from_sub"}
subgraph_builder = StateGraph(State)
subgraph_builder.add_node("sub_node", subgraph_node)
subgraph_builder.add_edge(START, "sub_node")
subgraph = subgraph_builder.compile()
def main_node(state: State, runtime: Runtime) -> dict[str, str]:
captured_main["execution_info"] = runtime.execution_info
return {"message": "from_main"}
builder = StateGraph(State)
builder.add_node("main_node", main_node)
builder.add_node("subgraph", subgraph)
builder.add_edge(START, "main_node")
builder.add_edge("main_node", "subgraph")
graph = builder.compile(checkpointer=MemorySaver())
graph.invoke(
{"message": "hi"},
config={"configurable": {"thread_id": "sub-thread"}},
)
main_info = captured_main["execution_info"]
sub_info = captured_sub["execution_info"]
# Both share the same thread_id
assert main_info.thread_id == "sub-thread"
assert sub_info.thread_id == "sub-thread"
# Both have node_attempt = 1
assert main_info.node_attempt == 1
assert sub_info.node_attempt == 1
# Main namespace is "main_node:<task_id>" (top-level, no separator)
assert main_info.checkpoint_ns.startswith("main_node:")
assert "|" not in main_info.checkpoint_ns
# Subgraph namespace is "subgraph:<task_id>|sub_node:<task_id>" (nested)
assert sub_info.checkpoint_ns.startswith("subgraph:")
assert "|sub_node:" in sub_info.checkpoint_ns
# task_id appears in its own namespace segment
assert main_info.task_id in main_info.checkpoint_ns
assert sub_info.task_id in sub_info.checkpoint_ns
+1 -1
View File
@@ -312,7 +312,7 @@ def test_configurable_metadata():
},
"metadata": {"nooverride": 18},
}
expected = {"includeme", "andme", "nooverride"}
expected = {"nooverride"}
merged = ensure_config(config)
metadata = merged["metadata"]
assert metadata.keys() == expected
+2 -4
View File
@@ -1367,7 +1367,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.1.5"
version = "1.1.4"
source = { editable = "." }
dependencies = [
{ name = "langchain-core" },
@@ -1691,7 +1691,6 @@ dependencies = [
{ name = "click", marker = "python_full_version < '3.14'" },
{ name = "httpx", marker = "python_full_version < '3.14'" },
{ name = "langgraph-sdk", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
{ name = "pathspec", marker = "python_full_version < '3.14'" },
{ name = "python-dotenv", marker = "python_full_version < '3.14'" },
]
@@ -1708,7 +1707,6 @@ requires-dist = [
{ name = "langgraph-api", marker = "python_full_version >= '3.11' and extra == 'inmem'", specifier = ">=0.5.35,<0.8.0" },
{ name = "langgraph-runtime-inmem", marker = "python_full_version >= '3.11' and extra == 'inmem'", specifier = ">=0.7" },
{ name = "langgraph-sdk", marker = "python_full_version >= '3.11'", specifier = ">=0.1.0" },
{ name = "pathspec", specifier = ">=0.11.0" },
{ name = "python-dotenv", specifier = ">=0.8.0" },
]
provides-extras = ["inmem"]
@@ -1740,7 +1738,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "1.0.9"
version = "1.0.8"
source = { editable = "../prebuilt" }
dependencies = [
{ name = "langchain-core" },
+1 -24
View File
@@ -79,13 +79,11 @@ from langchain_core.tools.base import (
TOOL_MESSAGE_BLOCK_TYPES,
ToolException,
_DirectlyInjectedToolArg,
_is_injected_arg_type,
get_all_basemodel_annotations,
)
from langgraph._internal._runnable import RunnableCallable
from langgraph.errors import GraphBubbleUp
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.runtime import ExecutionInfo, ServerInfo # noqa: TC002
from langgraph.store.base import BaseStore # noqa: TC002
from langgraph.types import Command, Send, StreamWriter
from pydantic import BaseModel, ValidationError
@@ -613,7 +611,6 @@ class _InjectedArgs:
state: dict[str, str | None]
store: str | None
runtime: str | None
all_injected_keys: set[str]
class ToolNode(RunnableCallable):
@@ -807,8 +804,6 @@ class ToolNode(RunnableCallable):
context=runtime.context,
store=runtime.store,
stream_writer=runtime.stream_writer,
execution_info=runtime.execution_info,
server_info=runtime.server_info,
)
tool_runtimes.append(tool_runtime)
@@ -841,8 +836,6 @@ class ToolNode(RunnableCallable):
context=runtime.context,
store=runtime.store,
stream_writer=runtime.stream_writer,
execution_info=runtime.execution_info,
server_info=runtime.server_info,
)
tool_runtimes.append(tool_runtime)
@@ -1384,15 +1377,7 @@ class ToolNode(RunnableCallable):
if injected.runtime:
injected_args[injected.runtime] = tool_runtime
# Strip any caller-supplied values for injected args, then add
# back only trusted values. This prevents an LLM from forging
# hidden InjectedToolArg fields via ToolCall.args.
stripped_args = {
k: v
for k, v in tool_call_copy["args"].items()
if k not in injected.all_injected_keys
}
tool_call_copy["args"] = {**stripped_args, **injected_args}
tool_call_copy["args"] = {**tool_call_copy["args"], **injected_args}
return tool_call_copy
def _validate_tool_command(
@@ -1613,8 +1598,6 @@ class ToolRuntime(_DirectlyInjectedToolArg, Generic[ContextT, StateT]):
stream_writer: StreamWriter
tool_call_id: str | None
store: BaseStore | None
execution_info: ExecutionInfo | None = None
server_info: ServerInfo | None = None
class InjectedState(InjectedToolArg):
@@ -1858,13 +1841,8 @@ def _get_all_injected_args(tool: BaseTool) -> _InjectedArgs:
state_args: dict[str, str | None] = {}
store_arg: str | None = None
runtime_arg: str | None = None
all_injected_keys: set[str] = set()
for name, type_ in all_annotations.items():
# Track all InjectedToolArg-annotated params (including custom subclasses)
if _is_injected_arg_type(type_):
all_injected_keys.add(name)
# Check for runtime (special case: parameter named "runtime")
if name == "runtime":
runtime_arg = name
@@ -1888,5 +1866,4 @@ def _get_all_injected_args(tool: BaseTool) -> _InjectedArgs:
state=state_args,
store=store_arg,
runtime=runtime_arg,
all_injected_keys=all_injected_keys,
)
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph-prebuilt"
version = "1.0.9"
version = "1.0.8"
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
authors = []
requires-python = ">=3.10"
+1 -195
View File
@@ -21,7 +21,7 @@ from langchain_core.messages import (
ToolMessage,
)
from langchain_core.runnables.config import RunnableConfig
from langchain_core.tools import BaseTool, InjectedToolArg, ToolException
from langchain_core.tools import BaseTool, ToolException
from langchain_core.tools import tool as dec_tool
from langgraph.config import get_stream_writer
from langgraph.errors import GraphBubbleUp, GraphInterrupt
@@ -59,16 +59,10 @@ def _create_mock_runtime(store: BaseStore | None = None) -> Mock:
which is injected by RunnableCallable from config["configurable"]["__pregel_runtime"].
When testing ToolNode directly (outside a graph), we need to provide this manually.
"""
from langgraph.runtime import ExecutionInfo
mock_runtime = Mock()
mock_runtime.store = store
mock_runtime.context = None
mock_runtime.stream_writer = lambda *args, **kwargs: None
mock_runtime.execution_info = ExecutionInfo(
checkpoint_id="test-cp", checkpoint_ns="", task_id="test-task"
)
mock_runtime.server_info = None
return mock_runtime
@@ -2014,191 +2008,3 @@ async def test_tool_node_inject_runtime_dynamic_tool_via_wrap_tool_call_async()
tool_message = result["messages"][-1]
assert tool_message.content == "dynamic: x=42, tool_call_id=call_dynamic_2"
assert tool_message.tool_call_id == "call_dynamic_2"
def test_tool_runtime_forwards_execution_info_and_server_info() -> None:
"""Test that execution_info and server_info are forwarded from Runtime to ToolRuntime."""
from langgraph.runtime import ExecutionInfo, ServerInfo
exec_info = ExecutionInfo(
thread_id="t-1",
checkpoint_id="cp-1",
checkpoint_ns="",
task_id="tk-1",
run_id="r-1",
)
server_info = ServerInfo(assistant_id="asst-1", graph_id="graph-1")
mock_runtime = Mock()
mock_runtime.store = None
mock_runtime.context = None
mock_runtime.stream_writer = lambda *args, **kwargs: None
mock_runtime.execution_info = exec_info
mock_runtime.server_info = server_info
captured: dict = {}
@dec_tool
def info_tool(x: int, runtime: ToolRuntime) -> str:
"""Tool that captures runtime info."""
captured["execution_info"] = runtime.execution_info
captured["server_info"] = runtime.server_info
return "ok"
node = ToolNode([info_tool])
tool_call = {
"name": "info_tool",
"args": {"x": 1},
"id": "call-1",
"type": "tool_call",
}
msg = AIMessage("", tool_calls=[tool_call])
config: RunnableConfig = {"configurable": {"__pregel_runtime": mock_runtime}}
node.invoke({"messages": [msg]}, config=config)
assert captured["execution_info"] is exec_info
assert captured["execution_info"].thread_id == "t-1"
assert captured["execution_info"].task_id == "tk-1"
assert captured["server_info"] is server_info
assert captured["server_info"].assistant_id == "asst-1"
async def test_tool_runtime_forwards_execution_info_and_server_info_async() -> None:
"""Test that execution_info and server_info are forwarded in async path."""
from langgraph.runtime import ExecutionInfo, ServerInfo
exec_info = ExecutionInfo(
thread_id="t-2",
checkpoint_id="cp-2",
checkpoint_ns="",
task_id="tk-2",
run_id="r-2",
)
server_info = ServerInfo(assistant_id="asst-2", graph_id="graph-2")
mock_runtime = Mock()
mock_runtime.store = None
mock_runtime.context = None
mock_runtime.stream_writer = lambda *args, **kwargs: None
mock_runtime.execution_info = exec_info
mock_runtime.server_info = server_info
captured: dict = {}
@dec_tool
async def info_tool_async(x: int, runtime: ToolRuntime) -> str:
"""Async tool that captures runtime info."""
captured["execution_info"] = runtime.execution_info
captured["server_info"] = runtime.server_info
return "ok"
node = ToolNode([info_tool_async])
tool_call = {
"name": "info_tool_async",
"args": {"x": 1},
"id": "call-2",
"type": "tool_call",
}
msg = AIMessage("", tool_calls=[tool_call])
config: RunnableConfig = {"configurable": {"__pregel_runtime": mock_runtime}}
await node.ainvoke({"messages": [msg]}, config=config)
assert captured["execution_info"] is exec_info
assert captured["execution_info"].thread_id == "t-2"
assert captured["server_info"] is server_info
assert captured["server_info"].graph_id == "graph-2"
# --- InjectedToolArg security tests ---
def test_tool_node_strips_plain_injected_tool_arg() -> None:
"""Plain InjectedToolArg values supplied by the LLM should be stripped."""
@dec_tool
def read_secret(
query: str,
auth: Annotated[dict, InjectedToolArg()],
) -> str:
"""Return secret data based on auth role."""
if auth.get("role") == "admin":
return "ADMIN_SECRET"
return "PUBLIC_DATA"
node = ToolNode([read_secret], handle_tool_errors=True)
# LLM tries to supply the hidden 'auth' field
tool_call = {
"name": "read_secret",
"args": {"query": "hello", "auth": {"role": "admin"}},
"id": "call-1",
"type": "tool_call",
}
msg = AIMessage("", tool_calls=[tool_call])
result = node.invoke({"messages": [msg]}, config=_create_config_with_runtime())
tool_message = result["messages"][-1]
# auth should have been stripped, so tool should fail (missing required arg)
assert "ADMIN_SECRET" not in tool_message.content
def test_tool_node_strips_custom_injected_tool_arg_subclass() -> None:
"""Custom InjectedToolArg subclasses should also be stripped."""
class InjectedAuth(InjectedToolArg):
pass
@dec_tool
def read_secret(
query: str,
auth: Annotated[dict, InjectedAuth()],
) -> str:
"""Return secret data based on auth role."""
if auth.get("role") == "admin":
return "ADMIN_SECRET"
return "PUBLIC_DATA"
node = ToolNode([read_secret], handle_tool_errors=True)
tool_call = {
"name": "read_secret",
"args": {"query": "hello", "auth": {"role": "admin"}},
"id": "call-1",
"type": "tool_call",
}
msg = AIMessage("", tool_calls=[tool_call])
result = node.invoke({"messages": [msg]}, config=_create_config_with_runtime())
tool_message = result["messages"][-1]
assert "ADMIN_SECRET" not in tool_message.content
def test_tool_node_injected_state_overwrites_llm_value() -> None:
"""InjectedState should use graph state, not LLM-supplied values."""
@dec_tool
def read_secret(
query: str,
auth: Annotated[dict, InjectedState("auth")],
) -> str:
"""Return secret data based on auth from graph state."""
if auth.get("role") == "admin":
return "ADMIN_SECRET"
return "PUBLIC_DATA"
node = ToolNode([read_secret])
# LLM tries to supply auth as admin
tool_call = {
"name": "read_secret",
"args": {"query": "hello", "auth": {"role": "admin"}},
"id": "call-1",
"type": "tool_call",
}
msg = AIMessage("", tool_calls=[tool_call])
# Graph state has auth as viewer
result = node.invoke(
{"messages": [msg], "auth": {"role": "viewer"}},
config=_create_config_with_runtime(),
)
tool_message = result["messages"][-1]
assert tool_message.content == "PUBLIC_DATA"
+2 -2
View File
@@ -268,7 +268,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.1.5"
version = "1.1.4"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -490,7 +490,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "1.0.9"
version = "1.0.8"
source = { editable = "." }
dependencies = [
{ name = "langchain-core" },
+2 -2
View File
@@ -281,7 +281,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.1.5"
version = "1.1.4"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -413,7 +413,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "1.0.9"
version = "1.0.8"
source = { editable = "../prebuilt" }
dependencies = [
{ name = "langchain-core" },