mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-18 05:35:43 +02:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8657df80f3 | ||
|
|
a529b9bede | ||
|
|
0a26b471d3 | ||
|
|
b674dd4622 | ||
|
|
8df0a377d0 | ||
|
|
216cf33a54 | ||
|
|
4956134a37 | ||
|
|
aa94790f36 | ||
|
|
e002711ede | ||
|
|
f44b49b33d |
@@ -121,8 +121,8 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
LANGCHAIN_OPENAI_VERSION=$(docker run --rm --entrypoint "" langgraph-test-h python -c "import sys; from importlib.metadata import version; v = version('langchain-openai'); print(v);")
|
||||
if [ "$LANGCHAIN_OPENAI_VERSION" != "1.0.1" ]; then
|
||||
echo "LANGCHAIN_OPENAI_VERSION != 1.0.1; $LANGCHAIN_OPENAI_VERSION"
|
||||
if [ "$LANGCHAIN_OPENAI_VERSION" != "1.1.14" ]; then
|
||||
echo "LANGCHAIN_OPENAI_VERSION != 1.1.14; $LANGCHAIN_OPENAI_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
LANGCHAIN_ANTHROPIC_VERSION=$(docker run --rm --entrypoint "" langgraph-test-h python -c "import sys; from importlib.metadata import version; v = version('langchain-anthropic'); print(v);")
|
||||
|
||||
@@ -46,6 +46,23 @@ LC_REVIVER = Reviver()
|
||||
EMPTY_BYTES = b""
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Dedup log warnings across process lifetime; cap bounds state if types are
|
||||
# dynamically generated (also acts as a circuit breaker on warning volume).
|
||||
# Dedup is best-effort: racing threads may each emit once for the same key,
|
||||
# and warnings are silently dropped once _MAX_WARNED_TYPES is reached.
|
||||
_MAX_WARNED_TYPES = 1000
|
||||
_warned_unregistered_types: set[tuple[str, str]] = set()
|
||||
_warned_blocked_types: set[tuple[str, str]] = set()
|
||||
|
||||
|
||||
def _warn_once(
|
||||
seen: set[tuple[str, str]], key: tuple[str, str], msg: str, *args: object
|
||||
) -> None:
|
||||
if key in seen or len(seen) >= _MAX_WARNED_TYPES:
|
||||
return
|
||||
seen.add(key)
|
||||
logger.warning(msg, *args)
|
||||
|
||||
|
||||
class JsonPlusSerializer(SerializerProtocol):
|
||||
"""Serializer that uses ormsgpack, with optional fallbacks.
|
||||
@@ -534,7 +551,9 @@ def _create_msgpack_ext_hook(
|
||||
"name": name,
|
||||
}
|
||||
)
|
||||
logger.warning(
|
||||
_warn_once(
|
||||
_warned_unregistered_types,
|
||||
key,
|
||||
"Deserializing unregistered type %s.%s from checkpoint. "
|
||||
"This will be blocked in a future version. "
|
||||
"Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add "
|
||||
@@ -556,7 +575,9 @@ def _create_msgpack_ext_hook(
|
||||
"name": name,
|
||||
}
|
||||
)
|
||||
logger.warning(
|
||||
_warn_once(
|
||||
_warned_blocked_types,
|
||||
key,
|
||||
"Blocked deserialization of %s.%s - not in allowed_msgpack_modules. "
|
||||
"Add to allowed_msgpack_modules to allow: [(%r, %r)]",
|
||||
module,
|
||||
|
||||
@@ -29,6 +29,8 @@ from langgraph.checkpoint.serde.jsonplus import (
|
||||
EXT_METHOD_SINGLE_ARG,
|
||||
JsonPlusSerializer,
|
||||
_msgpack_enc,
|
||||
_warned_blocked_types,
|
||||
_warned_unregistered_types,
|
||||
)
|
||||
|
||||
|
||||
@@ -102,6 +104,13 @@ def test_msgpack_method_pathlib_blocked_encrypted_strict(
|
||||
class TestEncryptedSerializerMsgpackAllowlist:
|
||||
"""Test msgpack allowlist behavior through EncryptedSerializer."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_warned_types(self) -> None:
|
||||
# Warning dedup state is process-global; reset per-test so each case
|
||||
# sees a fresh slate and assertions about warning emission are stable.
|
||||
_warned_unregistered_types.clear()
|
||||
_warned_blocked_types.clear()
|
||||
|
||||
def test_safe_types_no_warning(self, caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""Test safe types deserialize without warnings through encryption."""
|
||||
serde = _make_encrypted_serde()
|
||||
|
||||
@@ -35,6 +35,8 @@ from langgraph.checkpoint.serde.jsonplus import (
|
||||
JsonPlusSerializer,
|
||||
_msgpack_enc,
|
||||
_msgpack_ext_hook_to_json,
|
||||
_warned_blocked_types,
|
||||
_warned_unregistered_types,
|
||||
)
|
||||
from langgraph.store.base import Item
|
||||
|
||||
@@ -580,6 +582,14 @@ def test_msgpack_safe_types_no_warning(caplog: pytest.LogCaptureFixture) -> None
|
||||
assert result is not None
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_warned_types() -> None:
|
||||
# Warning dedup state is process-global; reset per-test so each case sees
|
||||
# a fresh slate and assertions about warning emission are stable.
|
||||
_warned_unregistered_types.clear()
|
||||
_warned_blocked_types.clear()
|
||||
|
||||
|
||||
def test_msgpack_pydantic_warns_by_default(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""Pydantic models not in allowlist should log warning but still deserialize."""
|
||||
current = _lg_msgpack.STRICT_MSGPACK_ENABLED
|
||||
@@ -595,6 +605,12 @@ def test_msgpack_pydantic_warns_by_default(caplog: pytest.LogCaptureFixture) ->
|
||||
assert "unregistered type" in caplog.text.lower()
|
||||
assert "allowed_msgpack_modules" in caplog.text
|
||||
assert result == obj
|
||||
|
||||
# Second deserialization of the same type should NOT produce another warning
|
||||
caplog.clear()
|
||||
result2 = serde.loads_typed(dumped)
|
||||
assert "unregistered type" not in caplog.text.lower()
|
||||
assert result2 == obj
|
||||
_lg_msgpack.STRICT_MSGPACK_ENABLED = current
|
||||
|
||||
|
||||
@@ -639,7 +655,6 @@ def test_msgpack_allowlist_silences_warning(caplog: pytest.LogCaptureFixture) ->
|
||||
|
||||
def test_msgpack_none_blocks_unregistered(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""allowed_msgpack_modules=None should block unregistered types."""
|
||||
|
||||
serde = JsonPlusSerializer(allowed_msgpack_modules=None)
|
||||
|
||||
obj = MyPydantic(foo="test", bar=42, inner=InnerPydantic(hello="world"))
|
||||
@@ -657,7 +672,6 @@ def test_msgpack_allowlist_blocks_non_listed(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Allowlists should block unregistered types even if msgpack is enabled."""
|
||||
|
||||
serde = JsonPlusSerializer(
|
||||
allowed_msgpack_modules=[("tests.test_jsonplus", "MyPydantic")]
|
||||
)
|
||||
|
||||
@@ -12,13 +12,25 @@ from langgraph.checkpoint.base import (
|
||||
empty_checkpoint,
|
||||
)
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
||||
from langgraph.checkpoint.serde.jsonplus import (
|
||||
JsonPlusSerializer,
|
||||
_warned_blocked_types,
|
||||
_warned_unregistered_types,
|
||||
)
|
||||
|
||||
|
||||
class MemoryPydantic(BaseModel):
|
||||
foo: str
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_warned_types() -> None:
|
||||
# Warning dedup state is process-global; reset per-test so each case sees
|
||||
# a fresh slate and assertions about warning emission are stable.
|
||||
_warned_unregistered_types.clear()
|
||||
_warned_blocked_types.clear()
|
||||
|
||||
|
||||
class TestMemorySaver:
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup(self) -> None:
|
||||
|
||||
@@ -5,5 +5,5 @@ description = "Test for prerelease stuff"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"langchain-openai==1.0.1"
|
||||
"langchain-openai==1.1.14"
|
||||
]
|
||||
@@ -5,7 +5,7 @@ description = "Test for prerelease stuff"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"langchain-openai==1.0.0a2",
|
||||
"langchain-openai==1.1.14",
|
||||
"langchain-anthropic==1.0.0a5",
|
||||
"langgraph==1.1.5"
|
||||
]
|
||||
|
||||
@@ -5,7 +5,7 @@ description = "Test for prerelease stuff"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"langchain-openai==1.0.0a2",
|
||||
"langchain-openai==1.1.14",
|
||||
"langgraph==1.1.2",
|
||||
"langchain_community>=0.3.0",
|
||||
]
|
||||
@@ -1 +1 @@
|
||||
__version__ = "0.4.23"
|
||||
__version__ = "0.4.24"
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Shared ignore-file handling for local source filtering."""
|
||||
|
||||
import pathlib
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pathspec
|
||||
|
||||
_ALWAYS_EXCLUDE = [
|
||||
"__pycache__/",
|
||||
".git/",
|
||||
".venv/",
|
||||
"venv/",
|
||||
"node_modules/",
|
||||
".tox/",
|
||||
".mypy_cache/",
|
||||
]
|
||||
_ALWAYS_EXCLUDE_NAMES = frozenset(
|
||||
pattern.rstrip("/").split("/")[-1] for pattern in _ALWAYS_EXCLUDE
|
||||
)
|
||||
_GLOB_CHARS = frozenset("*?[")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _NegatedDockerignoreHints:
|
||||
exact_dirs: frozenset[pathlib.PurePosixPath] = frozenset()
|
||||
wildcard_prefixes: frozenset[pathlib.PurePosixPath] = frozenset()
|
||||
recurse_all: bool = False
|
||||
|
||||
def requires_dir_walk(self, path: pathlib.PurePosixPath) -> bool:
|
||||
if self.recurse_all or path in self.exact_dirs:
|
||||
return True
|
||||
return any(
|
||||
path == prefix or path in prefix.parents or prefix in path.parents
|
||||
for prefix in self.wildcard_prefixes
|
||||
)
|
||||
|
||||
|
||||
def _build_ignore_spec(
|
||||
directory: pathlib.Path, *, include_gitignore: bool = True
|
||||
) -> pathspec.PathSpec:
|
||||
"""Build a PathSpec combining built-in exclusions with ignore files.
|
||||
|
||||
Always excludes common non-source directories (`_ALWAYS_EXCLUDE`). On top
|
||||
of that, patterns from `.dockerignore` are merged in. `.gitignore` patterns
|
||||
are optional because some callers need Docker build-context semantics,
|
||||
while archive creation wants both files.
|
||||
"""
|
||||
lines: list[str] = list(_ALWAYS_EXCLUDE)
|
||||
ignore_files = [".dockerignore"]
|
||||
if include_gitignore:
|
||||
ignore_files.append(".gitignore")
|
||||
for name in ignore_files:
|
||||
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 _is_always_excluded(path: pathlib.PurePosixPath, *, is_dir: bool) -> bool:
|
||||
"""Whether `path` lives inside a built-in excluded directory."""
|
||||
parent_parts = path.parts if is_dir else path.parts[:-1]
|
||||
return any(part in _ALWAYS_EXCLUDE_NAMES for part in parent_parts)
|
||||
|
||||
|
||||
def _build_dockerignore_negation_hints(
|
||||
directory: pathlib.Path,
|
||||
) -> _NegatedDockerignoreHints:
|
||||
"""Summarize which ignored directories must still be traversed.
|
||||
|
||||
Most negations only require walking a small, concrete chain of parent
|
||||
directories (for example `!assets/keep.txt` requires entering `assets/`).
|
||||
Broader glob negations may force a wider walk.
|
||||
"""
|
||||
ignore_file = directory / ".dockerignore"
|
||||
if not ignore_file.is_file():
|
||||
return _NegatedDockerignoreHints()
|
||||
|
||||
exact_dirs: set[pathlib.PurePosixPath] = set()
|
||||
wildcard_prefixes: set[pathlib.PurePosixPath] = set()
|
||||
recurse_all = False
|
||||
|
||||
for raw_line in ignore_file.read_text(encoding="utf-8").splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#") or line.startswith("\\!"):
|
||||
continue
|
||||
if line.startswith("\\#"):
|
||||
line = line[1:]
|
||||
if not line.startswith("!"):
|
||||
continue
|
||||
|
||||
pattern = line[1:].lstrip("/")
|
||||
while pattern.startswith("./"):
|
||||
pattern = pattern[2:]
|
||||
pattern = pattern.rstrip("/")
|
||||
parts = [part for part in pattern.split("/") if part and part != "."]
|
||||
if not parts:
|
||||
recurse_all = True
|
||||
continue
|
||||
|
||||
wildcard_index = next(
|
||||
(
|
||||
idx
|
||||
for idx, part in enumerate(parts)
|
||||
if any(char in part for char in _GLOB_CHARS)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if wildcard_index is not None:
|
||||
literal_parts = parts[:wildcard_index]
|
||||
if not literal_parts:
|
||||
recurse_all = True
|
||||
continue
|
||||
wildcard_prefixes.add(pathlib.PurePosixPath(*literal_parts))
|
||||
continue
|
||||
|
||||
parent_parts = parts[:-1]
|
||||
for idx in range(1, len(parent_parts) + 1):
|
||||
exact_dirs.add(pathlib.PurePosixPath(*parent_parts[:idx]))
|
||||
|
||||
return _NegatedDockerignoreHints(
|
||||
exact_dirs=frozenset(exact_dirs),
|
||||
wildcard_prefixes=frozenset(wildcard_prefixes),
|
||||
recurse_all=recurse_all,
|
||||
)
|
||||
@@ -9,35 +9,12 @@ from contextlib import contextmanager
|
||||
import click
|
||||
import pathspec
|
||||
|
||||
from langgraph_cli._ignore import _build_ignore_spec
|
||||
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."""
|
||||
|
||||
@@ -10,7 +10,13 @@ except ModuleNotFoundError: # pragma: no cover - exercised on Python 3.10.
|
||||
import tomli as tomllib
|
||||
|
||||
import click
|
||||
import pathspec
|
||||
|
||||
from langgraph_cli._ignore import (
|
||||
_build_dockerignore_negation_hints,
|
||||
_build_ignore_spec,
|
||||
_is_always_excluded,
|
||||
)
|
||||
from langgraph_cli.schemas import Config
|
||||
|
||||
|
||||
@@ -440,16 +446,32 @@ def _container_root_for_uv_lock_package(
|
||||
|
||||
|
||||
def _uv_lock_package_copy_items(
|
||||
package: UvLockPackage, plan: UvLockPlan
|
||||
package: UvLockPackage,
|
||||
plan: UvLockPlan,
|
||||
ignore_spec: pathspec.PathSpec,
|
||||
) -> tuple[tuple[pathlib.PurePosixPath, pathlib.PurePosixPath], ...]:
|
||||
# Skip entries that .dockerignore / built-in exclusions would strip from
|
||||
# the build context. Emitting `ADD <path>` for a file that Docker has
|
||||
# filtered out causes the build to fail with
|
||||
# "failed to compute cache key: <path> not found".
|
||||
if package.root != plan.project_root:
|
||||
relative_root = pathlib.PurePosixPath(
|
||||
*package.root.relative_to(plan.project_root).parts
|
||||
)
|
||||
if _is_always_excluded(relative_root, is_dir=True) or ignore_spec.match_file(
|
||||
f"{relative_root.as_posix()}/"
|
||||
):
|
||||
raise click.UsageError(
|
||||
f"Workspace member '{package.name}' at {relative_root} is "
|
||||
"excluded from the Docker build context, but uv.lock requires "
|
||||
"it to be copied into the build context. Remove the matching "
|
||||
"pattern or drop the member from [tool.uv.workspace].members."
|
||||
)
|
||||
return ((relative_root, plan.container_roots[package.root]),)
|
||||
|
||||
root_container = plan.container_roots[package.root]
|
||||
workspace_member_roots = plan.all_workspace_roots - {plan.project_root}
|
||||
negated_dockerignore_hints = _build_dockerignore_negation_hints(plan.project_root)
|
||||
|
||||
def iter_entries(
|
||||
current_dir: pathlib.Path,
|
||||
@@ -461,18 +483,32 @@ def _uv_lock_package_copy_items(
|
||||
# and excluded entirely otherwise.
|
||||
continue
|
||||
|
||||
descendant_member_roots = [
|
||||
ws_root
|
||||
for ws_root in workspace_member_roots
|
||||
if child in ws_root.parents
|
||||
]
|
||||
if child.is_dir() and descendant_member_roots:
|
||||
entries.extend(iter_entries(child))
|
||||
continue
|
||||
|
||||
relative_child = pathlib.PurePosixPath(
|
||||
*child.relative_to(plan.project_root).parts
|
||||
)
|
||||
is_dir = child.is_dir()
|
||||
if _is_always_excluded(relative_child, is_dir=is_dir):
|
||||
continue
|
||||
ignored = ignore_spec.match_file(
|
||||
f"{relative_child.as_posix()}/" if is_dir else relative_child.as_posix()
|
||||
)
|
||||
is_workspace_parent = is_dir and any(
|
||||
child in ws_root.parents for ws_root in workspace_member_roots
|
||||
)
|
||||
|
||||
if is_workspace_parent:
|
||||
entries.extend(iter_entries(child))
|
||||
continue
|
||||
if (
|
||||
is_dir
|
||||
and ignored
|
||||
and negated_dockerignore_hints.requires_dir_walk(relative_child)
|
||||
):
|
||||
entries.extend(iter_entries(child))
|
||||
continue
|
||||
if ignored:
|
||||
continue
|
||||
|
||||
entries.append(
|
||||
(relative_child, root_container.joinpath(*relative_child.parts))
|
||||
)
|
||||
@@ -956,10 +992,13 @@ def python_config_to_docker_uv_lock(
|
||||
docker_plan.add_raw("# -- End of uv.lock dependencies install --")
|
||||
docker_plan.add_blank()
|
||||
|
||||
ignore_spec = _build_ignore_spec(plan.project_root, include_gitignore=False)
|
||||
for package in plan.install_order:
|
||||
package_label = package.root.relative_to(plan.project_root).as_posix() or "."
|
||||
docker_plan.add_raw(f"# -- Adding workspace package {package_label} --")
|
||||
for source, destination in _uv_lock_package_copy_items(package, plan):
|
||||
for source, destination in _uv_lock_package_copy_items(
|
||||
package, plan, ignore_spec
|
||||
):
|
||||
docker_plan.add_raw(copy_from_project_root(source, destination.as_posix()))
|
||||
docker_plan.add_instruction(
|
||||
"WORKDIR", plan.container_roots[package.root].as_posix()
|
||||
|
||||
@@ -99,6 +99,13 @@ class TestBuildIgnoreSpec:
|
||||
assert spec.match_file("app.log")
|
||||
assert spec.match_file("mod.pyc")
|
||||
|
||||
def test_can_skip_gitignore(self, tmp_path):
|
||||
(tmp_path / ".dockerignore").write_text("*.log\n")
|
||||
(tmp_path / ".gitignore").write_text("*.pyc\n")
|
||||
spec = _build_ignore_spec(tmp_path, include_gitignore=False)
|
||||
assert spec.match_file("app.log")
|
||||
assert not 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__/")
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import pathlib
|
||||
import tempfile
|
||||
import textwrap
|
||||
from unittest.mock import patch
|
||||
|
||||
import click
|
||||
import pytest
|
||||
@@ -1855,6 +1856,364 @@ def test_config_to_docker_uv_lock_supports_single_uv_project_root():
|
||||
assert additional_contexts == {}
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_skips_dockerignore_entries():
|
||||
"""Entries filtered by .dockerignore / built-in excludes must not appear
|
||||
as ADD lines. Docker fails to compute the cache key for paths that the
|
||||
build context has stripped."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root = tmpdir_path / "single"
|
||||
project_root.mkdir()
|
||||
(project_root / "uv.lock").write_text("# uv lock file\n")
|
||||
(project_root / "pyproject.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "single-app"
|
||||
version = "0.1.0"
|
||||
dependencies = ["httpx>=0.28"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
"""
|
||||
).strip()
|
||||
+ "\n"
|
||||
)
|
||||
(project_root / "langgraph.json").write_text("{}\n")
|
||||
(project_root / "src").mkdir()
|
||||
(project_root / "src" / "agent.py").write_text("graph = object()\n")
|
||||
(project_root / "README.md").write_text("# hi\n")
|
||||
|
||||
# Built-in exclusions — must never appear as ADD lines.
|
||||
(project_root / ".git").mkdir()
|
||||
(project_root / ".git" / "HEAD").write_text("ref: refs/heads/main\n")
|
||||
(project_root / ".venv").mkdir()
|
||||
(project_root / ".venv" / "pyvenv.cfg").write_text("home = /usr\n")
|
||||
(project_root / "__pycache__").mkdir()
|
||||
(project_root / "__pycache__" / "x.cpython-311.pyc").write_bytes(b"\x00")
|
||||
|
||||
# .dockerignore excludes .gitignore and a custom path.
|
||||
(project_root / ".dockerignore").write_text(".gitignore\nsecrets.env\n")
|
||||
(project_root / ".gitignore").write_text("*.pyc\n")
|
||||
(project_root / "secrets.env").write_text("TOKEN=abc\n")
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
docker, _ = config_to_docker(
|
||||
project_root / "langgraph.json",
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
for excluded in (
|
||||
"ADD .git ",
|
||||
"ADD .gitignore ",
|
||||
"ADD .venv ",
|
||||
"ADD __pycache__ ",
|
||||
"ADD secrets.env ",
|
||||
):
|
||||
assert excluded not in docker, (
|
||||
f"{excluded!r} should be filtered out of Dockerfile:\n{docker}"
|
||||
)
|
||||
|
||||
# The .dockerignore itself is still part of the context and should be
|
||||
# ADDed (Docker needs it at build time, and archive.py includes it).
|
||||
assert "ADD .dockerignore /deps/workspace/.dockerignore" in docker
|
||||
assert "ADD src /deps/workspace/src" in docker
|
||||
assert "ADD README.md /deps/workspace/README.md" in docker
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_does_not_apply_gitignore():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root = tmpdir_path / "single"
|
||||
project_root.mkdir()
|
||||
(project_root / "uv.lock").write_text("# uv lock file\n")
|
||||
(project_root / "pyproject.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "single-app"
|
||||
version = "0.1.0"
|
||||
dependencies = ["httpx>=0.28"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
"""
|
||||
).strip()
|
||||
+ "\n"
|
||||
)
|
||||
(project_root / "langgraph.json").write_text("{}\n")
|
||||
(project_root / "src").mkdir()
|
||||
(project_root / "src" / "agent.py").write_text("graph = object()\n")
|
||||
(project_root / "README.md").write_text("# hi\n")
|
||||
(project_root / ".gitignore").write_text("README.md\n")
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
docker, _ = config_to_docker(
|
||||
project_root / "langgraph.json",
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
assert "ADD README.md /deps/workspace/README.md" in docker
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_skips_dockerignore_entries_in_workspace():
|
||||
"""Multi-member workspace: ignore patterns must filter root-level entries
|
||||
AND entries encountered while recursing into directories that contain
|
||||
workspace members (the `descendant_member_roots` branch)."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root, config_path = _write_uv_lock_workspace(
|
||||
tmpdir_path,
|
||||
agent_dependencies=["workspace-root", "shared", "httpx>=0.28"],
|
||||
root_sources="[tool.uv.sources]\nshared = { workspace = true }\nworkspace-root = { workspace = true }",
|
||||
agent_sources="[tool.uv.sources]\nshared = { workspace = true }\nworkspace-root = { workspace = true }",
|
||||
)
|
||||
root_src = project_root / "src" / "workspace_root"
|
||||
root_src.mkdir(parents=True)
|
||||
(root_src / "__init__.py").write_text("__all__ = []\n")
|
||||
(project_root / "README.md").write_text("workspace root package\n")
|
||||
|
||||
# A non-member sibling of the `apps/agent` member that should be
|
||||
# filtered out via .dockerignore. This exercises the recursion into
|
||||
# `apps/` where `apps/agent` is kept (it's a member) but its sibling is
|
||||
# filtered.
|
||||
(project_root / "apps" / "scratch.txt").write_text("scratch\n")
|
||||
# A root-level path that .dockerignore excludes.
|
||||
(project_root / "secrets.env").write_text("TOKEN=abc\n")
|
||||
(project_root / ".dockerignore").write_text("secrets.env\napps/scratch.txt\n")
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {
|
||||
"agent": "../../apps/agent/src/agent/graph.py:graph",
|
||||
},
|
||||
"source": {"kind": "uv", "root": "../..", "package": "agent"},
|
||||
}
|
||||
)
|
||||
docker, _ = config_to_docker(
|
||||
config_path, config, base_image="langchain/langgraph-api:0.2.47"
|
||||
)
|
||||
|
||||
assert "COPY --from=uv-workspace-root src /deps/workspace/src" in docker
|
||||
assert (
|
||||
"COPY --from=uv-workspace-root README.md /deps/workspace/README.md"
|
||||
in docker
|
||||
)
|
||||
assert (
|
||||
"COPY --from=uv-workspace-root .dockerignore /deps/workspace/.dockerignore"
|
||||
in docker
|
||||
)
|
||||
assert "secrets.env" not in docker
|
||||
assert "apps/scratch.txt" not in docker
|
||||
# Workspace members themselves are still copied via their own per-member
|
||||
# COPY line — the sibling filter must not disturb this.
|
||||
assert (
|
||||
"COPY --from=uv-workspace-root apps/agent /deps/workspace/apps/agent"
|
||||
in docker
|
||||
)
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_preserves_negated_dockerignore_descendants():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root = tmpdir_path / "single"
|
||||
project_root.mkdir()
|
||||
(project_root / "uv.lock").write_text("# uv lock file\n")
|
||||
(project_root / "pyproject.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "single-app"
|
||||
version = "0.1.0"
|
||||
dependencies = ["httpx>=0.28"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
"""
|
||||
).strip()
|
||||
+ "\n"
|
||||
)
|
||||
(project_root / "langgraph.json").write_text("{}\n")
|
||||
(project_root / "src").mkdir()
|
||||
(project_root / "src" / "agent.py").write_text("graph = object()\n")
|
||||
(project_root / "assets").mkdir()
|
||||
(project_root / "assets" / "keep.txt").write_text("keep\n")
|
||||
(project_root / "assets" / "drop.txt").write_text("drop\n")
|
||||
(project_root / ".dockerignore").write_text("assets/\n!assets/keep.txt\n")
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
docker, _ = config_to_docker(
|
||||
project_root / "langgraph.json",
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
assert "ADD assets /deps/workspace/assets" not in docker
|
||||
assert "ADD assets/keep.txt /deps/workspace/assets/keep.txt" in docker
|
||||
assert "assets/drop.txt" not in docker
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_prunes_unrelated_ignored_subtrees():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root = tmpdir_path / "single"
|
||||
project_root.mkdir()
|
||||
(project_root / "uv.lock").write_text("# uv lock file\n")
|
||||
(project_root / "pyproject.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "single-app"
|
||||
version = "0.1.0"
|
||||
dependencies = ["httpx>=0.28"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
"""
|
||||
).strip()
|
||||
+ "\n"
|
||||
)
|
||||
(project_root / "langgraph.json").write_text("{}\n")
|
||||
(project_root / "src").mkdir()
|
||||
(project_root / "src" / "agent.py").write_text("graph = object()\n")
|
||||
(project_root / "assets").mkdir()
|
||||
(project_root / "assets" / "keep.txt").write_text("keep\n")
|
||||
(project_root / "vendor").mkdir()
|
||||
(project_root / "vendor" / "huge.txt").write_text("large\n")
|
||||
(project_root / ".dockerignore").write_text(
|
||||
"vendor/\nassets/\n!assets/keep.txt\n"
|
||||
)
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
|
||||
original_iterdir = pathlib.Path.iterdir
|
||||
|
||||
def guarded_iterdir(self):
|
||||
if self == project_root / "vendor":
|
||||
raise AssertionError("should not walk unrelated ignored subtree")
|
||||
return original_iterdir(self)
|
||||
|
||||
with patch.object(
|
||||
pathlib.Path, "iterdir", autospec=True, side_effect=guarded_iterdir
|
||||
):
|
||||
docker, _ = config_to_docker(
|
||||
project_root / "langgraph.json",
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
assert "ADD assets/keep.txt /deps/workspace/assets/keep.txt" in docker
|
||||
assert "vendor/huge.txt" not in docker
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_never_reincludes_always_excluded_subtrees():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root = tmpdir_path / "single"
|
||||
project_root.mkdir()
|
||||
(project_root / "uv.lock").write_text("# uv lock file\n")
|
||||
(project_root / "pyproject.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "single-app"
|
||||
version = "0.1.0"
|
||||
dependencies = ["httpx>=0.28"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
"""
|
||||
).strip()
|
||||
+ "\n"
|
||||
)
|
||||
(project_root / "langgraph.json").write_text("{}\n")
|
||||
(project_root / "src").mkdir()
|
||||
(project_root / "src" / "agent.py").write_text("graph = object()\n")
|
||||
(project_root / ".venv" / "pkg").mkdir(parents=True)
|
||||
(project_root / ".venv" / "pkg" / "keep.txt").write_text("keep\n")
|
||||
(project_root / "node_modules" / "pkg").mkdir(parents=True)
|
||||
(project_root / "node_modules" / "pkg" / "package.json").write_text("{}\n")
|
||||
(project_root / ".dockerignore").write_text(
|
||||
"!.venv/pkg/keep.txt\n!node_modules/pkg/package.json\n"
|
||||
)
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
docker, _ = config_to_docker(
|
||||
project_root / "langgraph.json",
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
assert ".venv/pkg/keep.txt" not in docker
|
||||
assert "node_modules/pkg/package.json" not in docker
|
||||
assert "ADD src /deps/workspace/src" in docker
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_rejects_ignored_workspace_member():
|
||||
"""A workspace member matched by .dockerignore cannot be copied into the
|
||||
build context — uv.lock requires it, so fail loudly with a clear message."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
project_root, config_path = _write_uv_lock_workspace(
|
||||
tmpdir_path,
|
||||
agent_sources="[tool.uv.sources]\nshared = { workspace = true }",
|
||||
)
|
||||
(project_root / ".dockerignore").write_text("libs/shared\n")
|
||||
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "../../apps/agent/src/agent/graph.py:graph"},
|
||||
"source": {"kind": "uv", "root": "../..", "package": "agent"},
|
||||
"auth": {"path": "../../libs/shared/src/shared/auth.py:create_auth"},
|
||||
}
|
||||
)
|
||||
with pytest.raises(
|
||||
click.UsageError, match=r"Workspace member 'shared' at libs/shared"
|
||||
):
|
||||
config_to_docker(
|
||||
config_path, config, base_image="langchain/langgraph-api:0.2.47"
|
||||
)
|
||||
|
||||
|
||||
def test_config_to_docker_uv_lock_rejects_invalid_source_package_type():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tmpdir_path = pathlib.Path(tmpdir)
|
||||
|
||||
@@ -245,15 +245,6 @@ class _GraphCallbackManager(BaseCallbackManager):
|
||||
run_id=run_id,
|
||||
)
|
||||
|
||||
def add_handler(
|
||||
self,
|
||||
handler: BaseCallbackHandler,
|
||||
inherit: bool = True, # noqa: FBT001,FBT002
|
||||
) -> None:
|
||||
if not isinstance(handler, GraphCallbackHandler):
|
||||
raise TypeError("handlers must inherit GraphCallbackHandler")
|
||||
super().add_handler(handler, inherit=inherit)
|
||||
|
||||
def copy(
|
||||
self,
|
||||
*,
|
||||
@@ -321,15 +312,6 @@ class _AsyncGraphCallbackManager(BaseCallbackManager):
|
||||
run_id=run_id,
|
||||
)
|
||||
|
||||
def add_handler(
|
||||
self,
|
||||
handler: BaseCallbackHandler,
|
||||
inherit: bool = True, # noqa: FBT001,FBT002
|
||||
) -> None:
|
||||
if not isinstance(handler, GraphCallbackHandler):
|
||||
raise TypeError("handlers must inherit GraphCallbackHandler")
|
||||
super().add_handler(handler, inherit=inherit)
|
||||
|
||||
def copy(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -831,8 +831,18 @@ class PregelLoop:
|
||||
# parent. For forks (source=update/fork), use the fork's parent
|
||||
# checkpoint ID since the fork was created after the subgraph's
|
||||
# checkpoints from the original execution.
|
||||
#
|
||||
# Only gate on is_time_traveling (not is_replaying). When the
|
||||
# client resumes with an explicit checkpoint_id that happens to
|
||||
# point at the current head (e.g. LangGraph Studio sending
|
||||
# `checkpoint: {checkpoint_id}` alongside Command(resume=...)),
|
||||
# is_replaying is True but is_time_traveling is False. In that
|
||||
# case subgraphs should load their latest checkpoint normally,
|
||||
# not go through ReplayState's before-bound lookup which would
|
||||
# miss subgraph checkpoints created during processing of the
|
||||
# current parent step.
|
||||
replay_state: ReplayState | None = None
|
||||
if self.is_replaying:
|
||||
if is_time_traveling:
|
||||
replay_checkpoint_id = self.checkpoint["id"]
|
||||
if (
|
||||
self.checkpoint_metadata.get("source")
|
||||
|
||||
@@ -14,7 +14,7 @@ from langchain_core.messages import BaseMessage
|
||||
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, LLMResult
|
||||
from pydantic import BaseModel
|
||||
|
||||
from langgraph._internal._constants import NS_END, NS_SEP
|
||||
from langgraph._internal._constants import NS_SEP
|
||||
from langgraph.constants import TAG_HIDDEN, TAG_NOSTREAM
|
||||
from langgraph.pregel.protocol import StreamChunk
|
||||
from langgraph.types import Command
|
||||
@@ -132,23 +132,15 @@ class StreamMessagesHandler(BaseCallbackHandler, _StreamingCallbackHandler):
|
||||
**kwargs: Any,
|
||||
) -> Any:
|
||||
if metadata and (not tags or (TAG_NOSTREAM not in tags)):
|
||||
task_checkpoint_ns = cast(str, metadata["langgraph_checkpoint_ns"])
|
||||
checkpoint_ns = (
|
||||
f"{task_checkpoint_ns.rsplit(NS_END, 1)[0]}{NS_END}"
|
||||
if NS_END in task_checkpoint_ns
|
||||
else task_checkpoint_ns
|
||||
)
|
||||
ns = tuple(task_checkpoint_ns.split(NS_SEP))[:-1]
|
||||
ns = tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP))[
|
||||
:-1
|
||||
]
|
||||
if not self.subgraphs and len(ns) > 0 and ns != self.parent_ns:
|
||||
return
|
||||
stream_metadata = dict(metadata)
|
||||
stream_metadata["langgraph_checkpoint_ns"] = checkpoint_ns
|
||||
# Preserve backwards-compatible streamed checkpoint metadata shape.
|
||||
stream_metadata["checkpoint_ns"] = checkpoint_ns
|
||||
if tags:
|
||||
if filtered_tags := [t for t in tags if not t.startswith("seq:step")]:
|
||||
stream_metadata["tags"] = filtered_tags
|
||||
self.metadata[run_id] = (ns, stream_metadata)
|
||||
metadata["tags"] = filtered_tags
|
||||
self.metadata[run_id] = (ns, metadata)
|
||||
|
||||
def on_llm_new_token(
|
||||
self,
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langgraph"
|
||||
version = "1.1.7"
|
||||
version = "1.1.9"
|
||||
description = "Building stateful, multi-actor applications with LLMs"
|
||||
authors = []
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -275,3 +275,70 @@ def test_graph_callbacks_accept_base_callback_manager() -> None:
|
||||
|
||||
assert "__interrupt__" in first
|
||||
assert len(graph_handler.interrupt_events) == 1
|
||||
|
||||
|
||||
def test_non_graph_handler_via_add_handler_does_not_crash() -> None:
|
||||
"""Non-GraphCallbackHandler added via add_handler should not raise.
|
||||
|
||||
Libraries like opentelemetry-instrumentation-langchain monkey-patch
|
||||
BaseCallbackManager.__init__ and inject handlers via add_handler().
|
||||
These handlers inherit from BaseCallbackHandler, not
|
||||
GraphCallbackHandler. They must be silently accepted — graph lifecycle
|
||||
events will simply not be dispatched to them.
|
||||
"""
|
||||
from langgraph.callbacks import _GraphCallbackManager
|
||||
|
||||
manager = _GraphCallbackManager()
|
||||
plain_handler = _LangChainCustomEventHandler()
|
||||
|
||||
manager.add_handler(plain_handler, inherit=True)
|
||||
assert plain_handler in manager.handlers
|
||||
|
||||
|
||||
def test_non_graph_handler_does_not_receive_lifecycle_events() -> None:
|
||||
"""Non-GraphCallbackHandler added alongside a GraphCallbackHandler
|
||||
should not interfere with lifecycle event dispatch."""
|
||||
graph = _build_interrupt_graph()
|
||||
graph_handler = _GraphEventHandler()
|
||||
plain_handler = _LangChainCustomEventHandler()
|
||||
|
||||
config = {
|
||||
"configurable": {"thread_id": "graph-callback-mixed-handlers"},
|
||||
"callbacks": [plain_handler, graph_handler],
|
||||
}
|
||||
|
||||
first = graph.invoke({"answer": None}, config)
|
||||
assert "__interrupt__" in first
|
||||
|
||||
assert len(graph_handler.interrupt_events) == 1
|
||||
assert plain_handler.events == []
|
||||
|
||||
resumed = graph.invoke(Command(resume="done"), config)
|
||||
assert resumed == {"answer": "done"}
|
||||
assert len(graph_handler.resume_events) == 1
|
||||
assert plain_handler.events == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@NEEDS_CONTEXTVARS
|
||||
async def test_non_graph_handler_does_not_receive_lifecycle_events_async() -> None:
|
||||
"""Async variant: non-GraphCallbackHandler should not interfere."""
|
||||
graph = _build_interrupt_graph()
|
||||
graph_handler = _GraphEventHandler()
|
||||
plain_handler = _LangChainCustomEventHandler()
|
||||
|
||||
config = {
|
||||
"configurable": {"thread_id": "graph-callback-mixed-handlers-async"},
|
||||
"callbacks": [plain_handler, graph_handler],
|
||||
}
|
||||
|
||||
first = await graph.ainvoke({"answer": None}, config)
|
||||
assert "__interrupt__" in first
|
||||
|
||||
assert len(graph_handler.interrupt_events) == 1
|
||||
assert plain_handler.events == []
|
||||
|
||||
resumed = await graph.ainvoke(Command(resume="done"), config)
|
||||
assert resumed == {"answer": "done"}
|
||||
assert len(graph_handler.resume_events) == 1
|
||||
assert plain_handler.events == []
|
||||
|
||||
@@ -1113,6 +1113,72 @@ def test_subgraph_interrupt_replay_from_parent_then_resume(
|
||||
]
|
||||
|
||||
|
||||
def test_subgraph_interrupt_resume_with_explicit_head_checkpoint_id(
|
||||
sync_checkpointer: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Resume with Command(resume=...) plus the current head checkpoint_id
|
||||
in config. The subgraph must continue from the interrupted node, not
|
||||
restart from scratch. Explicit checkpoint_id triggers is_replaying but
|
||||
this is a resume, not a time-travel, so ReplayState should not apply."""
|
||||
|
||||
called: list[str] = []
|
||||
|
||||
def step_a(state: State) -> State:
|
||||
called.append("step_a")
|
||||
return {"value": ["sub_a"]}
|
||||
|
||||
def ask_human(state: State) -> State:
|
||||
called.append("ask_human")
|
||||
answer = interrupt("Provide input:")
|
||||
return {"value": [f"human:{answer}"]}
|
||||
|
||||
def step_b(state: State) -> State:
|
||||
called.append("step_b")
|
||||
return {"value": ["sub_b"]}
|
||||
|
||||
subgraph = (
|
||||
StateGraph(State)
|
||||
.add_node("step_a", step_a)
|
||||
.add_node("ask_human", ask_human)
|
||||
.add_node("step_b", step_b)
|
||||
.add_edge(START, "step_a")
|
||||
.add_edge("step_a", "ask_human")
|
||||
.add_edge("ask_human", "step_b")
|
||||
.compile(checkpointer=True)
|
||||
)
|
||||
|
||||
graph = (
|
||||
StateGraph(State)
|
||||
.add_node("subgraph_node", subgraph)
|
||||
.add_edge(START, "subgraph_node")
|
||||
.compile(checkpointer=sync_checkpointer)
|
||||
)
|
||||
|
||||
config = {"configurable": {"thread_id": "1"}}
|
||||
|
||||
# Run until interrupt fires in subgraph
|
||||
graph.invoke({"value": []}, config)
|
||||
assert called == ["step_a", "ask_human"]
|
||||
|
||||
# Resume with explicit head checkpoint_id in config
|
||||
head_checkpoint_id = graph.get_state(config).config["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
called.clear()
|
||||
resume_config = {
|
||||
"configurable": {
|
||||
"thread_id": "1",
|
||||
"checkpoint_id": head_checkpoint_id,
|
||||
"checkpoint_ns": "",
|
||||
}
|
||||
}
|
||||
result = graph.invoke(Command(resume="answer"), resume_config)
|
||||
|
||||
assert called == ["ask_human", "step_b"]
|
||||
assert "__interrupt__" not in result
|
||||
assert result["value"] == ["sub_a", "human:answer", "sub_b"]
|
||||
|
||||
|
||||
def test_subgraph_replay_loads_accumulated_state_then_resume(
|
||||
sync_checkpointer: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
|
||||
Generated
+2
-2
@@ -1367,7 +1367,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph"
|
||||
version = "1.1.7"
|
||||
version = "1.1.9"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
@@ -1742,7 +1742,7 @@ test = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.0.9"
|
||||
version = "1.0.10"
|
||||
source = { editable = "../prebuilt" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
|
||||
@@ -808,6 +808,7 @@ class ToolNode(RunnableCallable):
|
||||
context=runtime.context,
|
||||
store=runtime.store,
|
||||
stream_writer=runtime.stream_writer,
|
||||
tools=list(self.tools_by_name.values()),
|
||||
execution_info=runtime.execution_info,
|
||||
server_info=runtime.server_info,
|
||||
)
|
||||
@@ -842,6 +843,7 @@ class ToolNode(RunnableCallable):
|
||||
context=runtime.context,
|
||||
store=runtime.store,
|
||||
stream_writer=runtime.stream_writer,
|
||||
tools=list(self.tools_by_name.values()),
|
||||
execution_info=runtime.execution_info,
|
||||
server_info=runtime.server_info,
|
||||
)
|
||||
@@ -1576,6 +1578,7 @@ class ToolRuntime(_DirectlyInjectedToolArg, Generic[ContextT, StateT]):
|
||||
- `context`: Runtime context (shared with `Runtime`)
|
||||
- `store`: `BaseStore` instance for persistent storage (shared with `Runtime`)
|
||||
- `stream_writer`: `StreamWriter` for streaming output (shared with `Runtime`)
|
||||
- `tools`: List of all available `BaseTool` instances
|
||||
|
||||
No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`
|
||||
as a parameter.
|
||||
@@ -1618,6 +1621,7 @@ class ToolRuntime(_DirectlyInjectedToolArg, Generic[ContextT, StateT]):
|
||||
context: ContextT
|
||||
config: RunnableConfig
|
||||
stream_writer: StreamWriter
|
||||
tools: list[BaseTool]
|
||||
tool_call_id: str | None
|
||||
store: BaseStore | None
|
||||
execution_info: ExecutionInfo | None = None
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.0.9"
|
||||
version = "1.0.10"
|
||||
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
|
||||
authors = []
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -69,6 +69,7 @@ def _create_config_with_runtime(store=None, state=None):
|
||||
context={},
|
||||
store=store,
|
||||
stream_writer=None,
|
||||
tools=[],
|
||||
tool_call_id="test_id",
|
||||
)
|
||||
return {
|
||||
|
||||
@@ -2016,8 +2016,8 @@ async def test_tool_node_inject_runtime_dynamic_tool_via_wrap_tool_call_async()
|
||||
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."""
|
||||
def test_tool_runtime_forwards_execution_info_server_info_and_tools() -> None:
|
||||
"""Test that execution_info, server_info, and tools are forwarded from Runtime to ToolRuntime."""
|
||||
from langgraph.runtime import ExecutionInfo, ServerInfo
|
||||
|
||||
exec_info = ExecutionInfo(
|
||||
@@ -2043,9 +2043,15 @@ def test_tool_runtime_forwards_execution_info_and_server_info() -> None:
|
||||
"""Tool that captures runtime info."""
|
||||
captured["execution_info"] = runtime.execution_info
|
||||
captured["server_info"] = runtime.server_info
|
||||
captured["tools"] = runtime.tools
|
||||
return "ok"
|
||||
|
||||
node = ToolNode([info_tool])
|
||||
@dec_tool
|
||||
def other_tool(y: int) -> str:
|
||||
"""Another tool available to the runtime."""
|
||||
return str(y)
|
||||
|
||||
node = ToolNode([info_tool, other_tool])
|
||||
tool_call = {
|
||||
"name": "info_tool",
|
||||
"args": {"x": 1},
|
||||
@@ -2054,17 +2060,21 @@ def test_tool_runtime_forwards_execution_info_and_server_info() -> None:
|
||||
}
|
||||
msg = AIMessage("", tool_calls=[tool_call])
|
||||
config: RunnableConfig = {"configurable": {"__pregel_runtime": mock_runtime}}
|
||||
node.invoke({"messages": [msg]}, config=config)
|
||||
result = node.invoke({"messages": [msg]}, config=config)
|
||||
|
||||
assert result["messages"][-1].content == "ok"
|
||||
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"
|
||||
assert [tool.name for tool in captured["tools"]] == ["info_tool", "other_tool"]
|
||||
|
||||
|
||||
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."""
|
||||
async def test_tool_runtime_forwards_execution_info_server_info_and_tools_async() -> (
|
||||
None
|
||||
):
|
||||
"""Test that execution_info, server_info, and tools are forwarded in async path."""
|
||||
from langgraph.runtime import ExecutionInfo, ServerInfo
|
||||
|
||||
exec_info = ExecutionInfo(
|
||||
@@ -2090,9 +2100,15 @@ async def test_tool_runtime_forwards_execution_info_and_server_info_async() -> N
|
||||
"""Async tool that captures runtime info."""
|
||||
captured["execution_info"] = runtime.execution_info
|
||||
captured["server_info"] = runtime.server_info
|
||||
captured["tools"] = runtime.tools
|
||||
return "ok"
|
||||
|
||||
node = ToolNode([info_tool_async])
|
||||
@dec_tool
|
||||
async def other_tool_async(y: int) -> str:
|
||||
"""Another async tool available to the runtime."""
|
||||
return str(y)
|
||||
|
||||
node = ToolNode([info_tool_async, other_tool_async])
|
||||
tool_call = {
|
||||
"name": "info_tool_async",
|
||||
"args": {"x": 1},
|
||||
@@ -2101,12 +2117,17 @@ async def test_tool_runtime_forwards_execution_info_and_server_info_async() -> N
|
||||
}
|
||||
msg = AIMessage("", tool_calls=[tool_call])
|
||||
config: RunnableConfig = {"configurable": {"__pregel_runtime": mock_runtime}}
|
||||
await node.ainvoke({"messages": [msg]}, config=config)
|
||||
result = await node.ainvoke({"messages": [msg]}, config=config)
|
||||
|
||||
assert result["messages"][-1].content == "ok"
|
||||
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"
|
||||
assert [tool.name for tool in captured["tools"]] == [
|
||||
"info_tool_async",
|
||||
"other_tool_async",
|
||||
]
|
||||
|
||||
|
||||
# --- InjectedToolArg security tests ---
|
||||
|
||||
Generated
+2
-2
@@ -268,7 +268,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph"
|
||||
version = "1.1.7"
|
||||
version = "1.1.9"
|
||||
source = { editable = "../langgraph" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
@@ -490,7 +490,7 @@ test = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.0.9"
|
||||
version = "1.0.10"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
|
||||
Generated
+2
-2
@@ -281,7 +281,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph"
|
||||
version = "1.1.7"
|
||||
version = "1.1.9"
|
||||
source = { editable = "../langgraph" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
@@ -413,7 +413,7 @@ test = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.0.9"
|
||||
version = "1.0.10"
|
||||
source = { editable = "../prebuilt" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
|
||||
Reference in New Issue
Block a user