Compare commits

..
Author SHA1 Message Date
Elior Nataf Lackritz 750f31482e fix(cli): cover every npm install lifecycle hook
npm runs prepublish, preprepare and postprepare on install too, so a project
using one of those would have had its install layer split and the hook would
run against a source tree that is not there yet.
2026-08-12 16:03:24 -04:00
Elior Nataf Lackritz 77fbf25d41 perf(cli): cache the Node install layer across source-only changes
The generated Node Dockerfile copies source before running the install, so
the first source change invalidates the install layer and every dependency
is reinstalled. A production build showed 0/3 steps cached with `npm ci`
rebuilding at 16.9s.

Copy `package.json` and the lockfile first instead. Falls back to the
current output when there is no lockfile, when an install lifecycle hook is
present, when a custom install command is set, or when the config is nested
in a workspace.
2026-08-12 15:39:54 -04:00
17 changed files with 390 additions and 852 deletions
-5
View File
@@ -77,10 +77,6 @@ __pypackages__/
# Environments
.env
.envrc
*.crt
*.key
*.pem
credentials.json
.venv
.venvs
env/
@@ -102,7 +98,6 @@ dmypy.json
.vercel
.turbo
node_modules/
.editorconfig
.scratch
.worktrees/
-8
View File
@@ -2,14 +2,6 @@
This repository is a monorepo. Each library lives in a subdirectory under `libs/`.
<corridor>
## Corridor security analysis
When Corridor's `analyzePlan` tool is available, create a plan and use the tool to analyze it before generating or modifying code. Apply the resulting security guidance before writing code.
</corridor>
When you modify code in any library, run the following commands in that library's directory before creating a pull request:
- `make format` run code formatters
-8
View File
@@ -2,14 +2,6 @@
This repository is a monorepo. Each library lives in a subdirectory under `libs/`.
<corridor>
## Corridor security analysis
Before generating or modifying code, create a plan and use Corridor's `analyzePlan` tool to analyze it. Apply the resulting security guidance before writing code.
</corridor>
When you modify code in any library, run the following commands in that library's directory before creating a pull request:
- `make format` run code formatters
-2
View File
@@ -103,8 +103,6 @@ The CLI uses a `langgraph.json` configuration file with these key settings:
}
```
Git dependencies should use credential-free URLs. The CLI conservatively scans direct `langgraph.json` dependencies, common Python package files, uv project and lock files, and common Node.js package and lock files for HTTP Git URLs with userinfo. This check is not exhaustive: generated Docker builds can copy other files, including nested requirement or constraint files, into image layers without scanning them. For private dependencies, provide short-lived credentials through your build environment's secret-backed Git credential helper. Do not store credentials in copied files such as `langgraph.json` or `pip_config_file`.
See the [full documentation](https://reference.langchain.com/python/langgraph-cli) for detailed configuration options.
## Development
+85 -96
View File
@@ -6,7 +6,6 @@ import re
import shlex
import textwrap
from collections import Counter
from collections.abc import Iterable
from typing import Literal, NamedTuple
import click
@@ -37,10 +36,6 @@ DISALLOWED_BUILD_COMMAND_CHARS = [
# This blocks background execution (cmd &) while allowing command
# chaining (cmd1 && cmd2) which is common in build commands.
_SINGLE_AMPERSAND_RE = re.compile(r"(?<!&)&(?:&&)*(?!&)")
_GIT_HTTP_AUTHORITY_RES = (
re.compile(r"git\+https?://(?P<authority>[^/\s\"']+)", re.I),
re.compile(r"\bgit\s*=\s*[\"']https?://(?P<authority>[^/\s\"']+)", re.I),
)
_API_VERSION_PATTERN = re.compile(
r"^(?P<major>\d+)"
r"(?:\.(?P<minor>\d+))?"
@@ -83,62 +78,6 @@ def has_disallowed_build_command_content(command: str) -> bool:
return False
def _has_git_http_url_userinfo(dependency: str) -> bool:
"""Check whether a Git HTTP URL contains userinfo."""
return any(
"@" in match.group("authority")
for pattern in _GIT_HTTP_AUTHORITY_RES
for match in pattern.finditer(dependency)
)
def _validate_git_http_url_userinfo(
values: Iterable[str], *, source: pathlib.Path | None = None
) -> None:
"""Reject credential-bearing Git HTTP URLs without echoing their values."""
if not any(_has_git_http_url_userinfo(value) for value in values):
return
message = (
"Git dependency URLs must not contain credentials or other URL "
"userinfo because generated Dockerfiles and image layers can retain "
"them. Use a credential-free Git URL and provide short-lived "
"credentials through your build environment's secret-backed Git "
"credential helper."
)
if source is not None:
message += f" Found in: {source}"
raise click.UsageError(message)
def _validate_git_http_url_userinfo_files(paths: Iterable[pathlib.Path]) -> None:
"""Reject credential-bearing Git HTTP URLs in dependency files."""
for path in paths:
path = path.resolve()
if not path.is_file():
continue
try:
contents = path.read_text(encoding="utf-8", errors="replace")
except OSError:
raise click.UsageError(
f"Could not inspect dependency file for embedded credentials: {path}"
) from None
_validate_git_http_url_userinfo([contents], source=path)
def _validate_local_dependency_files(config_path: pathlib.Path, config: Config) -> None:
"""Validate dependency files copied into a non-uv Python image."""
paths: list[pathlib.Path] = []
for dependency in config["dependencies"]:
if not isinstance(dependency, str) or not dependency.startswith("."):
continue
root = (config_path.parent / dependency).resolve()
paths.extend(
root / name
for name in ("requirements.txt", "pyproject.toml", "setup.py", "setup.cfg")
)
_validate_git_http_url_userinfo_files(paths)
MIN_PYTHON_VERSION = "3.11"
DEFAULT_PYTHON_VERSION = "3.11"
@@ -381,9 +320,7 @@ def _get_source_kind(config: Config) -> str | None:
return kind if isinstance(kind, str) else None
def validate_config(
config: Config, *, source_path: pathlib.Path | None = None
) -> Config:
def validate_config(config: Config) -> Config:
"""Validate a configuration dictionary."""
graphs = config.get("graphs", {})
@@ -478,15 +415,6 @@ def validate_config(
' "source": {"kind": "uv", "root": ".."}'
)
_validate_git_http_url_userinfo(
(
dependency
for dependency in config["dependencies"]
if isinstance(dependency, str)
),
source=source_path,
)
source = config.get("source")
source_kind = _get_source_kind(config)
if source is not None and not isinstance(source, dict):
@@ -681,7 +609,7 @@ def validate_config_file(config_path: pathlib.Path) -> Config:
"""Load and validate a configuration file."""
with open(config_path) as f:
config = json.load(f)
validated = validate_config(config, source_path=config_path.resolve())
validated = validate_config(config)
# Enforce the package.json doesn't enforce an
# incompatible Node.js version
if validated.get("node_version"):
@@ -1234,7 +1162,47 @@ def _build_runtime_env_vars(config: Config) -> list[str]:
return env_vars
def _get_node_pm_install_cmd(project_dir: pathlib.Path) -> str:
# npm runs all of these as part of an install, before the source would be copied.
_NODE_INSTALL_HOOKS = (
"preinstall",
"install",
"postinstall",
"prepublish",
"preprepare",
"prepare",
"postprepare",
)
def _splittable_node_manifests(
project_dir: pathlib.Path, lockfile: str | None
) -> list[str] | None:
"""Return manifests to copy before installing, or None if unsafe to split.
A lockfile is required: without one the install resolves versions at build
time, so a cached layer could pin an older resolution than a clean build.
"""
if lockfile is None:
return None
manifest = project_dir / "package.json"
try:
if not manifest.is_file():
return None
with open(manifest) as f:
package_json = json.load(f)
except (OSError, ValueError):
return None
if not isinstance(package_json, dict):
return None
scripts = package_json.get("scripts") or {}
if any(hook in scripts for hook in _NODE_INSTALL_HOOKS):
return None
return ["package.json", lockfile]
def _get_node_pm_install_cmd(project_dir: pathlib.Path) -> tuple[str, str | None]:
"""Return the install command and the lockfile it was chosen from."""
def test_file(file_name):
full_path = project_dir / file_name
try:
@@ -1273,13 +1241,19 @@ def _get_node_pm_install_cmd(project_dir: pathlib.Path) -> str:
if yarn:
install_cmd = "yarn install --frozen-lockfile"
lockfile = "yarn.lock"
elif pnpm:
install_cmd = "pnpm i --frozen-lockfile"
lockfile = "pnpm-lock.yaml"
elif npm:
install_cmd = "npm ci"
lockfile = "package-lock.json"
elif bun:
install_cmd = "bun i"
lockfile = "bun.lockb"
else:
# No lockfile, so the install resolves versions at build time.
lockfile = None
pkg_manager_name = get_pkg_manager_name()
if pkg_manager_name == "yarn":
@@ -1291,7 +1265,7 @@ def _get_node_pm_install_cmd(project_dir: pathlib.Path) -> str:
else:
install_cmd = "npm i"
return install_cmd
return install_cmd, lockfile
semver_pattern = re.compile(r":(\d+(?:\.\d+)?(?:\.\d+)?)(?:-|$)")
@@ -1352,7 +1326,6 @@ def python_config_to_docker(
api_version=api_version,
build_tools_to_uninstall=build_tools_to_uninstall,
)
_validate_local_dependency_files(config_path, config)
if pip_installer == "auto":
if _image_supports_uv(base_image):
pip_installer = "uv"
@@ -1496,7 +1469,7 @@ ADD {relpath} /deps/{name}
"# -- Installing JS dependencies --",
f"ENV NODE_VERSION={config.get('node_version') or DEFAULT_NODE_VERSION}",
f"WORKDIR {local_deps.working_dir}",
f"RUN {_get_node_pm_install_cmd(config_path.parent)} && tsx /api/langgraph_api/js/build.mts",
f"RUN {_get_node_pm_install_cmd(config_path.parent)[0]} && tsx /api/langgraph_api/js/build.mts",
"# -- End of JS dependencies install --",
]
)
@@ -1563,20 +1536,11 @@ def node_config_to_docker(
) -> tuple[str, dict[str, str]]:
# Calculate paths for monorepo support
install_root = (
pathlib.Path(build_context).resolve()
if build_context
else config_path.parent.resolve()
pathlib.Path(build_context).resolve() if build_context else config_path.parent
)
config_root = config_path.parent.resolve()
dependency_roots = (
(install_root, config_root) if install_root != config_root else (install_root,)
)
_validate_git_http_url_userinfo_files(
root / name
for root in dependency_roots
for name in ("package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml")
)
install_cmd = install_command or _get_node_pm_install_cmd(install_root)
detected_cmd, detected_lockfile = _get_node_pm_install_cmd(install_root)
install_cmd = install_command or detected_cmd
relative_workdir = ""
if build_context:
relative_workdir = _calculate_relative_workdir(config_path, build_context)
container_name = pathlib.Path(build_context).name
@@ -1614,16 +1578,41 @@ def node_config_to_docker(
else:
build_workdir = faux_path
source_root = faux_path if not build_context else container_root
# Excluded: a custom install command may read files we have not copied yet,
# and a nested config means workspace manifests the root copy would miss.
manifests = (
_splittable_node_manifests(install_root, detected_lockfile)
if install_command is None and not relative_workdir
else None
)
if manifests:
add_steps = [
*(f"ADD {name} {source_root}/{name}" for name in manifests),
"",
f"WORKDIR {install_workdir}",
"",
install_step,
"",
f"ADD . {source_root}",
]
else:
add_steps = [
f"ADD . {source_root}",
"",
f"WORKDIR {install_workdir}",
"",
install_step,
]
docker_file_contents = [
f"FROM {image_str}",
"",
os.linesep.join(config["dockerfile_lines"]),
"",
f"ADD . {faux_path if not build_context else container_root}",
"",
f"WORKDIR {install_workdir}",
"",
install_step,
*add_steps,
"",
os.linesep.join(env_vars),
"",
+1 -5
View File
@@ -650,8 +650,7 @@ class Config(TypedDict, total=False):
pip_config_file: str | None
"""Optional. Path to a pip config file (e.g., "/etc/pip.conf" or "pip.ini") for controlling
package installation (custom indices, timeouts, etc.). The file is copied into the
generated image, so it must not contain credentials or other secrets.
package installation (custom indices, credentials, etc.).
Only relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.
"""
@@ -690,9 +689,6 @@ class Config(TypedDict, total=False):
- "." or "./src" if you have a local Python package
- str (aka "anthropic") for a PyPI package
- "git+https://github.com/org/repo.git@main" for a Git-based package
Git HTTP URLs must not contain userinfo such as a username or token. For private
dependencies, provide short-lived credentials through the build environment's
secret-backed Git credential helper.
Defaults to an empty list, meaning no additional packages installed beyond your base environment.
This field is not supported when `source.kind` is `uv`.
+1 -27
View File
@@ -880,7 +880,6 @@ def python_config_to_docker_uv_lock(
_get_node_pm_install_cmd,
_get_pip_cleanup_lines,
_image_supports_uv,
_validate_git_http_url_userinfo_files,
docker_tag,
)
@@ -891,20 +890,11 @@ def python_config_to_docker_uv_lock(
)
config_root = config_path.parent.resolve()
source_root = config["source"].get("root", ".")
project_root = (config_root / source_root).resolve()
_validate_git_http_url_userinfo_files(
[project_root / "pyproject.toml", project_root / "uv.lock"]
)
install_cmd = "uv pip install --system"
_, global_reqs_pip_install, pip_config_file_str = _build_python_install_commands(
config, install_cmd
)
plan = _plan_uv_lock_workspace(config_path, config)
_validate_git_http_url_userinfo_files(
package.pyproject_path for package in plan.install_order
)
_update_uv_lock_graph_paths(config_path, config, plan)
for section, key in [
@@ -980,22 +970,6 @@ def python_config_to_docker_uv_lock(
f"{uv_export_project_dir}/uv.lock",
)
)
for package_root in sorted(
plan.all_workspace_roots,
key=lambda root: root.as_posix(),
):
if package_root == plan.project_root:
continue
package_relative_path = pathlib.PurePosixPath(
package_root.relative_to(plan.project_root).as_posix()
)
package_pyproject_path = package_relative_path / "pyproject.toml"
docker_plan.add_raw(
copy_from_project_root(
package_pyproject_path,
f"{uv_export_project_dir}/{package_pyproject_path.as_posix()}",
)
)
docker_plan.add_instruction("WORKDIR", uv_export_project_dir)
docker_plan.add_instruction(
"RUN",
@@ -1045,7 +1019,7 @@ def python_config_to_docker_uv_lock(
docker_plan.add_instruction("WORKDIR", plan.working_dir)
docker_plan.add_instruction(
"RUN",
f"{_get_node_pm_install_cmd(plan.target_root)} && "
f"{_get_node_pm_install_cmd(plan.target_root)[0]} && "
"tsx /api/langgraph_api/js/build.mts",
)
docker_plan.add_raw("# -- End of JS dependencies install --")
+2 -2
View File
@@ -28,7 +28,7 @@
"type": "null"
}
],
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
},
"_INTERNAL_docker_tag": {
"anyOf": [
@@ -270,7 +270,7 @@
"type": "null"
}
],
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
},
"_INTERNAL_docker_tag": {
"anyOf": [
+2 -2
View File
@@ -28,7 +28,7 @@
"type": "null"
}
],
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
},
"_INTERNAL_docker_tag": {
"anyOf": [
@@ -270,7 +270,7 @@
"type": "null"
}
],
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
},
"_INTERNAL_docker_tag": {
"anyOf": [
+140 -250
View File
@@ -255,243 +255,6 @@ def test_validate_config():
)
@pytest.mark.parametrize(
"dependency",
[
"git+https://user:secret-token@github.com/org/private.git@main",
"private-package @ git+http://token@github.com/org/private.git",
"git+HTTPS://user%40example.com:secret%2Ftoken@github.com/org/private.git",
"git+https://${GIT_TOKEN}@github.com/org/private.git",
],
)
def test_validate_config_rejects_git_http_url_userinfo(dependency: str):
with pytest.raises(click.UsageError) as exc_info:
validate_config(
{
"python_version": "3.11",
"dependencies": [dependency],
"graphs": {"agent": "./agent.py:graph"},
}
)
message = str(exc_info.value)
assert "must not contain credentials or other URL userinfo" in message
assert "secret-token" not in message
assert "secret%2Ftoken" not in message
def test_validate_config_file_reports_source_for_git_http_url_userinfo(
tmp_path: pathlib.Path,
):
config_path = tmp_path / "langgraph.json"
config_path.write_text(
json.dumps(
{
"python_version": "3.11",
"dependencies": ["git+https://secret-token@github.com/org/private.git"],
"graphs": {"agent": "./agent.py:graph"},
}
)
)
with pytest.raises(click.UsageError) as exc_info:
validate_config_file(config_path)
message = str(exc_info.value)
assert "secret-token" not in message
assert f"Found in: {config_path.resolve()}" in message
@pytest.mark.parametrize(
"manifest", ["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"]
)
def test_config_to_docker_rejects_git_http_url_userinfo_in_node_files(
tmp_path: pathlib.Path, manifest: str
):
config_path = tmp_path / "langgraph.json"
config_path.write_text("{}\n")
(tmp_path / "agent.js").write_text("export const graph = {};\n")
(tmp_path / "package.json").write_text('{"name":"agent"}\n')
(tmp_path / manifest).write_text(
'"priv": "git+https://user:secret-token@github.com/org/private.git"\n'
)
config = validate_config(
{
"node_version": "20",
"graphs": {"agent": "./agent.js:graph"},
}
)
with pytest.raises(click.UsageError) as exc_info:
config_to_docker(
config_path,
config,
base_image="langchain/langgraphjs-api",
)
message = str(exc_info.value)
assert "must not contain credentials or other URL userinfo" in message
assert "secret-token" not in message
assert f"Found in: {(tmp_path / manifest).resolve()}" in message
def test_config_to_docker_allows_node_git_urls_without_http_userinfo(
tmp_path: pathlib.Path,
):
config_path = tmp_path / "langgraph.json"
config_path.write_text("{}\n")
(tmp_path / "agent.js").write_text("export const graph = {};\n")
(tmp_path / "package.json").write_text(
'{"dependencies":{"public":"git+https://github.com/org/public.git"}}\n'
)
config = validate_config(
{
"node_version": "20",
"graphs": {"agent": "./agent.js:graph"},
}
)
docker, _ = config_to_docker(
config_path,
config,
base_image="langchain/langgraphjs-api",
)
assert f"ADD . /deps/{tmp_path.name}" in docker
def test_config_to_docker_rejects_git_http_url_userinfo_in_node_workspace(
tmp_path: pathlib.Path,
):
config_root = tmp_path / "apps" / "agent"
config_root.mkdir(parents=True)
config_path = config_root / "langgraph.json"
config_path.write_text("{}\n")
(config_root / "agent.js").write_text("export const graph = {};\n")
(config_root / "package.json").write_text(
'{"dependencies":{"priv":"git+https://secret-token@github.com/org/private.git"}}\n'
)
(tmp_path / "package.json").write_text('{"name":"workspace"}\n')
config = validate_config(
{
"node_version": "20",
"graphs": {"agent": "./agent.js:graph"},
}
)
with pytest.raises(click.UsageError) as exc_info:
config_to_docker(
config_path,
config,
base_image="langchain/langgraphjs-api",
build_context=str(tmp_path),
)
message = str(exc_info.value)
assert "secret-token" not in message
assert f"Found in: {(config_root / 'package.json').resolve()}" in message
@pytest.mark.parametrize(
"dependency",
[
"git+https://github.com/org/public.git@main",
"private-package @ git+https://github.com/org/private.git@main",
"git+ssh://git@github.com/org/private.git@main",
],
)
def test_validate_config_allows_git_urls_without_http_userinfo(dependency: str):
config = validate_config(
{
"python_version": "3.11",
"dependencies": [dependency],
"graphs": {"agent": "./agent.py:graph"},
}
)
assert config["dependencies"] == [dependency]
def test_config_to_docker_rejects_git_http_url_userinfo_in_requirements(
tmp_path: pathlib.Path,
):
config_path = tmp_path / "langgraph.json"
config_path.write_text("{}\n")
(tmp_path / "agent.py").write_text("graph = object()\n")
(tmp_path / "requirements.txt").write_text(
"private @ git+https://secret-token@github.com/org/private.git\n"
)
config = validate_config(
{
"python_version": "3.11",
"dependencies": ["."],
"graphs": {"agent": "./agent.py:graph"},
}
)
with pytest.raises(click.UsageError) as exc_info:
config_to_docker(
config_path,
config,
base_image="langchain/langgraph-api:0.2.47",
)
message = str(exc_info.value)
assert "must not contain credentials or other URL userinfo" in message
assert "secret-token" not in message
assert f"Found in: {(tmp_path / 'requirements.txt').resolve()}" in message
@pytest.mark.parametrize("manifest", ["pyproject.toml", "uv.lock"])
def test_config_to_docker_rejects_git_http_url_userinfo_in_uv_files(
tmp_path: pathlib.Path, manifest: str
):
config_path = tmp_path / "langgraph.json"
config_path.write_text("{}\n")
(tmp_path / "src").mkdir()
(tmp_path / "src" / "agent.py").write_text("graph = object()\n")
pyproject = textwrap.dedent(
"""
[project]
name = "agent"
version = "0.1.0"
dependencies = ["private"]
[tool.uv.sources]
private = { git = "https://github.com/org/private.git" }
"""
).strip()
uv_lock = "# uv lock file\n"
if manifest == "pyproject.toml":
pyproject = pyproject.replace(
"https://github.com", "https://secret-token@github.com"
)
else:
uv_lock += (
'source = { git = "https://secret-token@github.com/org/private.git" }\n'
)
(tmp_path / "pyproject.toml").write_text(pyproject + "\n")
(tmp_path / "uv.lock").write_text(uv_lock)
config = validate_config(
{
"python_version": "3.11",
"graphs": {"agent": "./src/agent.py:graph"},
"source": {"kind": "uv"},
}
)
with pytest.raises(click.UsageError) as exc_info:
config_to_docker(
config_path,
config,
base_image="langchain/langgraph-api:0.2.47",
)
message = str(exc_info.value)
assert "must not contain credentials or other URL userinfo" in message
assert "secret-token" not in message
def test_validate_config_image_distro():
"""Test validation of image_distro field."""
# Valid image_distro values should work
@@ -1640,19 +1403,6 @@ def test_config_to_docker_uv_lock():
"COPY --from=uv-workspace-root uv.lock /tmp/uv_export/project/uv.lock"
in docker
)
workspace_pyprojects = [
"apps/agent/pyproject.toml",
"libs/extra/pyproject.toml",
"libs/shared/pyproject.toml",
]
export_instruction = "RUN uv export --package agent"
for pyproject_path in workspace_pyprojects:
copy_instruction = (
"COPY --from=uv-workspace-root "
f"{pyproject_path} /tmp/uv_export/project/{pyproject_path}"
)
assert copy_instruction in docker
assert docker.index(copy_instruction) < docker.index(export_instruction)
assert additional_contexts == {"uv-workspace-root": str(project_root.resolve())}
assert (
@@ -3674,3 +3424,143 @@ class TestHasDisallowedBuildCommandContent:
)
def test_valid_commands_allowed(self, cmd: str) -> None:
assert not has_disallowed_build_command_content(cmd)
class TestNodeDependencyLayerOrdering:
"""Dependency manifests are copied before source so the install layer caches.
Without this the first source change invalidates the install, and a JS
deployment reinstalls every dependency on every push.
"""
def _project(
self,
tmp_path: pathlib.Path,
*,
lockfile: str | None,
scripts: dict[str, str] | None = None,
) -> pathlib.Path:
package_json: dict = {"name": "agent"}
if scripts:
package_json["scripts"] = scripts
(tmp_path / "package.json").write_text(json.dumps(package_json))
if lockfile:
(tmp_path / lockfile).write_text("")
(tmp_path / "graphs").mkdir()
(tmp_path / "graphs" / "agent.js").write_text("")
config_path = tmp_path / "langgraph.json"
config_path.write_text("{}")
return config_path
def _dockerfile(self, config_path: pathlib.Path, **kwargs) -> str:
actual, _ = config_to_docker(
config_path,
validate_config(
{"node_version": "20", "graphs": {"agent": "./graphs/agent.js:graph"}}
),
base_image="langchain/langgraphjs-api",
**kwargs,
)
return clean_empty_lines(actual)
def test_manifests_copied_before_install(self, tmp_path: pathlib.Path) -> None:
config_path = self._project(tmp_path, lockfile="package-lock.json")
lines = self._dockerfile(config_path).splitlines()
add_manifest = lines.index(
f"ADD package.json /deps/{tmp_path.name}/package.json"
)
add_lock = lines.index(
f"ADD package-lock.json /deps/{tmp_path.name}/package-lock.json"
)
install = lines.index("RUN npm ci")
add_source = lines.index(f"ADD . /deps/{tmp_path.name}")
assert add_manifest < install
assert add_lock < install
assert install < add_source
def test_lockfile_choice_follows_package_manager(
self, tmp_path: pathlib.Path
) -> None:
config_path = self._project(tmp_path, lockfile="pnpm-lock.yaml")
dockerfile = self._dockerfile(config_path)
assert f"ADD pnpm-lock.yaml /deps/{tmp_path.name}/pnpm-lock.yaml" in dockerfile
assert "package-lock.json" not in dockerfile
def test_no_lockfile_keeps_source_first(self, tmp_path: pathlib.Path) -> None:
# No lockfile means the install resolves at build time, so caching it is wrong.
config_path = self._project(tmp_path, lockfile=None)
lines = self._dockerfile(config_path).splitlines()
assert lines.index(f"ADD . /deps/{tmp_path.name}") < lines.index("RUN npm i")
assert not any(line.startswith("ADD package.json") for line in lines)
def test_nested_config_keeps_source_first(self, tmp_path: pathlib.Path) -> None:
# A workspace keeps manifests in subdirectories the root copy would miss.
root = tmp_path / "repo"
root.mkdir()
(root / "package.json").write_text(json.dumps({"name": "root"}))
(root / "package-lock.json").write_text("")
pkg = root / "packages" / "agent"
pkg.mkdir(parents=True)
(pkg / "graphs").mkdir()
(pkg / "graphs" / "agent.js").write_text("")
config_path = pkg / "langgraph.json"
config_path.write_text("{}")
lines = self._dockerfile(config_path, build_context=str(root)).splitlines()
assert lines.index("ADD . /deps/repo") < lines.index("RUN npm ci")
assert not any(line.startswith("ADD package.json") for line in lines)
def test_custom_install_command_keeps_source_first(
self, tmp_path: pathlib.Path
) -> None:
# A custom command may read files the manifest copy would not include.
config_path = self._project(tmp_path, lockfile="package-lock.json")
lines = self._dockerfile(
config_path,
install_command="npm run bootstrap",
build_context=str(tmp_path),
).splitlines()
assert lines.index(f"ADD . /deps/{tmp_path.name}") < lines.index(
"RUN npm run bootstrap"
)
@pytest.mark.parametrize(
"hook",
[
"preinstall",
"install",
"postinstall",
"prepublish",
"preprepare",
"prepare",
"postprepare",
],
)
def test_install_hook_keeps_source_first(
self, tmp_path: pathlib.Path, hook: str
) -> None:
# A hook referencing a project file would hit ENOENT: source is not copied yet.
config_path = self._project(
tmp_path,
lockfile="package-lock.json",
scripts={hook: "node scripts/setup.js"},
)
lines = self._dockerfile(config_path).splitlines()
assert lines.index(f"ADD . /deps/{tmp_path.name}") < lines.index("RUN npm ci")
assert not any(line.startswith("ADD package.json") for line in lines)
def test_only_the_chosen_lockfile_is_copied(self, tmp_path: pathlib.Path) -> None:
# Install picks yarn, so copying the npm lockfile would bust the cache for nothing.
config_path = self._project(tmp_path, lockfile="yarn.lock")
(tmp_path / "package-lock.json").write_text("")
dockerfile = self._dockerfile(config_path)
assert f"ADD yarn.lock /deps/{tmp_path.name}/yarn.lock" in dockerfile
assert "ADD package-lock.json" not in dockerfile
+6 -6
View File
@@ -266,20 +266,20 @@ wheels = [
[[package]]
name = "langgraph-checkpoint"
version = "4.2.0"
version = "4.0.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "langchain-core" },
{ name = "ormsgpack" },
]
sdist = { url = "https://files.pythonhosted.org/packages/dc/e1/089c4c9e0a2fec7f883f82ae8e6a727138d50074cfeb6644bc2d13b1019b/langgraph_checkpoint-4.2.0.tar.gz", hash = "sha256:51a593b6bee684b0818e5d6e58e28ab340c6db7794575056ce7bd1b746a84ed7", size = 180239, upload-time = "2026-08-07T20:05:03.756Z" }
sdist = { url = "https://files.pythonhosted.org/packages/b1/44/a8df45d1e8b4637e29789fa8bae1db022c953cc7ac80093cfc52e923547e/langgraph_checkpoint-4.0.1.tar.gz", hash = "sha256:b433123735df11ade28829e40ce25b9be614930cd50245ff2af60629234befd9", size = 158135, upload-time = "2026-02-27T21:06:16.092Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/05/71/3b475f09bd57d3a5649792c66353312b4432afd843f301739dfcebd157f0/langgraph_checkpoint-4.2.0-py3-none-any.whl", hash = "sha256:0547fd228935a0b758865de3a3d6d7a2537c308895d0f9ab092ce9151b5da942", size = 56833, upload-time = "2026-08-07T20:05:02.655Z" },
{ url = "https://files.pythonhosted.org/packages/65/4c/09a4a0c42f5d2fc38d6c4d67884788eff7fd2cfdf367fdf7033de908b4c0/langgraph_checkpoint-4.0.1-py3-none-any.whl", hash = "sha256:e3adcd7a0e0166f3b48b8cf508ce0ea366e7420b5a73aa81289888727769b034", size = 50453, upload-time = "2026-02-27T21:06:14.293Z" },
]
[[package]]
name = "langgraph-checkpoint-postgres"
version = "3.1.1"
version = "3.0.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "langgraph-checkpoint" },
@@ -287,9 +287,9 @@ dependencies = [
{ name = "psycopg" },
{ name = "psycopg-pool" },
]
sdist = { url = "https://files.pythonhosted.org/packages/06/92/1e8959f8cd1b56e672fde3227f6fd642be85af6c5fd662d73921074aa39d/langgraph_checkpoint_postgres-3.1.1.tar.gz", hash = "sha256:d320e147ddad8c374cd546df0b52b532dd54d0541dd9fd23fc738cbd5de76f41", size = 150413, upload-time = "2026-07-30T19:15:39.014Z" }
sdist = { url = "https://files.pythonhosted.org/packages/95/7a/8f439966643d32111248a225e6cb33a182d07c90de780c4dbfc1e0377832/langgraph_checkpoint_postgres-3.0.5.tar.gz", hash = "sha256:a8fd7278a63f4f849b5cbc7884a15ca8f41e7d5f7467d0a66b31e8c24492f7eb", size = 127856, upload-time = "2026-03-18T21:25:29.785Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/03/32/ba457698a48a0e18d786caa770033067049fbe36d6846f8e50f13b594b51/langgraph_checkpoint_postgres-3.1.1-py3-none-any.whl", hash = "sha256:6e353aecd8150de144fef8e51a49076f58b7d6830d4cf51392b7ad4d79832ba7", size = 50778, upload-time = "2026-07-30T19:15:37.405Z" },
{ url = "https://files.pythonhosted.org/packages/e8/87/b0f98b33a67204bca9d5619bcd9574222f6b025cf3c125eedcec9a50ecbc/langgraph_checkpoint_postgres-3.0.5-py3-none-any.whl", hash = "sha256:86d7040a88fd70087eaafb72251d796696a0a2d856168f5c11ef620771411552", size = 42907, upload-time = "2026-03-18T21:25:28.75Z" },
]
[[package]]
+141 -71
View File
@@ -1,10 +1,11 @@
from __future__ import annotations
import dis
import ast
import inspect
import re
import textwrap
from collections.abc import Callable, Sequence
from functools import partial
from types import CodeType, FunctionType
from typing import Any
from langchain_core.runnables import (
@@ -16,6 +17,7 @@ from langchain_core.runnables import (
from langchain_core.runnables.base import RunnableBindingBase
from langchain_core.runnables.config import run_in_executor
from langgraph.checkpoint.base import ChannelVersions
from typing_extensions import override
from langgraph._internal._runnable import RunnableCallable, RunnableSeq
from langgraph._internal._timeout import sync_timeout_unsupported
@@ -135,87 +137,155 @@ def validate_timeout_supported(runnable: Runnable, *, name: str) -> None:
raise sync_timeout_unsupported(name)
# Values treated as dead ends when deciding whether to walk a function's
# bytecode. A container can hold a graph, but `find_subgraph_pregel` does not
# look inside one, so skipping it costs nothing while that holds. Matched by
# exact type, since a subclass of a builtin can carry attributes.
_LEAF_TYPES = frozenset(
{
int,
float,
complex,
bool,
str,
bytes,
bytearray,
list,
tuple,
dict,
set,
frozenset,
type(None),
}
)
def get_function_nonlocals(func: Callable) -> list[Any]:
"""Get the values a function reaches from outside its own scope.
"""Get the nonlocal variables accessed by a function.
Args:
func: The function to check.
Returns:
Every captured cell value, the globals the function names, and each
value along an attribute path it loads. Over-approximates: a value can
come back without the function reaching it at runtime.
List[Any]: The nonlocal variables accessed by the function.
"""
func = getattr(func, "__func__", func) # bound method -> function
wrapped = getattr(func, "__wrapped__", None)
if callable(wrapped):
func = getattr(wrapped, "__func__", wrapped)
if not isinstance(func, FunctionType):
try:
code = inspect.getsource(func)
tree = ast.parse(textwrap.dedent(code))
visitor = FunctionNonLocals()
visitor.visit(tree)
values: list[Any] = []
closure = (
inspect.getclosurevars(func.__wrapped__)
if hasattr(func, "__wrapped__") and callable(func.__wrapped__)
else inspect.getclosurevars(func)
)
candidates = {**closure.globals, **closure.nonlocals}
for k, v in candidates.items():
if k in visitor.nonlocals:
values.append(v)
for kk in visitor.nonlocals:
if "." in kk and kk.startswith(k):
vv = v
for part in kk.split(".")[1:]:
if vv is None:
break
else:
try:
vv = getattr(vv, part)
except AttributeError:
break
else:
values.append(vv)
except (SyntaxError, TypeError, OSError, SystemError):
return []
code = func.__code__
cells: dict[str, Any] = {}
for name, cell in zip(code.co_freevars, func.__closure__ or ()):
try:
cells[name] = cell.cell_contents
except ValueError:
continue # empty cell: a recursive def not yet bound
# Every captured value counts, referenced or not: over-declaring costs an
# introspection entry, under-declaring drops the subgraph's checkpoints and
# stream events. Checking each cell against the bytecode would cost more and
# only trade the cheap error for the expensive one.
values: list[Any] = list(cells.values())
global_ns = func.__globals__
globals_ = {name: global_ns[name] for name in code.co_names if name in global_ns}
if all(type(v) in _LEAF_TYPES for v in (*cells.values(), *globals_.values())):
return values
# Nested code objects hold the references made by inner defs, lambdas and
# comprehensions, which resolve against the namespaces gathered above.
codes = [code]
for c in codes:
codes.extend(k for k in c.co_consts if isinstance(k, CodeType))
value: Any = None
for instruction in dis.get_instructions(c):
opname = instruction.opname
if opname == "LOAD_GLOBAL":
value = globals_.get(instruction.argval)
elif opname == "LOAD_DEREF":
value = cells.get(instruction.argval)
elif opname in ("LOAD_ATTR", "LOAD_METHOD"):
value = getattr(value, instruction.argval, None)
else:
value = None # anything else ends the chain: `a, b.c` is not `a.c`
continue
if value is not None:
values.append(value)
return values
class FunctionNonLocals(ast.NodeVisitor):
"""Get the nonlocal variables accessed of a function."""
def __init__(self) -> None:
self.nonlocals: set[str] = set()
@override
def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
"""Visit a function definition.
Args:
node: The node to visit.
Returns:
Any: The result of the visit.
"""
visitor = NonLocals()
visitor.visit(node)
self.nonlocals.update(visitor.loads - visitor.stores)
@override
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any:
"""Visit an async function definition.
Args:
node: The node to visit.
Returns:
Any: The result of the visit.
"""
visitor = NonLocals()
visitor.visit(node)
self.nonlocals.update(visitor.loads - visitor.stores)
@override
def visit_Lambda(self, node: ast.Lambda) -> Any:
"""Visit a lambda function.
Args:
node: The node to visit.
Returns:
Any: The result of the visit.
"""
visitor = NonLocals()
visitor.visit(node)
self.nonlocals.update(visitor.loads - visitor.stores)
class NonLocals(ast.NodeVisitor):
"""Get nonlocal variables accessed."""
def __init__(self) -> None:
self.loads: set[str] = set()
self.stores: set[str] = set()
@override
def visit_Name(self, node: ast.Name) -> Any:
"""Visit a name node.
Args:
node: The node to visit.
Returns:
Any: The result of the visit.
"""
if isinstance(node.ctx, ast.Load):
self.loads.add(node.id)
elif isinstance(node.ctx, ast.Store):
self.stores.add(node.id)
@override
def visit_Attribute(self, node: ast.Attribute) -> Any:
"""Visit an attribute node.
Args:
node: The node to visit.
Returns:
Any: The result of the visit.
"""
if isinstance(node.ctx, ast.Load):
parent = node.value
attr_expr = node.attr
while isinstance(parent, ast.Attribute):
attr_expr = parent.attr + "." + attr_expr
parent = parent.value
if isinstance(parent, ast.Name):
self.loads.add(parent.id + "." + attr_expr)
self.loads.discard(parent.id)
elif isinstance(parent, ast.Call):
if isinstance(parent.func, ast.Name):
self.loads.add(parent.func.id)
else:
parent = parent.func
attr_expr = ""
while isinstance(parent, ast.Attribute):
if attr_expr:
attr_expr = parent.attr + "." + attr_expr
else:
attr_expr = parent.attr
parent = parent.value
if isinstance(parent, ast.Name):
self.loads.add(parent.id + "." + attr_expr)
def is_xxh3_128_hexdigest(value: str) -> bool:
"""Check if the given string matches the format of xxh3_128_hexdigest."""
return bool(re.fullmatch(r"[0-9a-f]{32}", value))
@@ -1,286 +0,0 @@
"""Tests for subgraph auto-detection (`pregel/_utils.py`).
Detection failing is silent — the graph still runs, only introspection goes
quiet — so every shape a node can hold a graph in is pinned here. The expected
values are what the source-parsing implementation this replaced produced for
the same shapes, except for `sourceless`, whose source it could not read,
`empty_closure_cell`, on which it raised, and `unreachable_attribute_chain`,
where it reported a graph that dropped code could never invoke.
"""
import functools
import operator
from typing import Annotated, Any
import pytest
from typing_extensions import TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.pregel._utils import get_function_nonlocals
class State(TypedDict):
log: Annotated[list, operator.add]
def _leaf(tag: str) -> Any:
"""Return a compiled graph that reports itself as `tag`."""
builder = StateGraph(State)
builder.add_node(tag, lambda s: {"log": [tag]})
builder.add_edge(START, tag)
builder.add_edge(tag, END)
compiled = builder.compile()
compiled.name = tag
return compiled
def _detect(node: Any) -> str | None:
"""Return the name of the subgraph detected for `node`, or None."""
builder = StateGraph(State)
builder.add_node("n", node)
builder.add_edge(START, "n")
builder.add_edge("n", END)
subgraphs = builder.compile().nodes["n"].subgraphs
return getattr(subgraphs[0], "name", "?") if subgraphs else None
class _Box:
def __init__(self, payload: Any) -> None:
self.payload = payload
class _ListSubclass(list):
pass
class _MethodHolder:
def __init__(self) -> None:
self.graph = _leaf("via_self")
def as_node(self, state: State) -> Any:
return self.graph.invoke(state)
MODULE_GRAPH = _leaf("module_global")
CHAIN = _Box(_Box(_leaf("attr_chain")))
GRAPH_IN_PLAIN_LIST = [_leaf("in_list")]
METHOD_HOLDER = _MethodHolder()
def closure_capture() -> Any:
sub = _leaf("closure")
def node(state: State) -> Any:
return sub.invoke(state)
return node
def module_global() -> Any:
def node(state: State) -> Any:
return MODULE_GRAPH.invoke(state)
return node
def attribute_chain() -> Any:
def node(state: State) -> Any:
return CHAIN.payload.payload.invoke(state)
return node
def nested_def_captured_attribute() -> Any:
"""A chain on a captured holder, named only inside a nested code object.
The captured value is the holder, not the graph, so the chain itself has to
be recovered from the nested scope.
"""
holder = _Box(_leaf("nested_captured"))
def node(state: State) -> Any:
def inner() -> Any:
return holder.payload.invoke(state)
return inner()
return node
def unreachable_branch() -> Any:
"""A captured graph referenced only from code the compiler removes."""
sub = _leaf("unreachable")
def node(state: State) -> Any:
if False:
sub.invoke(state)
return {"log": []}
return node
def unreachable_attribute_chain() -> Any:
"""A graph named only along an attribute path the compiler dropped.
The closure keeps `holder`, but the `.payload` load is gone. The source
parser reported this one; dropped code cannot invoke anything, so that was
a phantom rather than a detection.
"""
holder = _Box(_leaf("unreachable_attr"))
def node(state: State) -> Any:
if False:
holder.payload.invoke(state)
return {"log": []}
return node
def wrapper_referencing_nothing() -> Any:
"""A wrapper whose own scope holds nothing, so only `__wrapped__` leads on.
`functools.wraps` would leave the wrapper closing over the inner function;
setting the attribute by hand does not.
"""
sub = _leaf("via_wrapped")
def inner(state: State) -> Any:
return sub.invoke(state)
def wrapper(state: State) -> Any:
return {"log": []}
wrapper.__wrapped__ = inner
return wrapper
def captured_list_subclass() -> Any:
"""A `list` subclass is not a leaf: it can carry a graph as an attribute."""
holder = _ListSubclass()
holder.payload = _leaf("list_subclass")
def node(state: State) -> Any:
return holder.payload.invoke(state)
return node
def empty_closure_cell() -> Any:
"""An unassigned closure variable leaves a cell that cannot be read."""
sub = _leaf("beside_empty_cell")
def node(state: State) -> Any:
return unassigned, sub.invoke(state)
return node
unassigned = 1 # never runs, so the cell it creates is never filled
def sourceless() -> Any:
"""A node compiled without a source file, which `getsource` could not read."""
namespace: dict[str, Any] = {"SOURCELESS": _leaf("sourceless")}
exec(
compile(
"def node(state):\n return SOURCELESS.invoke(state)", "<test>", "exec"
),
namespace,
)
return namespace["node"]
async def _async_node(state: State) -> Any:
return await MODULE_GRAPH.ainvoke(state)
def async_node() -> Any:
return _async_node
def no_subgraph() -> Any:
"""Nothing but leaf values in reach, so the bytecode walk is skipped."""
def node(state: State) -> Any:
return {"log": [len("abc") + 1]}
return node
def recombined_names() -> Any:
"""Loads `CHAIN.payload` and `local.payload`, never `CHAIN.payload.payload`."""
def node(state: State) -> Any:
local = _Box("not a graph")
return {"log": [CHAIN.payload, local.payload]}
return node
def broken_attribute_chain() -> Any:
holder = _Box("a string, so `.payload.missing` cannot resolve")
def node(state: State) -> Any:
return holder.payload.missing.invoke(state)
return node
def nested_def_global() -> Any:
"""A global named only in a nested code object: out of reach, as before."""
def node(state: State) -> Any:
def inner() -> Any:
return MODULE_GRAPH.invoke(state)
return inner()
return node
def graph_in_plain_list() -> Any:
def node(state: State) -> Any:
return GRAPH_IN_PLAIN_LIST[0].invoke(state)
return node
def bound_method_self() -> Any:
return METHOD_HOLDER.as_node
@pytest.mark.parametrize(
("factory", "expected"),
[
(closure_capture, "closure"),
(module_global, "module_global"),
(attribute_chain, "attr_chain"),
(nested_def_captured_attribute, "nested_captured"),
(unreachable_branch, "unreachable"),
(wrapper_referencing_nothing, "via_wrapped"),
(captured_list_subclass, "list_subclass"),
(empty_closure_cell, "beside_empty_cell"),
(sourceless, "sourceless"),
(async_node, "module_global"),
# Shapes no reference chain reaches: a subscript, an instance attribute
# of `self`, a global named only in a nested scope, and an attribute
# path the compiler dropped.
(no_subgraph, None),
(recombined_names, None),
(broken_attribute_chain, None),
(nested_def_global, None),
(graph_in_plain_list, None),
(bound_method_self, None),
(unreachable_attribute_chain, None),
],
ids=lambda value: value.__name__ if callable(value) else str(value),
)
def test_subgraph_detection(factory: Any, expected: str | None) -> None:
assert _detect(factory()) == expected
@pytest.mark.parametrize(
"candidate",
[functools.partial(lambda state, extra: {"log": [extra]}, extra="x"), len],
ids=["partial", "builtin"],
)
def test_callables_without_a_code_object_are_handled(candidate: Any) -> None:
assert get_function_nonlocals(candidate) == []
+3 -10
View File
@@ -1,15 +1,8 @@
from langgraph_sdk.auth import Auth
from langgraph_sdk.client import get_client, get_sync_client
from langgraph_sdk.encryption import Encryption
from langgraph_sdk.encryption.types import DecryptResult, EncryptionContext
from langgraph_sdk.encryption.types import EncryptionContext
__version__ = "0.4.3"
__version__ = "0.4.2"
__all__ = [
"Auth",
"DecryptResult",
"Encryption",
"EncryptionContext",
"get_client",
"get_sync_client",
]
__all__ = ["Auth", "Encryption", "EncryptionContext", "get_client", "get_sync_client"]
@@ -18,9 +18,6 @@ import warnings
from langgraph_sdk.encryption import types
_BlobDecryptorT = typing.TypeVar("_BlobDecryptorT", bound=types.BlobDecryptor)
_JsonDecryptorT = typing.TypeVar("_JsonDecryptorT", bound=types.JsonDecryptor)
class LangGraphBetaWarning(UserWarning):
"""Warning for beta features in LangGraph SDK."""
@@ -144,7 +141,7 @@ class _DecryptDecorators:
def __init__(self, parent: Encryption):
self._parent = parent
def blob(self, fn: _BlobDecryptorT) -> _BlobDecryptorT:
def blob(self, fn: types.BlobDecryptor) -> types.BlobDecryptor:
"""Register a blob decryption handler.
The handler will be called to decrypt opaque data like checkpoint blobs.
@@ -152,9 +149,7 @@ class _DecryptDecorators:
Example:
```python
@encryption.decrypt.blob
async def decrypt_blob(
ctx: EncryptionContext, blob: bytes
) -> bytes | DecryptResult[bytes]:
async def decrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
# Decrypt the blob using your encryption service
return decrypted_blob
```
@@ -175,15 +170,13 @@ class _DecryptDecorators:
self._parent._blob_decryptor = fn
return fn
def json(self, fn: _JsonDecryptorT) -> _JsonDecryptorT:
def json(self, fn: types.JsonDecryptor) -> types.JsonDecryptor:
"""Register the JSON decryption handler.
Example:
```python
@encryption.decrypt.json
async def decrypt_json(
ctx: EncryptionContext, data: dict
) -> dict | DecryptResult[dict]:
async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
# Decrypt the data
return decrypt_data(data)
```
@@ -376,7 +369,7 @@ class Encryption:
"""Reference to encryption type definitions.
Provides access to all type definitions used in the encryption system,
including EncryptionContext, DecryptResult, BlobEncryptor, BlobDecryptor,
including EncryptionContext, BlobEncryptor, BlobDecryptor,
JsonEncryptor, and JsonDecryptor.
"""
+4 -30
View File
@@ -9,30 +9,10 @@ from __future__ import annotations
import typing
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
Json = dict[str, typing.Any]
"""JSON-serializable dictionary type for structured data encryption."""
T = typing.TypeVar("T")
@dataclass(frozen=True, slots=True)
class DecryptResult(typing.Generic[T]):
"""Decrypted data and optional replacement ciphertext.
Return this from a decrypt handler when encrypted data should be replaced,
such as after rotating its encryption key. Returning plaintext directly
remains supported when no replacement is needed.
Attributes:
plaintext: Decrypted data returned to the caller
replacement: New encrypted data to persist in place of the input
"""
plaintext: T
replacement: T | None = None
class EncryptionContext:
"""Context passed to encryption/decryption handlers.
@@ -77,9 +57,7 @@ Returns:
Awaitable that resolves to encrypted bytes
"""
BlobDecryptor = Callable[
[EncryptionContext, bytes], Awaitable[bytes | DecryptResult[bytes]]
]
BlobDecryptor = Callable[[EncryptionContext, bytes], Awaitable[bytes]]
"""Handler for decrypting opaque blob data like checkpoints.
Note: Must be an async function. Decryption typically involves I/O operations
@@ -90,8 +68,7 @@ Args:
blob: The encrypted bytes to decrypt
Returns:
Awaitable that resolves to decrypted bytes, or a DecryptResult containing
decrypted bytes and replacement ciphertext
Awaitable that resolves to decrypted bytes
"""
JsonEncryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
@@ -124,9 +101,7 @@ Returns:
Awaitable that resolves to encrypted JSON dictionary
"""
JsonDecryptor = Callable[
[EncryptionContext, Json], Awaitable[Json | DecryptResult[Json]]
]
JsonDecryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
"""Handler for decrypting structured JSON data.
Note: Must be an async function. Decryption typically involves I/O operations
@@ -140,8 +115,7 @@ Args:
data: The encrypted JSON dictionary
Returns:
Awaitable that resolves to a decrypted JSON dictionary, or a DecryptResult
containing decrypted JSON and replacement ciphertext
Awaitable that resolves to decrypted JSON dictionary
"""
if typing.TYPE_CHECKING:
-32
View File
@@ -1,40 +1,8 @@
from collections.abc import Awaitable, Callable
import pytest
from langgraph_sdk import DecryptResult, EncryptionContext
from langgraph_sdk.encryption import DuplicateHandlerError, Encryption
def test_decrypt_result():
result = DecryptResult(plaintext=b"plain", replacement=b"rotated")
assert result.plaintext == b"plain"
assert result.replacement == b"rotated"
assert DecryptResult(plaintext={"plain": True}).replacement is None
def test_decrypt_decorators_preserve_return_types():
encryption = Encryption()
@encryption.decrypt.blob
async def blob_dec(_ctx: EncryptionContext, data: bytes) -> bytes:
return data
@encryption.decrypt.json
async def json_dec(
_ctx: EncryptionContext, data: dict[str, object]
) -> dict[str, object]:
return data
blob_handler: Callable[[EncryptionContext, bytes], Awaitable[bytes]] = blob_dec
json_handler: Callable[
[EncryptionContext, dict[str, object]], Awaitable[dict[str, object]]
] = json_dec
assert blob_handler is blob_dec
assert json_handler is json_dec
class TestHandlerValidation:
"""Test duplicate handler and signature validation."""