chore: import upstream snapshot with attribution
CI / changes (push) Has been cancelled
CI / cd libs/checkpoint (push) Has been cancelled
CI / cd libs/checkpoint-conformance (push) Has been cancelled
CI / cd libs/checkpoint-postgres (push) Has been cancelled
CI / cd libs/checkpoint-sqlite (push) Has been cancelled
CI / cd libs/cli (push) Has been cancelled
CI / cd libs/prebuilt (push) Has been cancelled
CI / cd libs/sdk-py (push) Has been cancelled
CI / cd libs/langgraph (push) Has been cancelled
CI / Check SDK methods matching (push) Has been cancelled
CI / Check CLI schema hasn't changed #3.13 (push) Has been cancelled
CI / CLI integration test (push) Has been cancelled
CI / sdk-py integration test (push) Has been cancelled
CI / CI Success (push) Has been cancelled
baseline / benchmark (push) Has been cancelled
Deploy Redirects to GitHub Pages / deploy (push) Has been cancelled
CI / changes (push) Has been cancelled
CI / cd libs/checkpoint (push) Has been cancelled
CI / cd libs/checkpoint-conformance (push) Has been cancelled
CI / cd libs/checkpoint-postgres (push) Has been cancelled
CI / cd libs/checkpoint-sqlite (push) Has been cancelled
CI / cd libs/cli (push) Has been cancelled
CI / cd libs/prebuilt (push) Has been cancelled
CI / cd libs/sdk-py (push) Has been cancelled
CI / cd libs/langgraph (push) Has been cancelled
CI / Check SDK methods matching (push) Has been cancelled
CI / Check CLI schema hasn't changed #3.13 (push) Has been cancelled
CI / CLI integration test (push) Has been cancelled
CI / sdk-py integration test (push) Has been cancelled
CI / CI Success (push) Has been cancelled
baseline / benchmark (push) Has been cancelled
Deploy Redirects to GitHub Pages / deploy (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
name: "\U0001F41B Bug Report"
|
||||
description: Report a bug in LangGraph. To report a security issue, please instead use the security option (below). For questions, please use the LangChain forum (below).
|
||||
labels: ["bug"]
|
||||
type: bug
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for taking the time to file a bug report.
|
||||
|
||||
> **All contributions must be in English.** See the [language policy](https://docs.langchain.com/oss/python/contributing/overview#language-policy).
|
||||
|
||||
For usage questions, feature requests and general design questions, please use the [LangChain Forum](https://forum.langchain.com/).
|
||||
|
||||
Check these before submitting to see if your issue has already been reported, fixed or if there's another way to solve your problem:
|
||||
|
||||
* [Documentation](https://docs.langchain.com/oss/python/langgraph/overview),
|
||||
* [API Reference Documentation](https://reference.langchain.com/python/),
|
||||
* [LangChain ChatBot](https://chat.langchain.com/)
|
||||
* [GitHub search](https://github.com/langchain-ai/langgraph),
|
||||
* [LangChain Forum](https://forum.langchain.com/),
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Checked other resources
|
||||
description: Please confirm and check all the following options.
|
||||
options:
|
||||
- label: This is a bug, not a usage question.
|
||||
required: true
|
||||
- label: I added a clear and descriptive title that summarizes this issue.
|
||||
required: true
|
||||
- label: I used the GitHub search to find a similar question and didn't find it.
|
||||
required: true
|
||||
- label: I am sure that this is a bug in LangGraph rather than my code.
|
||||
required: true
|
||||
- label: The bug is not resolved by updating to the latest stable version of LangGraph (or the specific integration package).
|
||||
required: true
|
||||
- label: This is not related to the langchain-community package.
|
||||
required: true
|
||||
- label: I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.
|
||||
required: true
|
||||
- type: textarea
|
||||
id: related
|
||||
validations:
|
||||
required: false
|
||||
attributes:
|
||||
label: Related Issues / PRs
|
||||
description: |
|
||||
If this bug is related to any existing issues or pull requests, please link them here.
|
||||
placeholder: |
|
||||
* e.g. #123, #456
|
||||
- type: textarea
|
||||
id: reproduction
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Reproduction Steps / Example Code (Python)
|
||||
description: |
|
||||
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
|
||||
|
||||
If a maintainer can copy it, run it, and see it right away, there's a much higher chance that you'll be able to get help.
|
||||
|
||||
**Important!**
|
||||
|
||||
* Avoid screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
|
||||
* Reduce your code to the minimum required to reproduce the issue if possible.
|
||||
|
||||
(This will be automatically formatted into code, so no need for backticks.)
|
||||
render: python
|
||||
placeholder: |
|
||||
from langgraph.graph import StateGraph
|
||||
|
||||
def bad_code(inputs) -> int:
|
||||
raise NotImplementedError('For demo purpose')
|
||||
|
||||
chain = StateGraph(list)
|
||||
chain.invoke('Hello!')
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Error Message and Stack Trace (if applicable)
|
||||
description: |
|
||||
If you are reporting an error, please copy and paste the full error message and
|
||||
stack trace.
|
||||
(This will be automatically formatted into code, so no need for backticks.)
|
||||
render: shell
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: |
|
||||
What is the problem, question, or error?
|
||||
|
||||
Write a short description telling what you are doing, what you expect to happen, and what is currently happening.
|
||||
placeholder: |
|
||||
* I'm trying to use the `langgraph` library to do X.
|
||||
* I expect to see Y.
|
||||
* Instead, it does Z.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: system-info
|
||||
attributes:
|
||||
label: System Info
|
||||
description: |
|
||||
Please share your system info with us.
|
||||
|
||||
Run the following command in your terminal and paste the output here:
|
||||
|
||||
`python -m langchain_core.sys_info`
|
||||
|
||||
or if you have an existing python interpreter running:
|
||||
|
||||
```python
|
||||
from langchain_core import sys_info
|
||||
sys_info.print_sys_info()
|
||||
```
|
||||
placeholder: |
|
||||
python -m langchain_core.sys_info
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,15 @@
|
||||
blank_issues_enabled: false
|
||||
version: 2.1
|
||||
contact_links:
|
||||
- name: 💬 LangChain Forum
|
||||
url: https://forum.langchain.com/
|
||||
about: General community discussions and support
|
||||
- name: 📚 LangGraph Documentation
|
||||
url: https://docs.langchain.com/oss/python/langgraph/overview
|
||||
about: View the official LangGraph documentation
|
||||
- name: 📚 API Reference Documentation
|
||||
url: https://reference.langchain.com/python/langgraph/
|
||||
about: View the official LangGraph API reference documentation
|
||||
- name: 📚 Documentation issue
|
||||
url: https://github.com/langchain-ai/docs/issues/new?template=02-langgraph.yml
|
||||
about: Report an issue related to the LangGraph documentation
|
||||
@@ -0,0 +1,28 @@
|
||||
name: "\U0001F512 Privileged"
|
||||
description: You are a LangGraph maintainer. If not, check the other options.
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
> **All contributions must be in English.** See the [language policy](https://docs.langchain.com/oss/python/contributing/overview#language-policy).
|
||||
|
||||
If you are not a LangGraph maintainer, employee, or were not asked directly by a maintainer to create an issue, then please start the conversation on the [LangChain Forum](https://forum.langchain.com/) instead.
|
||||
|
||||
**Note:** Do not begin work on a PR unless explicitly assigned to this issue by a maintainer.
|
||||
- type: checkboxes
|
||||
id: privileged
|
||||
attributes:
|
||||
label: Privileged issue
|
||||
description: Confirm that you are allowed to create an issue here.
|
||||
options:
|
||||
- label: I am a LangGraph maintainer.
|
||||
required: true
|
||||
- type: textarea
|
||||
id: content
|
||||
attributes:
|
||||
label: Issue Content
|
||||
description: Add the content of the issue here.
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Please do not begin work on a PR unless explicitly assigned to this issue by a maintainer.
|
||||
@@ -0,0 +1,40 @@
|
||||
Fixes #
|
||||
|
||||
<!-- Replace everything above this line with a 1-2 sentence description of your change. Keep the "Fixes #xx" keyword and update the issue number. -->
|
||||
|
||||
Read the full contributing guidelines: https://docs.langchain.com/oss/python/contributing/overview
|
||||
|
||||
> **All contributions must be in English.** See the [language policy](https://docs.langchain.com/oss/python/contributing/overview#language-policy).
|
||||
|
||||
If you paste a large clearly AI generated description here your PR may be IGNORED or CLOSED!
|
||||
|
||||
Thank you for contributing to LangGraph! Follow these steps to have your pull request considered as ready for review.
|
||||
|
||||
1. PR title: Should follow the format: TYPE(SCOPE): DESCRIPTION
|
||||
|
||||
- feat(langgraph): add multi-tenant support
|
||||
- Allowed TYPE and SCOPE values: https://github.com/langchain-ai/langgraph/blob/main/.github/workflows/pr_lint.yml#L19-L43
|
||||
|
||||
2. PR description:
|
||||
|
||||
- Write 1-2 sentences summarizing the change.
|
||||
- The `Fixes #xx` line at the top is **required** for external contributions — update the issue number and keep the keyword. This links your PR to the approved issue and auto-closes it on merge.
|
||||
- If there are any breaking changes, please clearly describe them.
|
||||
- If this PR depends on another PR being merged first, please include "Depends on #PR_NUMBER" in the description.
|
||||
|
||||
3. Run `make format`, `make lint` and `make test` from the root of the package(s) you've modified.
|
||||
|
||||
- We will not consider a PR unless these three are passing in CI.
|
||||
|
||||
4. How did you verify your code works?
|
||||
|
||||
Additional guidelines:
|
||||
|
||||
- All external PRs must link to an issue or discussion where a solution has been approved by a maintainer, and you must be assigned to that issue. PRs without prior approval will be closed.
|
||||
- PRs should not touch more than one package unless absolutely necessary.
|
||||
- Do not update the `uv.lock` files or add dependencies to `pyproject.toml` files (even optional ones) unless you have explicit permission to do so by a maintainer.
|
||||
|
||||
## Social handles (optional)
|
||||
<!-- If you'd like a shoutout on release, add your socials below -->
|
||||
Twitter: @
|
||||
LinkedIn: https://linkedin.com/in/
|
||||
@@ -0,0 +1,479 @@
|
||||
# Threat Model: LangGraph
|
||||
|
||||
> Generated: 2026-03-28 | Commit: 0ba22143 | Scope: Full monorepo (all libs/)
|
||||
|
||||
> **Disclaimer:** This threat model is automatically generated to help developers and security researchers understand where trust is placed in this system and where boundaries exist. It is experimental, subject to change, and not an authoritative security reference — findings should be validated before acting on them. The analysis may be incomplete or contain inaccuracies. We welcome suggestions and corrections to improve this document.
|
||||
|
||||
For vulnerability reporting, see the [GitHub Security Advisories](https://github.com/langchain-ai/langgraph/security/advisories) page.
|
||||
|
||||
## Scope
|
||||
|
||||
### In Scope
|
||||
|
||||
- `libs/langgraph` — Core graph execution engine (Pregel, StateGraph, channels, functional API with `@entrypoint`/`@task`)
|
||||
- `libs/prebuilt` — High-level agent APIs (ToolNode, create_react_agent, ValidationNode, InjectedState/InjectedStore/ToolRuntime injection)
|
||||
- `libs/checkpoint` — Checkpoint serialization/deserialization (JsonPlusSerializer, EncryptedSerializer, BaseCache, stores, serde event hooks, SAFE_MSGPACK_TYPES allowlist)
|
||||
- `libs/checkpoint-postgres` — PostgreSQL checkpoint saver, key-value store, and vector search
|
||||
- `libs/checkpoint-sqlite` — SQLite checkpoint saver, key-value store, and vector search
|
||||
- `libs/cli` — CLI for Docker-based deployment (`langgraph up/build/dev/new`), WebhookUrlPolicy
|
||||
- `libs/sdk-py` — Python SDK client for LangGraph Server API (HttpClient, Auth system, Encryption handlers)
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- `libs/sdk-js` — Moved to external `langchain-ai/langgraphjs` repository; no source in this repo
|
||||
- `libs/checkpoint-conformance` — Conformance test suite only; not shipped code
|
||||
- LangGraph Server / `langgraph-api` — Closed-source server runtime; not in this repo
|
||||
- LangChain Core (`langchain-core`) — Upstream dependency; separate threat model
|
||||
- User application code — Tools, prompts, model selection, deployment infrastructure
|
||||
- LLM provider behavior — Model output content and safety
|
||||
- LangSmith platform — Observability/tracing backend
|
||||
- Tests, benchmarks, documentation — Not shipped code
|
||||
|
||||
### Assumptions
|
||||
|
||||
1. The project is used as a library/framework — users control their own application code, model selection, and deployment.
|
||||
2. Checkpoint storage backends (databases) are deployed with proper access controls by the user.
|
||||
3. LLM providers return well-formed responses per their documented API contracts.
|
||||
4. The `langgraph.json` configuration file is developer-controlled and not user-supplied at runtime.
|
||||
5. The CLI runs in a developer environment with Docker access.
|
||||
6. The SDK connects to trusted LangGraph Server endpoints chosen by the user.
|
||||
7. SDK Encryption handlers are developer-authored server-side code with application-level trust.
|
||||
|
||||
---
|
||||
|
||||
## System Overview
|
||||
|
||||
LangGraph is an open-source Python framework for building stateful, multi-actor AI agent applications. It provides a graph-based execution model (Bulk Synchronous Parallel via the Pregel engine) where user-defined nodes process shared state through typed channels. The framework supports two authoring APIs: the declarative StateGraph API and the functional API (`@entrypoint`/`@task` decorators). It includes checkpointing (persistence of graph state to databases), tool execution (dispatching LLM-generated tool calls with runtime injection of state/store/context), remote graph composition (calling LangGraph Server APIs), Docker-based deployment via a CLI, and a beta SDK encryption framework for custom at-rest encryption handlers.
|
||||
|
||||
### Architecture Diagram
|
||||
|
||||
```
|
||||
+---------------------------------------------------------------------------+
|
||||
| User Application |
|
||||
| |
|
||||
| +-----------------------------------------------+ |
|
||||
| | User Application Code | |
|
||||
| | (graph nodes, tools; StateGraph builder API | |
|
||||
| | and functional API @entrypoint/@task both | |
|
||||
| | compile to the same Pregel execution engine) | |
|
||||
| +------------------------+----------------------+ |
|
||||
| | |
|
||||
| +------------v-----------+ |
|
||||
| | StateGraph / Pregel | |
|
||||
| | (core execution engine)| |
|
||||
| +------+----------+------+ |
|
||||
| | | |
|
||||
| InjectedState +--v---------+ |
|
||||
| InjectedStore | ToolNode | |
|
||||
| ToolRuntime | (opt-in) | |
|
||||
| +------------+ |
|
||||
| | |
|
||||
| - - - - - - - - - - - | - - - - TB1: User/Framework API - - - - - - - - |
|
||||
| | |
|
||||
| +-----v------+ +--------------+ |
|
||||
| | Checkpoint | | RemoteGraph | |
|
||||
| | Serializer | | (SDK client) | |
|
||||
| |(jsonplus) | +------+--------+ |
|
||||
| +-----+------+ | |
|
||||
| | | |
|
||||
| - - - - - - - - - - - | - - - - - - - -|- - TB2: Storage/Network - - - - |
|
||||
| v v |
|
||||
| +--------------+ +--------------+ |
|
||||
| | PostgreSQL | | LangGraph | |
|
||||
| | / SQLite | | Server API | |
|
||||
| +--------------+ +--------------+ |
|
||||
| |
|
||||
| +----------+ +--------------+ |
|
||||
| | CLI |------------------>| Docker | |
|
||||
| |(langgraph| TB4: Config | Engine | |
|
||||
| | up/build)| +--------------+ |
|
||||
| +----------+ |
|
||||
| |
|
||||
| +--------------------+ |
|
||||
| | SDK Encryption | TB5: Developer-authored handlers |
|
||||
| | Handlers (beta) | (server-side execution in langgraph-api) |
|
||||
| +--------------------+ |
|
||||
+---------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Components
|
||||
|
||||
| ID | Component | Description | Trust Level | Default? | Entry Points |
|
||||
|----|-----------|-------------|-------------|----------|--------------|
|
||||
| C1 | StateGraph / Pregel | Core graph builder and execution engine with v1/v2 output, durability modes (sync/async/exit), interrupt_before/interrupt_after | framework-controlled | Yes | `StateGraph.add_node()`, `StateGraph.compile()`, `Pregel.invoke()`, `Pregel.stream()` |
|
||||
| C2 | JsonPlusSerializer | Checkpoint serialization/deserialization with msgpack, JSON, and pickle codecs; 47-entry SAFE_MSGPACK_TYPES allowlist | framework-controlled | Yes | `loads_typed()`, `dumps_typed()`, `_create_msgpack_ext_hook()`, `_reviver()` |
|
||||
| C3 | ToolNode | Dispatches LLM-generated tool calls to registered BaseTool instances; supports InjectedState/InjectedStore/ToolRuntime injection into tools | framework-controlled | No (explicit opt-in required) | `ToolNode._func()`, `_run_one()`, `_execute_tool_sync()`, `_validate_tool_call()`, `_inject_tool_args()` |
|
||||
| C4 | RemoteGraph | Client for remote LangGraph Server API; implements PregelProtocol | framework-controlled | No (opt-in) | `RemoteGraph.stream()`, `RemoteGraph.invoke()`, `RemoteGraph.get_state()` |
|
||||
| C5 | PostgresSaver / PostgresStore | PostgreSQL checkpoint saver, key-value store, and vector search | framework-controlled | No (opt-in) | `from_conn_string()`, `put()`, `get_tuple()`, `search()` |
|
||||
| C6 | SqliteSaver / SqliteStore | SQLite checkpoint saver, key-value store with JSON path filtering | framework-controlled | No (opt-in) | `from_conn_string()`, `put()`, `get_tuple()`, `search()` |
|
||||
| C7 | EncryptedSerializer | AES-EAX authenticated encryption wrapper for checkpoint data | framework-controlled | No (opt-in) | `from_pycryptodome_aes()`, `loads_typed()`, `dumps_typed()` |
|
||||
| C8 | CLI (langgraph_cli) | Docker-based build and deployment tooling; config schema includes WebhookUrlPolicy for SSRF protection | framework-controlled | No (separate install) | `langgraph up`, `langgraph build`, `langgraph dev`, `langgraph new` |
|
||||
| C9 | SDK Client (langgraph_sdk) | HTTP client for LangGraph Server API with SSE streaming and reconnection | framework-controlled | Yes | `get_client()`, `get_sync_client()`, `HttpClient.request_reconnect()`, `HttpClient.stream()` |
|
||||
| C10 | User-Registered Tools | BaseTool instances provided by users; may use InjectedState/InjectedStore/ToolRuntime annotations | user-controlled | N/A | Tool `invoke()` / `ainvoke()` methods |
|
||||
| C11 | User-Registered Nodes | Arbitrary callables added via `add_node()` or `@task`/`@entrypoint` | user-controlled | N/A | Node function signatures |
|
||||
| C12 | Checkpoint Storage | PostgreSQL or SQLite databases storing serialized graph state | external | N/A | Database connection interface |
|
||||
| C13 | Functional API | `@entrypoint`/`@task` decorators for function-based workflow authoring with retry/cache policies | framework-controlled | Yes | `entrypoint.__call__()`, `task()`, `_TaskFunction.__call__()` (`libs/langgraph/langgraph/func/__init__.py`) |
|
||||
| C14 | BaseCache | Cache layer for task results with JsonPlusSerializer (pickle_fallback=False) | framework-controlled | No (opt-in, requires checkpointer) | `get()`, `set()`, `clear()` (`libs/checkpoint/langgraph/cache/base/__init__.py`) |
|
||||
| C15 | Serde Event Hooks | Monitoring system for serialization/deserialization events (msgpack_blocked, msgpack_unregistered_allowed, msgpack_method_blocked) | framework-controlled | Yes | `register_serde_event_listener()`, `emit_serde_event()` (`libs/checkpoint/langgraph/checkpoint/serde/event_hooks.py`) |
|
||||
| C16 | Auth System (SDK) | Custom authentication/authorization handler framework | framework-controlled | No (opt-in) | `Auth.authenticate()`, `Auth.on()` handler registration (`libs/sdk-py/langgraph_sdk/auth/__init__.py`) |
|
||||
| C17 | SDK Encryption Handlers (beta) | Custom at-rest encryption/decryption framework; supports blob and JSON handlers with per-model/field context; server-side execution | framework-controlled | No (opt-in, beta) | `Encryption.encrypt.blob()`, `Encryption.encrypt.json()`, `Encryption.decrypt.blob()`, `Encryption.decrypt.json()`, `Encryption.context()` (`libs/sdk-py/langgraph_sdk/encryption/__init__.py`) |
|
||||
|
||||
---
|
||||
|
||||
## Data Classification
|
||||
|
||||
| ID | PII Category | Specific Fields | Sensitivity | Storage Location(s) | Encrypted at Rest | Retention | Regulatory |
|
||||
|----|-------------|----------------|-------------|---------------------|-------------------|-----------|------------|
|
||||
| DC1 | API credentials | `x-api-key` header, `LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, `LANGCHAIN_API_KEY` env vars | Critical | Environment variables, HTTP headers in transit | N/A (in-memory) | Session lifetime | All — breach trigger |
|
||||
| DC2 | Encryption keys | `LANGGRAPH_AES_KEY` env var, `key` parameter to `from_pycryptodome_aes()` | Critical | Environment variable, in-memory | N/A | Application lifetime | All — breach trigger |
|
||||
| DC3 | Serialized graph state | Checkpoint data in `checkpoints` and `writes` tables (msgpack/JSON/pickle bytes) | High | PostgreSQL (BYTEA), SQLite (BLOB) | Optional via EncryptedSerializer or SDK Encryption Handlers | Unbounded (no default TTL) | GDPR if state contains PII |
|
||||
| DC4 | Store key-value data | User-stored items in `store` tables via BaseStore | High | PostgreSQL, SQLite | No (plaintext JSON); optional via SDK Encryption Handlers | Configurable TTL, default unbounded | GDPR if contains PII |
|
||||
| DC5 | Checkpoint metadata | `thread_id`, `checkpoint_ns`, `run_id`, `step`, `source` | Medium | PostgreSQL, SQLite (metadata JSONB/JSON column) | No | Same as DC3 | Minimal |
|
||||
| DC6 | Agent conversation history | LangChain messages (HumanMessage, AIMessage, ToolMessage) serialized in checkpoint state | High | PostgreSQL, SQLite (within DC3 checkpoint bytes) | Only if DC3 encrypted | Unbounded | GDPR, CCPA if contains user PII |
|
||||
| DC7 | Connection strings | PostgreSQL URIs, SQLite file paths passed to `from_conn_string()` | Critical | Application code, environment variables | N/A (in-memory) | Application lifetime | All — may contain credentials |
|
||||
| DC8 | Vector embeddings | Document embeddings in `store_vectors` table | Low | PostgreSQL (pgvector), SQLite (vec extension) | No | Same as DC4 | Minimal |
|
||||
| DC9 | SDK Encryption context metadata | `EncryptionContext.metadata` dict passed to encryption handlers | Medium | In-memory per request; persisted with encrypted data | N/A (context, not payload) | Request lifetime + persistence alongside encrypted data | Depends on content |
|
||||
|
||||
### Data Classification Details
|
||||
|
||||
#### DC1: API Credentials
|
||||
|
||||
- **Fields**: `x-api-key` HTTP header, `LANGGRAPH_API_KEY`/`LANGSMITH_API_KEY`/`LANGCHAIN_API_KEY` environment variables
|
||||
- **Storage**: Environment variables (loaded at runtime), HTTP request headers (in transit)
|
||||
- **Access**: SDK client code (`libs/sdk-py/langgraph_sdk/_shared/utilities.py:_get_api_key`), any process with env var access
|
||||
- **Encryption**: TLS in transit (if HTTPS); no at-rest encryption for env vars
|
||||
- **Retention**: Session/process lifetime
|
||||
- **Logging exposure**: API key stripped of quotes but could appear in debug logs if HTTP headers are logged. `RESERVED_HEADERS` prevents user override of `x-api-key` but doesn't prevent logging.
|
||||
- **Cross-border**: Travels with every HTTP request to the LangGraph Server
|
||||
- **Gaps**: SDK `request_reconnect()` and `stream()` forward `x-api-key` header to server-controlled `Location` redirect URLs without URL validation (see T9)
|
||||
|
||||
#### DC2: Encryption Keys
|
||||
|
||||
- **Fields**: `LANGGRAPH_AES_KEY` environment variable, `key` bytes parameter
|
||||
- **Storage**: Environment variable or direct bytes in application code
|
||||
- **Access**: `libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:from_pycryptodome_aes`
|
||||
- **Encryption**: N/A — this IS the encryption key
|
||||
- **Retention**: Application lifetime
|
||||
- **Logging exposure**: Not logged by framework code
|
||||
- **Gaps**: Key loaded from env var as UTF-8 string limits entropy to ~6.57 bits/byte (see T7). Cipher name validated with `assert` which is stripped by `python -O` (see T8).
|
||||
|
||||
#### DC3: Serialized Graph State
|
||||
|
||||
- **Fields**: All channel values serialized via `JsonPlusSerializer.dumps_typed()` — includes complete agent state, conversation history, tool call results, and any user-defined state
|
||||
- **Storage**: PostgreSQL `checkpoints.checkpoint` (BYTEA), `writes.blob` (BYTEA); SQLite `checkpoints.checkpoint` (BLOB), `writes.blob` (BLOB)
|
||||
- **Access**: Any code with database credentials; `BaseCheckpointSaver.get_tuple()` / `put()`
|
||||
- **Encryption**: Optional via `EncryptedSerializer` wrapping (AES-EAX) or SDK Encryption Handlers (beta, server-side). Not encrypted by default.
|
||||
- **Retention**: Unbounded by default. Optional TTL via `CheckpointerConfig.ttl` (server-side config)
|
||||
- **Logging exposure**: Serde event hooks emit module/class names of deserialized types but not the data itself
|
||||
- **Gaps**: Default unbounded retention of potentially PII-containing state. Unencrypted by default. EncryptedSerializer has fallback that accepts unencrypted data (see T10).
|
||||
|
||||
#### DC6: Agent Conversation History
|
||||
|
||||
- **Fields**: `HumanMessage.content`, `AIMessage.content`, `ToolMessage.content`, `AIMessage.tool_calls` — embedded within DC3 checkpoint bytes
|
||||
- **Storage**: Same as DC3 (within serialized checkpoint data)
|
||||
- **Access**: Same as DC3
|
||||
- **Encryption**: Only if DC3 is encrypted via EncryptedSerializer or SDK Encryption Handlers
|
||||
- **Retention**: Same as DC3 (unbounded default)
|
||||
- **Gaps**: Conversation content may include user PII, PHI, or sensitive business data. No field-level encryption or redaction. Retention inherits from DC3 with no conversation-specific policy.
|
||||
|
||||
#### DC9: SDK Encryption Context Metadata
|
||||
|
||||
- **Fields**: `EncryptionContext.model` (str), `EncryptionContext.field` (str), `EncryptionContext.metadata` (dict)
|
||||
- **Storage**: In-memory during request processing; persisted alongside encrypted data for later decryption
|
||||
- **Access**: Encryption/decryption handlers (developer-authored), ContextHandler (receives authenticated BaseUser)
|
||||
- **Encryption**: N/A — this is context for encryption, not encrypted data itself
|
||||
- **Retention**: Persisted with encrypted data indefinitely
|
||||
- **Logging exposure**: Not logged by SDK code
|
||||
- **Gaps**: `metadata` is a mutable dict — whether cross-request isolation is enforced depends on server-side implementation (langgraph-api, out of scope). ContextHandler registration at `libs/sdk-py/langgraph_sdk/encryption/__init__.py:Encryption.context` does not call `_validate_handler` (missing async/param-count validation, unlike all other handler types).
|
||||
|
||||
---
|
||||
|
||||
## Trust Boundaries
|
||||
|
||||
| ID | Boundary | Description | Controls (Inside) | Does NOT Control (Outside) |
|
||||
|----|----------|-------------|-------------------|---------------------------|
|
||||
| TB1 | User/Framework API | Where user-provided code and configuration enters the framework | Graph execution logic, channel semantics, default configs, validation of graph structure, tool injection merge order (system values overwrite LLM values) | User node implementations, tool behavior, model selection, prompt construction, state schema design |
|
||||
| TB2 | Checkpoint Storage | Where serialized data enters/leaves the persistence layer | Serialization format, allowlists for deserialization (47 safe types, 1 safe method), encryption (if configured), serde event hooks | Database access controls, who can write to the checkpoint tables, storage infrastructure security |
|
||||
| TB3 | Remote API | Where data crosses the network to/from LangGraph Server | Outbound config sanitization (`_sanitize_config`), SDK HTTP transport, API key handling, `RESERVED_HEADERS` | Remote server behavior, response content integrity, network security (TLS), server-provided Location redirect targets |
|
||||
| TB4 | CLI Config/Docker | Where developer config drives container image generation | Dockerfile template structure, config schema validation (including WebhookUrlPolicy), list-based subprocess args, build command content validation | `langgraph.json` file content, Docker daemon security, host filesystem |
|
||||
| TB5 | SDK Encryption Handlers | Where developer-authored encryption handlers process sensitive data | Handler signature validation (async, 2-param for encrypt/decrypt), duplicate registration prevention, EncryptionContext construction | Handler implementation correctness, key management, actual encrypt/decrypt behavior, server-side execution environment |
|
||||
|
||||
### Boundary Details
|
||||
|
||||
#### TB1: User/Framework API
|
||||
|
||||
- **Inside**: Graph compilation validates structure (`libs/langgraph/langgraph/pregel/_validate.py:validate_graph`). Channel types enforce update semantics (`libs/langgraph/langgraph/channels/base.py:BaseChannel.update`). Functional API validates entrypoint has at least one parameter (`libs/langgraph/langgraph/func/__init__.py:entrypoint`). Sensitive config keys filtered from metadata propagation — keys containing "key", "token", "secret", "password", "auth" are excluded (`libs/langgraph/langgraph/_internal/_config.py:_exclude_as_metadata`). Tool injection merge order ensures system-injected values (InjectedState/InjectedStore/ToolRuntime) overwrite any LLM-supplied collisions (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._inject_tool_args` line 1380). Injected parameter names hidden from LLM tool schema via `tool_call_schema` filtering.
|
||||
- **Outside**: What user nodes do, what tools return, what LLMs generate, how users handle output.
|
||||
- **Crossing mechanism**: Python function calls — `add_node(callable)`, `add_edge()`, `compile(checkpointer=...)`, `@entrypoint`, `@task`.
|
||||
|
||||
#### TB2: Checkpoint Storage
|
||||
|
||||
- **Inside**: `JsonPlusSerializer` controls serialization format (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer`). Msgpack type allowlist (`libs/checkpoint/langgraph/checkpoint/serde/_msgpack.py:SAFE_MSGPACK_TYPES` — 47 safe types including stdlib, langchain_core messages, and langgraph types). Msgpack method allowlist (`libs/checkpoint/langgraph/checkpoint/serde/_msgpack.py:SAFE_MSGPACK_METHODS` — 1 safe method: `datetime.datetime.fromisoformat`). JSON module allowlist (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:_check_allowed_json_modules`). Serde event hooks for monitoring (`libs/checkpoint/langgraph/checkpoint/serde/event_hooks.py:emit_serde_event`). Optional `EncryptedSerializer` wrapping (`libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:EncryptedSerializer`). SQLite filter key regex validation (`libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/utils.py:_validate_filter_key`). Parameterized SQL queries in both Postgres and SQLite backends.
|
||||
- **Outside**: Database access controls, who can read/write checkpoint tables, storage backend integrity.
|
||||
- **Crossing mechanism**: Database read/write operations — serialized bytes stored as BYTEA (Postgres) or BLOB (SQLite).
|
||||
|
||||
#### TB3: Remote API
|
||||
|
||||
- **Inside**: `_sanitize_config()` strips non-primitive values and drops checkpoint-internal keys from outbound config (`libs/langgraph/langgraph/pregel/remote.py:_sanitize_config`). SDK handles API key from env vars (`libs/sdk-py/langgraph_sdk/_shared/utilities.py:_get_api_key`). `RESERVED_HEADERS` prevents user override of `x-api-key` (`libs/sdk-py/langgraph_sdk/_shared/utilities.py:RESERVED_HEADERS`).
|
||||
- **Outside**: Remote server response content, network integrity, whether the server is legitimate, server-provided Location redirect targets.
|
||||
- **Crossing mechanism**: HTTPS requests via `httpx` through `langgraph_sdk`.
|
||||
|
||||
#### TB4: CLI Config/Docker
|
||||
|
||||
- **Inside**: Config file parsed as JSON (`libs/cli/langgraph_cli/config.py:validate_config_file`). Docker subprocess invoked with list-based args via `asyncio.create_subprocess_exec`, not `shell=True` (`libs/cli/langgraph_cli/exec.py:subp_exec`). Template downloads from hardcoded GitHub URLs (`libs/cli/langgraph_cli/templates.py`). Config schema validation covers store, auth, encryption, http, webhooks, checkpointer, and ui sections (`libs/cli/langgraph_cli/schemas.py`). Build command content validation blocks shell metacharacters (`libs/cli/langgraph_cli/config.py:has_disallowed_build_command_content`). WebhookUrlPolicy (`libs/cli/langgraph_cli/schemas.py:WebhookUrlPolicy`) supports `require_https`, `allowed_domains`, `allowed_ports`, `max_url_length`, `disable_loopback` for SSRF protection.
|
||||
- **Outside**: Content of `langgraph.json`, Docker daemon behavior, filesystem permissions.
|
||||
- **Crossing mechanism**: JSON file read, subprocess execution, ZIP download/extraction.
|
||||
|
||||
#### TB5: SDK Encryption Handlers
|
||||
|
||||
- **Inside**: Handler signature validation — must be async, must accept exactly 2 positional params (`libs/sdk-py/langgraph_sdk/encryption/__init__.py:_validate_handler`). Duplicate handler registration prevention (`DuplicateHandlerError`). `EncryptionContext` construction with model/field/metadata (`libs/sdk-py/langgraph_sdk/encryption/types.py:EncryptionContext`). JSON key preservation constraint documented (enforced server-side).
|
||||
- **Outside**: Handler implementation correctness, key management strategy, actual encryption/decryption logic, server-side execution in langgraph-api.
|
||||
- **Crossing mechanism**: Python decorator registration at import time; server-side invocation at runtime.
|
||||
|
||||
---
|
||||
|
||||
## Data Flows
|
||||
|
||||
| ID | Source | Destination | Data Type | Classification | Crosses Boundary | Protocol |
|
||||
|----|--------|-------------|-----------|----------------|------------------|----------|
|
||||
| DF1 | C12 (Checkpoint Storage) | C2 (JsonPlusSerializer) | Serialized checkpoint bytes (msgpack/JSON/pickle) | DC3 | TB2 | Database read |
|
||||
| DF2 | C2 (JsonPlusSerializer) | C1 (Pregel) | Deserialized Python objects (channel state) | DC3, DC6 | TB2 | Function call |
|
||||
| DF3 | LLM (external) | C3 (ToolNode) | Tool call arguments (JSON strings in AIMessage) | — | TB1 | Function call (via langchain-core) |
|
||||
| DF4 | C3 (ToolNode) | C10 (User Tools) | Parsed argument dicts merged with injected state/store/runtime | — | TB1 | `tool.invoke(call_args)` |
|
||||
| DF5 | C4 (RemoteGraph) | C1 (Pregel) | Stream chunks (JSON-deserialized dicts) | — | TB3 | HTTPS / SSE |
|
||||
| DF6 | `langgraph.json` | C8 (CLI) | Config dict (graphs, env, store, auth, encryption, http, webhooks, checkpointer, ui) | — | TB4 | `json.load()` |
|
||||
| DF7 | C8 (CLI) | Docker | Dockerfile content with embedded ENV values | — | TB4 | `asyncio.create_subprocess_exec` |
|
||||
| DF8 | C11 (User Nodes) | C1 (Pregel) | State updates (arbitrary Python objects) | — | TB1 | Channel write |
|
||||
| DF9 | C9 (SDK Client) | C4 (RemoteGraph) | API responses (JSON) | — | TB3 | HTTPS |
|
||||
| DF10 | User config | C7 (EncryptedSerializer) | AES key from LANGGRAPH_AES_KEY env var | DC2 | TB2 | `os.getenv()` |
|
||||
| DF11 | C12 (Checkpoint Storage) | C14 (BaseCache) | Cached task results via JsonPlusSerializer | DC3 | TB2 | Database read |
|
||||
| DF12 | LangGraph Server | C9 (SDK Client) | HTTP responses with Location header | DC1 | TB3 | HTTP redirect |
|
||||
| DF13 | C9 (SDK Client) | Redirect target | Request headers including x-api-key | DC1 | TB3 | HTTPS |
|
||||
| DF14 | C1 (Pregel state) | C3 (ToolNode) | InjectedState/InjectedStore/ToolRuntime values for tool injection | DC3, DC4 | TB1 | Function call (dict merge) |
|
||||
| DF15 | Developer code | C17 (SDK Encryption Handlers) | Encryption/decryption handler functions and context handler | — | TB5 | Python decorator registration |
|
||||
|
||||
### Flow Details
|
||||
|
||||
#### DF1: Checkpoint Storage -> JsonPlusSerializer
|
||||
|
||||
- **Data**: Serialized graph state as `(type_tag, bytes)` tuples. Type tags include `"msgpack"`, `"json"`, `"pickle"`, `"bytes"`, `"null"`. When encrypted: `"msgpack+aes"`, `"json+aes"`.
|
||||
- **Validation**: Type tag dispatches to codec. Msgpack: `_create_msgpack_ext_hook` with allowlist check — `SAFE_MSGPACK_TYPES` (47 entries) always checked first, then `allowed_modules` determines behavior for unregistered types (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:_create_msgpack_ext_hook`). JSON: `_reviver` with `lc:2` module allowlist. Pickle: **no restrictions** (`pickle.loads(data_)` if `pickle_fallback=True`, `libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer.loads_typed`). The proposed `secure_pickle.py` with `RestrictedUnpickler` was documented in `SECURITY_FIX_SUMMARY.md` but never merged.
|
||||
- **Trust assumption**: Checkpoint storage is access-controlled. An attacker with write access to the database can craft malicious checkpoint data.
|
||||
|
||||
#### DF3: LLM -> ToolNode
|
||||
|
||||
- **Data**: Tool call name and arguments from LLM-generated `AIMessage.tool_calls`.
|
||||
- **Validation**: Tool name checked against registered `tools_by_name` dict — unknown names return error `ToolMessage` (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._validate_tool_call`). Argument values validated only by the target tool's Pydantic schema.
|
||||
- **Trust assumption**: LLM output is treated as untrusted for tool name routing but argument values pass through to tools without ToolNode-level sanitization.
|
||||
|
||||
#### DF4: ToolNode -> User Tools (with Injection)
|
||||
|
||||
- **Data**: Parsed argument dicts from LLM, merged with system-injected InjectedState/InjectedStore/ToolRuntime values.
|
||||
- **Validation**: Four-layer defense: (1) Injected parameter names hidden from LLM via `tool_call_schema` filtering. (2) Dict merge `{**llm_args, **injected_args}` places system values last — system always wins on collision (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._inject_tool_args` line 1380). (3) Pydantic `model_validate` with default `extra="ignore"` drops unknown keys. (4) Output construction only includes declared model fields.
|
||||
- **Trust assumption**: LLM-provided arguments cannot override system-injected values due to merge order.
|
||||
|
||||
#### DF5: RemoteGraph -> Pregel
|
||||
|
||||
- **Data**: Stream event chunks containing dicts for `Interrupt`, `Command`, state snapshots.
|
||||
- **Validation**: **None** on inbound data. `Interrupt(**i)` uses dict-splatting with no schema check (`libs/langgraph/langgraph/pregel/remote.py:RemoteGraph.stream`). `Command(**chunk.data)` uses dict-splatting for parent commands.
|
||||
- **Trust assumption**: Remote server is trusted. A compromised or malicious server can inject arbitrary field values.
|
||||
|
||||
#### DF6: langgraph.json -> CLI
|
||||
|
||||
- **Data**: JSON config including `graphs`, `env`, `store`, `auth`, `encryption`, `http`, `webhooks`, `checkpointer`, `ui`, `ui_config` sections.
|
||||
- **Validation**: Schema validation in `validate_config_file()` (`libs/cli/langgraph_cli/config.py:validate_config_file`). Config values embedded in Dockerfile via `json.dumps()` in single-quoted `ENV` lines (`libs/cli/langgraph_cli/config.py:python_config_to_docker`). Build command content validation (`libs/cli/langgraph_cli/config.py:has_disallowed_build_command_content`) blocks shell metacharacters.
|
||||
- **Trust assumption**: `langgraph.json` is developer-authored. Single quotes in config values could break Dockerfile `ENV` syntax.
|
||||
|
||||
#### DF11: Checkpoint Storage -> BaseCache
|
||||
|
||||
- **Data**: Cached task results stored via `BaseCache.set()` and retrieved via `BaseCache.get()`.
|
||||
- **Validation**: Uses `JsonPlusSerializer(pickle_fallback=False)` by default (`libs/checkpoint/langgraph/cache/base/__init__.py:BaseCache`). Subject to same msgpack deserialization behavior as DF1 (allowed_modules defaults based on `LANGGRAPH_STRICT_MSGPACK`).
|
||||
- **Trust assumption**: Cache storage has same access controls as checkpoint storage.
|
||||
|
||||
#### DF12-13: Server -> SDK -> Redirect Target (API Key Leak)
|
||||
|
||||
- **Data**: Server provides `Location` header in HTTP response. SDK follows the redirect and sends all original request headers (including `x-api-key`) to the target URL.
|
||||
- **Validation**: **None** on Location URL. No allowlist, no same-origin check, no header stripping on cross-origin redirect.
|
||||
- **Trust assumption**: The LangGraph Server is trusted to not redirect to malicious URLs. Violated if server is compromised.
|
||||
|
||||
#### DF14: Pregel State -> ToolNode (Runtime Injection)
|
||||
|
||||
- **Data**: Graph state dict (InjectedState), BaseStore instance (InjectedStore), ToolRuntime object (containing state, config, store, context, stream_writer, tool_call_id).
|
||||
- **Validation**: Injection targets determined by tool type annotations at compile time. Injected values overwrite any LLM-provided values with matching keys (safe merge order). Pydantic validation on tool input drops extra keys not in the tool's declared schema.
|
||||
- **Trust assumption**: System-injected values are trusted; LLM-provided values cannot interfere due to merge order guarantees.
|
||||
|
||||
#### DF15: Developer Code -> SDK Encryption Handlers
|
||||
|
||||
- **Data**: Async Python callables registered via decorators for blob/JSON encryption/decryption and context derivation.
|
||||
- **Validation**: `_validate_handler` checks async-ness and 2-param signature for encrypt/decrypt handlers. `DuplicateHandlerError` prevents double registration. **Gap**: `Encryption.context()` method does NOT call `_validate_handler` — a sync function or wrong param count passes registration and fails only at server-side invocation (`libs/sdk-py/langgraph_sdk/encryption/__init__.py:Encryption.context`).
|
||||
- **Trust assumption**: Handler authors are application developers with server-level trust.
|
||||
|
||||
---
|
||||
|
||||
## Threats
|
||||
|
||||
| ID | Data Flow | Classification | Threat | Boundary | Severity | Validation | Code Reference |
|
||||
|----|-----------|----------------|--------|----------|----------|------------|----------------|
|
||||
| T1 | DF1, DF11 | DC3 | Arbitrary code execution via msgpack deserialization when strict mode is OFF (default) | TB2 | High | Verified | `libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:_create_msgpack_ext_hook` |
|
||||
| T2 | DF1 | DC3 | Arbitrary code execution via `pickle.loads` when `pickle_fallback=True` | TB2 | High | Verified | `libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer.loads_typed` |
|
||||
| T3 | DF1 | DC3 | Arbitrary module import/execution via JSON `lc:2` constructor when `allowed_json_modules=True` | TB2 | High | Verified | `libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer._revive_lc2` |
|
||||
| T4 | DF5 | — | Unvalidated dict-splatting from remote API into `Interrupt`/`Command` objects | TB3 | Medium | Likely | `libs/langgraph/langgraph/pregel/remote.py:RemoteGraph.stream` |
|
||||
| T5 | DF6, DF7 | — | Dockerfile ENV injection via single-quote in `langgraph.json` config values | TB4 | Low | Likely | `libs/cli/langgraph_cli/config.py:python_config_to_docker` |
|
||||
| T6 | DF7 | — | ZIP slip in `langgraph new` template extraction | TB4 | Low | Unverified | `libs/cli/langgraph_cli/templates.py:_download_repo_with_requests` |
|
||||
| T7 | DF10 | DC2 | AES key entropy limited to printable characters via env var string encoding | TB2 | Info | — | `libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:EncryptedSerializer.from_pycryptodome_aes` |
|
||||
| T8 | DF10 | DC2 | EncryptedSerializer cipher name check uses `assert` (stripped with `python -O`) | TB2 | Low | Verified | `libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:PycryptodomeAesCipher.decrypt` |
|
||||
| T9 | DF12, DF13 | DC1 | SDK API key leak via server-controlled Location redirect to attacker-controlled URL | TB3 | Medium | Verified | `libs/sdk-py/langgraph_sdk/_async/http.py:HttpClient.request_reconnect`, `libs/sdk-py/langgraph_sdk/_async/http.py:HttpClient.stream` |
|
||||
| T10 | DF1 | DC3 | EncryptedSerializer silently accepts unencrypted data — attacker bypasses encryption by writing plain type tags | TB2 | Medium | Verified | `libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:EncryptedSerializer.loads_typed` |
|
||||
| T11 | DF1, DF11 | DC3, DC6 | Unbounded retention of checkpoint data containing PII/conversation history | TB2 | Medium | — | `libs/checkpoint/langgraph/checkpoint/base/__init__.py:BaseCheckpointSaver` |
|
||||
|
||||
### Threat Details
|
||||
|
||||
#### T1: Msgpack Deserialization RCE (Default Config)
|
||||
|
||||
- **Flow**: DF1 (Checkpoint Storage -> JsonPlusSerializer), DF11 (Checkpoint Storage -> BaseCache)
|
||||
- **Description**: When `LANGGRAPH_STRICT_MSGPACK` is not set (the default), the msgpack `_create_msgpack_ext_hook` allows **any** `(module, class)` pair stored in checkpoint data to be imported via `importlib.import_module` and instantiated with attacker-controlled arguments. The `SAFE_MSGPACK_TYPES` allowlist (47 entries) is checked first, but unregistered types are logged as warnings and allowed through when `allowed_modules=True` (the default when strict mode is off). Seven EXT codes are processed: `EXT_CONSTRUCTOR_SINGLE_ARG` (0), `EXT_CONSTRUCTOR_POS_ARGS` (1), `EXT_CONSTRUCTOR_KW_ARGS` (2), `EXT_METHOD_SINGLE_ARG` (3), `EXT_PYDANTIC_V1` (4), `EXT_PYDANTIC_V2` (5), `EXT_NUMPY_ARRAY` (6). The `BaseCache` component uses `JsonPlusSerializer(pickle_fallback=False)` but inherits the same msgpack `allowed_modules` default behavior. The proposed `RestrictedUnpickler` (`secure_pickle.py`) documented in `SECURITY_FIX_SUMMARY.md` was never merged — pickle remains unrestricted when enabled.
|
||||
- **Preconditions**: Attacker must have write access to the checkpoint database (PostgreSQL or SQLite). This requires compromised database credentials or a co-located attacker.
|
||||
|
||||
#### T2: Pickle Deserialization RCE
|
||||
|
||||
- **Flow**: DF1 (Checkpoint Storage -> JsonPlusSerializer)
|
||||
- **Description**: When `pickle_fallback=True` is explicitly passed to `JsonPlusSerializer`, checkpoint data with type tag `"pickle"` is deserialized via `pickle.loads()` with zero restrictions (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer.loads_typed`).
|
||||
- **Preconditions**: (1) Application or checkpointer explicitly enables `pickle_fallback=True`. (2) Attacker writes `("pickle", <payload>)` to checkpoint storage.
|
||||
|
||||
#### T3: JSON lc:2 Constructor RCE
|
||||
|
||||
- **Flow**: DF1 (Checkpoint Storage -> JsonPlusSerializer)
|
||||
- **Description**: The JSON `_reviver` handles `lc:2` type constructors by importing the module path from checkpoint JSON data via `importlib.import_module` (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:JsonPlusSerializer._revive_lc2`). If `allowed_json_modules=True` (explicit opt-in), any module reachable in the Python environment can be imported and instantiated. The method also supports method chaining — a `method` key in the JSON can call arbitrary methods on the imported class.
|
||||
- **Preconditions**: (1) `allowed_json_modules` set to `True` (not the default). (2) Attacker writes crafted JSON to checkpoint storage.
|
||||
|
||||
#### T4: RemoteGraph Unvalidated Inbound Data
|
||||
|
||||
- **Flow**: DF5 (RemoteGraph -> Pregel)
|
||||
- **Description**: Stream events from the remote LangGraph Server are deserialized from JSON and dict-splatted into `Interrupt(**i)` and `Command(**chunk.data)` without schema validation (`libs/langgraph/langgraph/pregel/remote.py:RemoteGraph.stream`). A compromised or malicious remote server can inject unexpected fields. `Command.update` can carry arbitrary state modifications; `Command.goto` can alter graph execution flow. `Interrupt` accepts `**deprecated_kwargs` which includes a `ns` parameter that can override interrupt ID generation via `xxh3_128_hexdigest`.
|
||||
- **Preconditions**: User connects `RemoteGraph` to a compromised or attacker-controlled server URL.
|
||||
|
||||
#### T5: Dockerfile ENV Single-Quote Injection
|
||||
|
||||
- **Flow**: DF6, DF7 (langgraph.json -> CLI -> Dockerfile)
|
||||
- **Description**: Config values from `langgraph.json` are serialized via `json.dumps()` and embedded in single-quoted `ENV` directives across multiple config sections (store, auth, encryption, http, webhooks, checkpointer, ui, ui_config, graphs). JSON does not escape single quotes, so a config value containing `'` could break the Dockerfile syntax or inject additional Dockerfile instructions. The pattern is duplicated in two Dockerfile generation functions (`libs/cli/langgraph_cli/config.py:python_config_to_docker` and `libs/cli/langgraph_cli/config.py:node_config_to_docker`).
|
||||
- **Preconditions**: A `langgraph.json` config value contains a single quote character.
|
||||
|
||||
#### T6: ZIP Slip in Template Extraction
|
||||
|
||||
- **Flow**: DF7 (CLI template download)
|
||||
- **Description**: `langgraph new` downloads a ZIP from GitHub and uses `zip_file.extractall(path)`. If the archive contains path-traversal entries (e.g., `../../etc/cron.d/exploit`), files could be written outside the target directory.
|
||||
- **Preconditions**: The GitHub-hosted template archive must contain malicious path entries. This requires compromise of the upstream template repo.
|
||||
|
||||
#### T7: AES Key Entropy via Environment Variable
|
||||
|
||||
- **Flow**: DF10 (User config -> EncryptedSerializer)
|
||||
- **Description**: The AES key is loaded from `LANGGRAPH_AES_KEY` as a UTF-8 string and `.encode()`d to bytes (`libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:EncryptedSerializer.from_pycryptodome_aes`). This limits key entropy to printable characters (~6.57 bits/byte vs. 8 bits/byte for random bytes), reducing effective key strength for AES-128 from 128 bits to ~105 bits.
|
||||
- **Preconditions**: User relies on environment variable path for key loading (vs. passing raw bytes directly via `key=` parameter).
|
||||
|
||||
#### T8: EncryptedSerializer Assert Bypass
|
||||
|
||||
- **Flow**: DF10 (Encrypted checkpoint data)
|
||||
- **Description**: The cipher name check in `decrypt()` uses `assert ciphername == "aes"` (`libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:PycryptodomeAesCipher.decrypt`), which is stripped when Python runs with `-O` (optimize) flag. The `ciphername` value comes from the type tag in checkpoint storage (split from the `type+cipher` format).
|
||||
- **Preconditions**: Python running with `-O` flag AND attacker can write to checkpoint storage.
|
||||
|
||||
#### T9: SDK API Key Leak via Server-Controlled Location Redirect
|
||||
|
||||
- **Flow**: DF12 (Server -> SDK), DF13 (SDK -> Redirect target)
|
||||
- **Description**: The SDK's `HttpClient.request_reconnect()` (`libs/sdk-py/langgraph_sdk/_async/http.py:HttpClient.request_reconnect`) follows server-provided `Location` headers and forwards the full `request_headers` dict (including the `x-api-key` authentication header) to the redirected URL. The `HttpClient.stream()` method (`libs/sdk-py/langgraph_sdk/_async/http.py:HttpClient.stream`) also follows `Location` headers for SSE reconnection and forwards `reconnect_headers` (which include `x-api-key`) to the server-controlled URL. No URL validation, same-origin check, or sensitive header stripping is performed before following the redirect. The same pattern exists in the sync client (`libs/sdk-py/langgraph_sdk/_sync/http.py`).
|
||||
- **Preconditions**: (1) User connects SDK to a LangGraph Server that is compromised or attacker-controlled. (2) The server returns a response with a `Location` header pointing to an attacker-controlled URL.
|
||||
|
||||
#### T10: EncryptedSerializer Encryption Bypass via Unencrypted Data Injection
|
||||
|
||||
- **Flow**: DF1 (Checkpoint Storage -> EncryptedSerializer)
|
||||
- **Description**: `EncryptedSerializer.loads_typed()` (`libs/checkpoint/langgraph/checkpoint/serde/encrypted.py:EncryptedSerializer.loads_typed`) checks if the type tag contains a `+` delimiter. If it does not (e.g., type tag is `"msgpack"` instead of `"msgpack+aes"`), the data is passed directly to the inner serde's `loads_typed()` **without any decryption or MAC verification**. An attacker with write access to checkpoint storage can bypass the encryption layer entirely by writing data with a plain type tag.
|
||||
- **Preconditions**: (1) Application uses `EncryptedSerializer` for checkpoint protection. (2) Attacker has write access to checkpoint storage.
|
||||
|
||||
#### T11: Unbounded Checkpoint Data Retention
|
||||
|
||||
- **Flow**: DF1, DF11 (Checkpoint Storage lifecycle)
|
||||
- **Description**: Checkpoint data (DC3, DC6) is retained indefinitely by default. No built-in TTL, pruning, or data lifecycle management in the library-level checkpoint savers. Conversation history containing user PII may accumulate without bounds.
|
||||
- **Preconditions**: Application uses checkpointing (the primary use case). No explicit cleanup configured.
|
||||
|
||||
---
|
||||
|
||||
## Input Source Coverage
|
||||
|
||||
| Input Source | Data Flows | Threats | Validation Points | Responsibility | Gaps |
|
||||
|-------------|-----------|---------|-------------------|----------------|------|
|
||||
| User direct input (graph state, config) | DF8 | — | Graph structure validation (`libs/langgraph/langgraph/pregel/_validate.py:validate_graph`), channel type enforcement (`libs/langgraph/langgraph/channels/base.py:BaseChannel`), sensitive key filtering (`libs/langgraph/langgraph/_internal/_config.py:_exclude_as_metadata`) | User | Node implementation safety is user's responsibility |
|
||||
| LLM output (tool calls) | DF3, DF4, DF14 | — | Tool name allowlist (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._validate_tool_call`), tool Pydantic schemas, injection merge order (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._inject_tool_args`), `tool_call_schema` filtering of injected params | Shared (project validates name and injection safety; user validates args via tool schema) | No ToolNode-level argument sanitization beyond injection overwrite |
|
||||
| Checkpoint storage data | DF1, DF2, DF11 | T1, T2, T3, T10 | Msgpack allowlist (`libs/checkpoint/langgraph/checkpoint/serde/_msgpack.py:SAFE_MSGPACK_TYPES` — 47 entries), msgpack method allowlist (`libs/checkpoint/langgraph/checkpoint/serde/_msgpack.py:SAFE_MSGPACK_METHODS`), JSON allowlist (`libs/checkpoint/langgraph/checkpoint/serde/jsonplus.py:_check_allowed_json_modules`), pickle gating, serde event hooks, optional encryption | Shared (project owns serializer defaults; user owns DB access controls) | Default msgpack mode allows unregistered types; EncryptedSerializer accepts unencrypted data; proposed secure_pickle.py never merged |
|
||||
| Remote API responses | DF5, DF9, DF12, DF13 | T4, T9 | Outbound config sanitization (`libs/langgraph/langgraph/pregel/remote.py:_sanitize_config`); no inbound validation; no redirect URL validation | User (user chooses which server to trust) | No inbound schema validation; API key forwarded on redirects |
|
||||
| Configuration (langgraph.json) | DF6, DF7 | T5 | JSON schema validation (`libs/cli/langgraph_cli/config.py:validate_config_file`), build command content validation (`libs/cli/langgraph_cli/config.py:has_disallowed_build_command_content`), list-based subprocess args, WebhookUrlPolicy (`libs/cli/langgraph_cli/schemas.py:WebhookUrlPolicy`) | User (developer-controlled file) | Single-quote not escaped in ENV embedding |
|
||||
| Configuration (env vars) | DF10 | T7, T8 | AES key length validation, EAX MAC verification | User (deployer controls env) | Key entropy, assert-based check |
|
||||
| Developer encryption handlers | DF15 | — | Handler signature validation (`libs/sdk-py/langgraph_sdk/encryption/__init__.py:_validate_handler`), duplicate prevention | User (developer-authored code) | `context()` handler missing `_validate_handler` call |
|
||||
|
||||
---
|
||||
|
||||
## Out-of-Scope Threats
|
||||
|
||||
Threats that appear valid in isolation but fall outside project responsibility because they depend on conditions the project does not control.
|
||||
|
||||
| Pattern | Why Out of Scope | Project Responsibility Ends At |
|
||||
|---------|-----------------|-------------------------------|
|
||||
| Prompt injection leading to arbitrary tool execution | Project does not control LLM model behavior, user prompt construction, or which tools are registered. ToolNode routes by name only to user-registered tools. | Providing tool name allowlist routing (`libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._validate_tool_call`); user owns tool registration and argument handling |
|
||||
| State poisoning via malicious node output | User-registered nodes (including `@task`-decorated functions) can write arbitrary values to channels. The framework executes nodes as provided. | Enforcing channel type contracts (`libs/langgraph/langgraph/channels/base.py:BaseChannel.update`); user owns node implementation correctness |
|
||||
| Cross-session state access via thread_id guessing | Checkpoint savers index by `thread_id`. Without application-level auth, any caller with a valid thread_id can access that thread's state. | Providing the `Auth` handler system for access control (`libs/sdk-py/langgraph_sdk/auth/__init__.py:Auth`); user must implement auth handlers |
|
||||
| Tool shadowing via duplicate registration | If a user registers two tools with the same name, ToolNode uses the last one. This is user misconfiguration. | Documenting tool registration semantics |
|
||||
| Indirect prompt injection via tool output | LLM reads tool output and may follow injected instructions. This is a fundamental LLM limitation, not a framework vulnerability. | Not including tool output in system prompts; user owns output handling |
|
||||
| Model selecting dangerous tool arguments | An LLM may generate SQL injection, path traversal, or command injection payloads as tool arguments. The risk depends entirely on what the user's tools do with those arguments. | Routing tool calls to registered tools only; user owns tool input validation |
|
||||
| RCE via user-provided node code | `add_node()` and `@entrypoint`/`@task` accept arbitrary callables. A malicious node can do anything. This is by design — the user controls their own code. | Executing nodes within the graph runtime; user owns node code safety |
|
||||
| SSRF via RemoteGraph URL | User provides the `url` parameter to `RemoteGraph`. Pointing it at an internal service is the user's decision. | Documenting that `url` should be a trusted endpoint; user owns URL selection |
|
||||
| Malicious SDK Encryption handler | Encryption handlers are developer-authored server-side code. A malicious handler has full process access, equivalent to any application code. | Validating handler signature (async, param count); handler behavior is the developer's responsibility |
|
||||
|
||||
### Rationale
|
||||
|
||||
**Prompt injection and tool execution**: LangGraph's `ToolNode` validates tool names against the registered set but does not inspect or sanitize argument values. This is the correct boundary — the framework cannot know what constitutes a "safe" argument for an arbitrary user-defined tool. The tool's own Pydantic schema and implementation must validate inputs. The framework's responsibility is to not execute unregistered tools and to correctly route registered ones. The injection system (InjectedState/InjectedStore/ToolRuntime) is safe because system-injected values always overwrite LLM-supplied collisions via dict merge order, and injected parameter names are hidden from the LLM's tool schema.
|
||||
|
||||
**State integrity**: LangGraph channels enforce type contracts (e.g., `LastValue` accepts one value per step, `BinaryOperatorAggregate` applies a reducer). The framework validates graph structure at compile time (`libs/langgraph/langgraph/pregel/_validate.py:validate_graph`). However, the semantic correctness of state updates is the user's responsibility — the framework cannot know what values are "valid" for a user-defined state schema.
|
||||
|
||||
**Checkpoint access control**: The framework provides `BaseCheckpointSaver` as an abstract interface and the `Auth` handler system for authorization (`libs/sdk-py/langgraph_sdk/auth/__init__.py:Auth`). It does not enforce authentication by default because it operates as a library, not a server. The `langgraph-api` server layer (out of scope) is responsible for enforcing auth on API endpoints. Users embedding LangGraph directly must implement their own access controls.
|
||||
|
||||
**Encryption handler safety**: The SDK Encryption module (`libs/sdk-py/langgraph_sdk/encryption/`) provides a registration framework for developer-authored encryption handlers. These handlers run server-side with full process access, identical to any application code. A buggy or malicious handler could return crafted data, but this is the same trust model as any developer-written code. The SDK validates handler shape (async, 2-param) but not handler behavior — this is the correct boundary for developer-trust-level code.
|
||||
|
||||
---
|
||||
|
||||
## Investigated and Dismissed
|
||||
|
||||
| ID | Original Threat | Investigation | Evidence | Conclusion |
|
||||
|----|----------------|---------------|----------|------------|
|
||||
| D1 | SQL injection via filter keys in PostgreSQL store | Traced filter key handling through `libs/checkpoint-postgres/langgraph/store/postgres/base.py:_get_filter_condition`. All filter operations use parameterized queries with `%s` placeholders. Keys map to `json_extract` path operators with type-safe wrappers. | `libs/checkpoint-postgres/langgraph/store/postgres/base.py:_get_filter_condition` — parameterized `%s` for all value bindings; key names used in `value->%s` path expressions are also parameterized | Disproven: All SQL operations in PostgreSQL store are fully parameterized. No injection vector. |
|
||||
| D2 | SQL injection via filter keys in SQLite store (post-fix) | Traced current filter handling through `libs/checkpoint-sqlite/langgraph/store/sqlite/base.py` and `libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/utils.py:_validate_filter_key`. Regex `^[a-zA-Z0-9_.-]+$` applied to all filter keys before use in `json_extract()` expressions. | `libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/utils.py:_validate_filter_key` — regex validation blocks injection characters. Published advisories GHSA-9rwj-6rc7-p77c and GHSA-7p73-8jqx-23r8 confirmed fixed. | Disproven: SQL injection in SQLite store filter keys is remediated by regex validation. |
|
||||
| D3 | Command injection via CLI subprocess execution | Traced CLI subprocess invocation path. `libs/cli/langgraph_cli/exec.py:subp_exec` uses `asyncio.create_subprocess_exec` with list-based arguments (not `shell=True`). `has_disallowed_build_command_content` blocks shell metacharacters in user-provided Dockerfile lines. | `libs/cli/langgraph_cli/exec.py:subp_exec` — explicit exec-style invocation; `libs/cli/langgraph_cli/config.py:has_disallowed_build_command_content` — regex blocks `\|`, `;`, `$`, `>`, `<`, backtick, `\`, single `&` | Disproven: CLI uses exec-style subprocess and validates build command content. No shell injection vector. |
|
||||
| D4 | Tool argument injection via InjectedState/InjectedStore dict-splatting | Investigated whether LLM-generated tool call arguments could override system-injected values (InjectedState, InjectedStore, ToolRuntime) via key collision in the dict merge at `libs/prebuilt/langgraph/prebuilt/tool_node.py:ToolNode._inject_tool_args` line 1380. Traced four independent defense layers. | (1) `tool_call_schema` at langchain-core `base.py` filters injected params from LLM schema. (2) `{**llm_args, **injected_args}` merge puts system values last — system wins on collision. (3) Pydantic `model_validate` with `extra="ignore"` drops unknown keys. (4) Output construction at `base.py` only includes declared model fields. | Disproven: Four-layer defense prevents LLM arguments from overriding system-injected values. Merge order guarantees system values win. No adversarial collision path exists. |
|
||||
|
||||
---
|
||||
|
||||
## External Context
|
||||
|
||||
### Published Security Advisories
|
||||
|
||||
| GHSA ID | Severity | Summary | CWEs | Relevance |
|
||||
|---------|----------|---------|------|-----------|
|
||||
| GHSA-g48c-2wqr-h844 | Medium | Unsafe msgpack deserialization in LangGraph checkpoint loading | — | Directly relates to T1 — patched in 1.0.10, confirms attack path via crafted msgpack payloads |
|
||||
| GHSA-mhr3-j7m5-c7c9 | Medium | BaseCache Deserialization RCE | CWE-502 | Directly relates to T1 — msgpack deserialization in cache layer |
|
||||
| GHSA-9rwj-6rc7-p77c | High | SQL injection via metadata filter key in SQLite checkpointer | CWE-89 | Fixed via `_validate_filter_key()` regex — see D2 |
|
||||
| GHSA-wwqv-p2pp-99h5 | High | RCE in JSON mode of JsonPlusSerializer | CWE-502 | Directly relates to T3 — `lc:2` constructor import |
|
||||
| GHSA-7p73-8jqx-23r8 | High | SQLite Filter Key SQL Injection in SqliteStore | CWE-89 | Fixed via `_validate_filter_key()` regex — see D2 |
|
||||
|
||||
**Pattern**: 3 of 5 published advisories involve CWE-502 (insecure deserialization) in the checkpoint serialization layer. This confirms the checkpoint storage boundary (TB2) as the highest-risk area. The extensive closed advisory history (~15 deserialization bypass attempts) further validates this assessment. No new published advisories since the prior assessment (2026-03-27).
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Revision History
|
||||
|
||||
| Date | Author | Changes |
|
||||
|------|--------|---------|
|
||||
| 2026-03-04 | Generated | Initial threat model |
|
||||
| 2026-03-04 | Updated | Added C13 (Functional API), C14 (BaseCache), DF11. Updated T1 for BaseCache/serde event hooks. Added GHSA-mhr3-j7m5-c7c9 and GHSA-9rwj-6rc7-p77c. Updated CLI config scope. Added External Context section. |
|
||||
| 2026-03-27 | Deep refinement | **Mode upgraded to Deep.** Added: Data Classification section (DC1-DC8 with detailed analysis for Critical/High entries). Added: C15 (Serde Event Hooks), C16 (Auth System). Added: Default? column to Components. Added: Classification column to Data Flows. Added: DF12-DF13 (SDK redirect flows). Added: T9 (SDK API key leak via Location redirect), T10 (EncryptedSerializer encryption bypass), T11 (unbounded checkpoint retention). Added: Validation column to Threats with flaw validation for High/Critical. Added: Investigated and Dismissed section (D1-D3: SQL injection and CLI command injection disproven). Added: Input Source Coverage section. Updated external context with GHSA-g48c-2wqr-h844 (new published advisory). Updated all code references to file:SymbolName notation. Expanded trust boundary details. |
|
||||
| 2026-03-30 | Diagram and Default? corrections | Fixed architecture diagram: merged "User Code" and "User-Registered Tools" into single "User Application Code" boundary; removed @entrypoint/@task as separate diagram elements (both compile to Pregel — authoring style, not separate component). Fixed Default? column: C3 ToolNode → No (explicit opt-in required); C8 CLI → No (separate install). |
|
||||
| 2026-03-28 | Deep update | **Added:** C17 (SDK Encryption Handlers — beta at-rest encryption framework). DC9 (SDK Encryption context metadata). TB5 (SDK Encryption Handler boundary). DF14 (ToolRuntime injection flow), DF15 (Encryption handler registration flow). D4 (Tool argument injection via InjectedState dict-splatting — disproven with 4-layer defense evidence). **Updated:** C1 description (v1/v2 output, durability modes, interrupt_before/after). C2 description (SAFE_MSGPACK_TYPES now 47 entries including langchain_core messages, Document, GetOp). C3 description (InjectedState/InjectedStore/ToolRuntime injection support, _inject_tool_args entry point). C8 description (WebhookUrlPolicy for SSRF protection). TB1 details (tool injection merge order guarantees). TB2 details (47 safe types, updated allowlist composition). TB4 details (WebhookUrlPolicy). DF4 description (injection merge semantics). T1 details (noted secure_pickle.py proposed but never merged). T4 details (Interrupt deprecated_kwargs ns parameter). Input Source Coverage (LLM output row updated with injection validation points, encryption handler row added). Out-of-Scope Threats (malicious encryption handler pattern added). Commit updated to 0ba22143. External context confirmed no new published advisories. |
|
||||
@@ -0,0 +1,35 @@
|
||||
# Helper to set up Python and uv with caching
|
||||
|
||||
name: uv-install
|
||||
description: Set up Python and uv with caching
|
||||
|
||||
inputs:
|
||||
python-version:
|
||||
description: Python version, supporting MAJOR.MINOR only
|
||||
required: true
|
||||
enable-cache:
|
||||
description: Enable caching for uv dependencies
|
||||
required: false
|
||||
default: "true"
|
||||
cache-suffix:
|
||||
description: Custom cache key suffix for cache invalidation
|
||||
required: false
|
||||
default: ""
|
||||
working-directory:
|
||||
description: Working directory for cache glob scoping
|
||||
required: false
|
||||
default: "**"
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install uv and set the python version
|
||||
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
|
||||
with:
|
||||
python-version: ${{ inputs.python-version }}
|
||||
enable-cache: ${{ inputs.enable-cache }}
|
||||
cache-dependency-glob: |
|
||||
${{ inputs.working-directory }}/pyproject.toml
|
||||
${{ inputs.working-directory }}/uv.lock
|
||||
${{ inputs.working-directory }}/requirements*.txt
|
||||
cache-suffix: ${{ inputs.cache-suffix }}
|
||||
@@ -0,0 +1,188 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/checkpoint"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/checkpoint-conformance"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/checkpoint-postgres"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/checkpoint-sqlite"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/cli"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/langgraph"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/prebuilt"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "uv"
|
||||
directory: "/libs/sdk-py"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/libs/cli/js-examples"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/libs/cli/js-monorepo-example"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
major:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "major"
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg width="472" height="100" viewBox="0 0 472 100" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="100" y="6.10352e-05" width="100" height="100" rx="20" transform="rotate(90 100 6.10352e-05)" fill="#161F34"/>
|
||||
<path d="M32.1494 67.8579H45.2266C45.2246 75.0778 39.3716 80.93 32.1514 80.9302C24.9301 80.9301 19.0756 75.0762 19.0752 67.855C19.0752 60.6341 24.9288 54.78 32.1494 54.7788V67.8579ZM67.8691 54.7788C75.0906 54.779 80.9443 60.6335 80.9443 67.855C80.944 75.0762 75.0904 80.93 67.8691 80.9302C60.6488 80.9301 54.7949 75.0778 54.793 67.8579H67.8594V54.7788C67.8626 54.7788 67.8659 54.7788 67.8691 54.7788ZM67.8691 19.0757C75.0906 19.0759 80.9443 24.9304 80.9443 32.1519C80.944 39.3731 75.0904 45.2269 67.8691 45.2271C67.8659 45.2271 67.8626 45.2261 67.8594 45.2261V32.1479H54.793C54.795 24.9281 60.6489 19.0758 67.8691 19.0757ZM32.1514 19.0757C39.3716 19.0759 45.2246 24.9281 45.2266 32.1479H32.1494V45.2261C24.929 45.2249 19.0755 39.3725 19.0752 32.1519C19.0752 24.9303 24.9299 19.0758 32.1514 19.0757Z" fill="#7FC8FF"/>
|
||||
<path d="M142.427 70.248V65.748H153.227V32.748H142.427V28.248H158.147V65.748H168.947V70.248H142.427ZM189.174 70.608C182.454 70.608 177.894 67.248 177.894 61.668C177.894 55.548 182.154 52.128 190.194 52.128H199.194V50.028C199.194 46.068 196.374 43.668 191.574 43.668C187.254 43.668 184.374 45.708 183.774 48.828H178.854C179.574 42.828 184.434 39.288 191.814 39.288C199.614 39.288 204.114 43.188 204.114 50.328V63.708C204.114 65.328 204.714 65.748 206.094 65.748H207.654V70.248H204.954C200.874 70.248 199.494 68.508 199.434 65.508C197.514 68.268 194.454 70.608 189.174 70.608ZM189.534 66.408C195.654 66.408 199.194 62.868 199.194 57.768V56.268H189.714C185.334 56.268 182.874 57.888 182.874 61.368C182.874 64.368 185.454 66.408 189.534 66.408ZM216.601 70.248V39.648H220.861L221.521 43.788C223.321 41.448 226.321 39.288 231.121 39.288C237.601 39.288 243.001 42.948 243.001 52.848V70.248H238.081V53.148C238.081 47.028 235.201 43.788 230.281 43.788C224.941 43.788 221.521 47.928 221.521 53.988V70.248H216.601ZM266.348 82.608C258.548 82.608 253.088 78.948 252.308 72.228H257.348C258.188 76.068 261.608 78.228 266.708 78.228C273.128 78.228 276.608 75.228 276.608 68.568V64.968C274.568 68.448 271.268 70.608 266.108 70.608C257.648 70.608 251.408 64.908 251.408 54.948C251.408 45.588 257.648 39.288 266.108 39.288C271.268 39.288 274.688 41.508 276.608 44.928L277.268 39.648H281.528V68.748C281.528 77.568 276.848 82.608 266.348 82.608ZM266.588 66.228C272.588 66.228 276.668 61.608 276.668 55.068C276.668 48.348 272.588 43.668 266.588 43.668C260.528 43.668 256.448 48.288 256.448 54.948C256.448 61.608 260.528 66.228 266.588 66.228ZM303.555 82.608C295.755 82.608 290.295 78.948 289.515 72.228H294.555C295.395 76.068 298.815 78.228 303.915 78.228C310.335 78.228 313.815 75.228 313.815 68.568V64.968C311.775 68.448 308.475 70.608 303.315 70.608C294.855 70.608 288.615 64.908 288.615 54.948C288.615 45.588 294.855 39.288 303.315 39.288C308.475 39.288 311.895 41.508 313.815 44.928L314.475 39.648H318.735V68.748C318.735 77.568 314.055 82.608 303.555 82.608ZM303.795 66.228C309.795 66.228 313.875 61.608 313.875 55.068C313.875 48.348 309.795 43.668 303.795 43.668C297.735 43.668 293.655 48.288 293.655 54.948C293.655 61.608 297.735 66.228 303.795 66.228ZM327.862 70.248V65.748H335.422V44.148H327.862V39.648H340.222V44.928C341.602 42.588 344.482 39.648 350.482 39.648H355.582V44.448H349.942C342.562 44.448 340.342 49.968 340.342 54.828V65.748H353.902V70.248H327.862ZM375.209 70.608C368.489 70.608 363.929 67.248 363.929 61.668C363.929 55.548 368.189 52.128 376.229 52.128H385.229V50.028C385.229 46.068 382.409 43.668 377.609 43.668C373.289 43.668 370.409 45.708 369.809 48.828H364.889C365.609 42.828 370.469 39.288 377.849 39.288C385.649 39.288 390.149 43.188 390.149 50.328V63.708C390.149 65.328 390.749 65.748 392.129 65.748H393.689V70.248H390.989C386.909 70.248 385.529 68.508 385.469 65.508C383.549 68.268 380.489 70.608 375.209 70.608ZM375.569 66.408C381.689 66.408 385.229 62.868 385.229 57.768V56.268H375.749C371.369 56.268 368.909 57.888 368.909 61.368C368.909 64.368 371.489 66.408 375.569 66.408ZM401.076 82.248V39.648H405.336L405.996 44.568C408.036 41.748 411.336 39.288 416.496 39.288C424.956 39.288 431.196 44.988 431.196 54.948C431.196 64.308 424.956 70.608 416.496 70.608C411.336 70.608 407.856 68.508 405.996 65.568V82.248H401.076ZM416.016 66.228C422.076 66.228 426.156 61.608 426.156 54.948C426.156 48.288 422.076 43.668 416.016 43.668C410.016 43.668 405.936 48.288 405.936 54.828C405.936 61.548 410.016 66.228 416.016 66.228ZM439.663 70.248V28.248H444.583V43.788C446.863 40.968 450.403 39.288 454.363 39.288C462.043 39.288 466.423 44.388 466.423 53.208V70.248H461.503V53.508C461.503 47.268 458.623 43.788 453.523 43.788C448.063 43.788 444.583 48.108 444.583 54.948V70.248H439.663Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,5 @@
|
||||
<svg width="472" height="100" viewBox="0 0 472 100" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="100" width="100" height="100" rx="20" transform="rotate(90 100 0)" fill="#161F34"/>
|
||||
<path d="M32.1494 67.8578H45.2266C45.2246 75.0776 39.3716 80.9299 32.1514 80.9301C24.9301 80.9299 19.0756 75.0761 19.0752 67.8549C19.0752 60.634 24.9288 54.7799 32.1494 54.7787V67.8578ZM67.8691 54.7787C75.0906 54.7789 80.9443 60.6334 80.9443 67.8549C80.944 75.076 75.0904 80.9299 67.8691 80.9301C60.6488 80.9299 54.7949 75.0777 54.793 67.8578H67.8594V54.7787C67.8626 54.7787 67.8659 54.7787 67.8691 54.7787ZM67.8691 19.0756C75.0906 19.0758 80.9443 24.9303 80.9443 32.1517C80.944 39.373 75.0904 45.2267 67.8691 45.2269C67.8659 45.2269 67.8626 45.226 67.8594 45.226V32.1478H54.793C54.795 24.928 60.6489 19.0757 67.8691 19.0756ZM32.1514 19.0756C39.3716 19.0757 45.2246 24.928 45.2266 32.1478H32.1494V45.226C24.929 45.2248 19.0755 39.3724 19.0752 32.1517C19.0752 24.9302 24.9299 19.0757 32.1514 19.0756Z" fill="#7FC8FF"/>
|
||||
<path d="M142.427 70.248V65.748H153.227V32.748H142.427V28.248H158.147V65.748H168.947V70.248H142.427ZM189.174 70.608C182.454 70.608 177.894 67.248 177.894 61.668C177.894 55.548 182.154 52.128 190.194 52.128H199.194V50.028C199.194 46.068 196.374 43.668 191.574 43.668C187.254 43.668 184.374 45.708 183.774 48.828H178.854C179.574 42.828 184.434 39.288 191.814 39.288C199.614 39.288 204.114 43.188 204.114 50.328V63.708C204.114 65.328 204.714 65.748 206.094 65.748H207.654V70.248H204.954C200.874 70.248 199.494 68.508 199.434 65.508C197.514 68.268 194.454 70.608 189.174 70.608ZM189.534 66.408C195.654 66.408 199.194 62.868 199.194 57.768V56.268H189.714C185.334 56.268 182.874 57.888 182.874 61.368C182.874 64.368 185.454 66.408 189.534 66.408ZM216.601 70.248V39.648H220.861L221.521 43.788C223.321 41.448 226.321 39.288 231.121 39.288C237.601 39.288 243.001 42.948 243.001 52.848V70.248H238.081V53.148C238.081 47.028 235.201 43.788 230.281 43.788C224.941 43.788 221.521 47.928 221.521 53.988V70.248H216.601ZM266.348 82.608C258.548 82.608 253.088 78.948 252.308 72.228H257.348C258.188 76.068 261.608 78.228 266.708 78.228C273.128 78.228 276.608 75.228 276.608 68.568V64.968C274.568 68.448 271.268 70.608 266.108 70.608C257.648 70.608 251.408 64.908 251.408 54.948C251.408 45.588 257.648 39.288 266.108 39.288C271.268 39.288 274.688 41.508 276.608 44.928L277.268 39.648H281.528V68.748C281.528 77.568 276.848 82.608 266.348 82.608ZM266.588 66.228C272.588 66.228 276.668 61.608 276.668 55.068C276.668 48.348 272.588 43.668 266.588 43.668C260.528 43.668 256.448 48.288 256.448 54.948C256.448 61.608 260.528 66.228 266.588 66.228ZM303.555 82.608C295.755 82.608 290.295 78.948 289.515 72.228H294.555C295.395 76.068 298.815 78.228 303.915 78.228C310.335 78.228 313.815 75.228 313.815 68.568V64.968C311.775 68.448 308.475 70.608 303.315 70.608C294.855 70.608 288.615 64.908 288.615 54.948C288.615 45.588 294.855 39.288 303.315 39.288C308.475 39.288 311.895 41.508 313.815 44.928L314.475 39.648H318.735V68.748C318.735 77.568 314.055 82.608 303.555 82.608ZM303.795 66.228C309.795 66.228 313.875 61.608 313.875 55.068C313.875 48.348 309.795 43.668 303.795 43.668C297.735 43.668 293.655 48.288 293.655 54.948C293.655 61.608 297.735 66.228 303.795 66.228ZM327.862 70.248V65.748H335.422V44.148H327.862V39.648H340.222V44.928C341.602 42.588 344.482 39.648 350.482 39.648H355.582V44.448H349.942C342.562 44.448 340.342 49.968 340.342 54.828V65.748H353.902V70.248H327.862ZM375.209 70.608C368.489 70.608 363.929 67.248 363.929 61.668C363.929 55.548 368.189 52.128 376.229 52.128H385.229V50.028C385.229 46.068 382.409 43.668 377.609 43.668C373.289 43.668 370.409 45.708 369.809 48.828H364.889C365.609 42.828 370.469 39.288 377.849 39.288C385.649 39.288 390.149 43.188 390.149 50.328V63.708C390.149 65.328 390.749 65.748 392.129 65.748H393.689V70.248H390.989C386.909 70.248 385.529 68.508 385.469 65.508C383.549 68.268 380.489 70.608 375.209 70.608ZM375.569 66.408C381.689 66.408 385.229 62.868 385.229 57.768V56.268H375.749C371.369 56.268 368.909 57.888 368.909 61.368C368.909 64.368 371.489 66.408 375.569 66.408ZM401.076 82.248V39.648H405.336L405.996 44.568C408.036 41.748 411.336 39.288 416.496 39.288C424.956 39.288 431.196 44.988 431.196 54.948C431.196 64.308 424.956 70.608 416.496 70.608C411.336 70.608 407.856 68.508 405.996 65.568V82.248H401.076ZM416.016 66.228C422.076 66.228 426.156 61.608 426.156 54.948C426.156 48.288 422.076 43.668 416.016 43.668C410.016 43.668 405.936 48.288 405.936 54.828C405.936 61.548 410.016 66.228 416.016 66.228ZM439.663 70.248V28.248H444.583V43.788C446.863 40.968 450.403 39.288 454.363 39.288C462.043 39.288 466.423 44.388 466.423 53.208V70.248H461.503V53.508C461.503 47.268 458.623 43.788 453.523 43.788C448.063 43.788 444.583 48.108 444.583 54.948V70.248H439.663Z" fill="#161F34"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,69 @@
|
||||
import ast
|
||||
import os
|
||||
from itertools import filterfalse
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
ROOT_PATH = os.path.abspath(os.path.join(__file__, "..", "..", ".."))
|
||||
CLIENT_PATH = os.path.join(ROOT_PATH, "libs", "sdk-py", "langgraph_sdk", "client.py")
|
||||
ASYNC_TO_SYNC_METHOD_MAP: Dict[str, str] = {
|
||||
"aclose": "close",
|
||||
"__aenter__": "__enter__",
|
||||
"__aexit__": "__exit__",
|
||||
}
|
||||
|
||||
|
||||
def get_class_methods(node: ast.ClassDef) -> List[str]:
|
||||
return [n.name for n in node.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
|
||||
|
||||
|
||||
def find_classes(tree: ast.AST) -> List[Tuple[str, List[str]]]:
|
||||
classes = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ClassDef):
|
||||
methods = get_class_methods(node)
|
||||
classes.append((node.name, methods))
|
||||
return classes
|
||||
|
||||
|
||||
def compare_sync_async_methods(sync_methods: List[str], async_methods: List[str]) -> List[str]:
|
||||
sync_set = set(sync_methods)
|
||||
async_set = {ASYNC_TO_SYNC_METHOD_MAP.get(async_method, async_method) for async_method in async_methods}
|
||||
missing_in_sync = list(async_set - sync_set)
|
||||
missing_in_async = list(sync_set - async_set)
|
||||
return missing_in_sync + missing_in_async
|
||||
|
||||
|
||||
def main():
|
||||
with open(CLIENT_PATH, "r") as file:
|
||||
tree = ast.parse(file.read())
|
||||
|
||||
classes = find_classes(tree)
|
||||
|
||||
def is_sync(class_spec: Tuple[str, List[str]]) -> bool:
|
||||
return class_spec[0].startswith("Sync")
|
||||
|
||||
sync_class_name_to_methods = {class_name: class_methods for class_name, class_methods in filter(is_sync, classes)}
|
||||
async_class_name_to_methods = {class_name: class_methods for class_name, class_methods in filterfalse(is_sync, classes)}
|
||||
|
||||
mismatches = []
|
||||
|
||||
for async_class_name, async_class_methods in async_class_name_to_methods.items():
|
||||
sync_class_name = "Sync" + async_class_name
|
||||
sync_class_methods = sync_class_name_to_methods.get(sync_class_name, [])
|
||||
diff = compare_sync_async_methods(sync_class_methods, async_class_methods)
|
||||
if diff:
|
||||
mismatches.append((sync_class_name, async_class_name, diff))
|
||||
|
||||
if mismatches:
|
||||
error_message = "Mismatches found between sync and async client methods:\n"
|
||||
for sync_class_name, async_class_name, diff in mismatches:
|
||||
error_message += f"{sync_class_name} vs {async_class_name}:\n"
|
||||
for method in diff:
|
||||
error_message += f" - {method}\n"
|
||||
raise ValueError(error_message)
|
||||
|
||||
print("All sync and async client methods match.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
import logging
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
from urllib import error, request
|
||||
|
||||
import langgraph_cli
|
||||
import langgraph_cli.config
|
||||
import langgraph_cli.docker
|
||||
from langgraph_cli.cli import prepare_args_and_stdin
|
||||
from langgraph_cli.constants import DEFAULT_PORT
|
||||
from langgraph_cli.exec import Runner, subp_exec
|
||||
from langgraph_cli.progress import Progress
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def test(config: pathlib.Path, port: int, tag: str, verbose: bool):
|
||||
"""Spin up API with Postgres/Redis via docker compose and wait until ready."""
|
||||
logger.info("Starting test...")
|
||||
with Runner() as runner, Progress(message="Pulling...") as set:
|
||||
# Detect docker/compose capabilities
|
||||
capabilities = langgraph_cli.docker.check_capabilities(runner)
|
||||
|
||||
# Validate config and prepare compose stdin/args using built image
|
||||
config_json = langgraph_cli.config.validate_config_file(config)
|
||||
args, stdin = prepare_args_and_stdin(
|
||||
capabilities=capabilities,
|
||||
config_path=config,
|
||||
config=config_json,
|
||||
docker_compose=None,
|
||||
port=port,
|
||||
watch=False,
|
||||
debugger_port=None,
|
||||
debugger_base_url=f"http://127.0.0.1:{port}",
|
||||
postgres_uri=None,
|
||||
api_version=None,
|
||||
image=tag,
|
||||
base_image=None,
|
||||
)
|
||||
|
||||
# Compose up with wait (implies detach), similar to `langgraph up --wait`
|
||||
args_up = [*args, "up", "--remove-orphans", "--wait"]
|
||||
|
||||
compose_cmd = ["docker", "compose"]
|
||||
if capabilities.compose_type == "standalone":
|
||||
compose_cmd = ["docker-compose"]
|
||||
|
||||
set("Starting...")
|
||||
try:
|
||||
runner.run(
|
||||
subp_exec(
|
||||
*compose_cmd,
|
||||
*args_up,
|
||||
input=stdin,
|
||||
verbose=verbose,
|
||||
)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
# On failure, show diagnostics then ensure clean teardown
|
||||
sys.stderr.write(f"docker compose up failed: {e}\n")
|
||||
try:
|
||||
sys.stderr.write("\n== docker compose ps ==\n")
|
||||
runner.run(
|
||||
subp_exec(*compose_cmd, *args, "ps", input=stdin, verbose=True)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
sys.stderr.write("\n== docker compose logs (api) ==\n")
|
||||
runner.run(
|
||||
subp_exec(
|
||||
*compose_cmd,
|
||||
*args,
|
||||
"logs",
|
||||
"langgraph-api",
|
||||
input=stdin,
|
||||
verbose=True,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
runner.run(
|
||||
subp_exec(
|
||||
*compose_cmd,
|
||||
*args,
|
||||
"down",
|
||||
"-v",
|
||||
"--remove-orphans",
|
||||
input=stdin,
|
||||
verbose=False,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
raise
|
||||
|
||||
set("")
|
||||
base_url = f"http://localhost:{port}"
|
||||
ok_url = f"{base_url}/ok"
|
||||
logger.info(f"Waiting for {ok_url} to respond with 200...")
|
||||
deadline = time.time() + 30
|
||||
last_err: Exception | None = None
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with request.urlopen(ok_url, timeout=2) as resp:
|
||||
if resp.status == 200:
|
||||
sys.stdout.write(
|
||||
f"""Ready!\n- API: {base_url}\n- /ok: 200 OK\n"""
|
||||
)
|
||||
sys.stdout.flush()
|
||||
break
|
||||
else:
|
||||
last_err = RuntimeError(f"Unexpected status: {resp.status}")
|
||||
logger.error(f"Unexpected status: {resp.status}")
|
||||
except error.URLError as e:
|
||||
logger.error(f"URLError: {e}")
|
||||
last_err = e
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"Exception: {e}")
|
||||
last_err = e
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
logger.error("Timeout waiting for /ok to return 200")
|
||||
# Bring stack down before raising
|
||||
args_down = [*args, "down", "-v", "--remove-orphans"]
|
||||
try:
|
||||
runner.run(
|
||||
subp_exec(
|
||||
*compose_cmd,
|
||||
*args_down,
|
||||
input=stdin,
|
||||
verbose=verbose,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
raise SystemExit(
|
||||
f"/ok did not return 202 within timeout. Last error: {last_err}"
|
||||
)
|
||||
|
||||
# Clean up: bring compose stack down to free ports for next test
|
||||
logger.info("Test succeeded. Bringing down compose stack...")
|
||||
try:
|
||||
args_down = [*args, "down", "-v", "--remove-orphans"]
|
||||
runner.run(
|
||||
subp_exec(
|
||||
*compose_cmd,
|
||||
*args_down,
|
||||
input=stdin,
|
||||
verbose=verbose,
|
||||
)
|
||||
)
|
||||
logger.info("Compose stack down. Finishing...")
|
||||
except Exception:
|
||||
logger.exception("Failed to bring down compose stack")
|
||||
pass
|
||||
|
||||
logger.info("Test finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-t", "--tag", type=str)
|
||||
parser.add_argument("-c", "--config", type=str, default="./langgraph.json")
|
||||
parser.add_argument("-p", "--port", type=int, default=DEFAULT_PORT)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
test(pathlib.Path(args.config), args.port, args.tag, verbose=True)
|
||||
except BaseException:
|
||||
logger.exception("Test failed")
|
||||
raise
|
||||
|
||||
logger.info("Test execution finished")
|
||||
@@ -0,0 +1,168 @@
|
||||
name: CLI integration test
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
LANGSMITH_API_KEY:
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- "3.10"
|
||||
- "3.14"
|
||||
example:
|
||||
- name: A
|
||||
workdir: libs/cli/examples
|
||||
tag: langgraph-test-a
|
||||
- name: B
|
||||
workdir: libs/cli/examples/graphs
|
||||
tag: langgraph-test-b
|
||||
- name: C
|
||||
workdir: libs/cli/examples/graphs_reqs_a
|
||||
tag: langgraph-test-c
|
||||
- name: D
|
||||
workdir: libs/cli/examples/graphs_reqs_b
|
||||
tag: langgraph-test-d
|
||||
name: "CLI integration test"
|
||||
env:
|
||||
HAS_LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY != '' }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: libs/cli
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Get changed files
|
||||
id: changed-files
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
uses: Ana06/get-changed-files@25f79e676e7ea1868813e21465014798211fad8c # v2.3.0
|
||||
with:
|
||||
filter: "libs/cli/**"
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
if: (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch')
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
enable-cache: "false"
|
||||
working-directory: libs/cli
|
||||
- name: Install cli globally
|
||||
if: (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch')
|
||||
run: pip install -e .
|
||||
- name: Build service ${{ matrix.example.name }}
|
||||
if: (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch')
|
||||
working-directory: ${{ matrix.example.workdir }}
|
||||
run: |
|
||||
langgraph build -t ${{ matrix.example.tag }}
|
||||
- name: Test service ${{ matrix.example.name }}
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&env.HAS_LANGSMITH_API_KEY == 'true' }}
|
||||
working-directory: ${{ matrix.example.workdir }}
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: |
|
||||
# Prepare environment file from local or parent example directory
|
||||
if [ -f .env.example ]; then cp .env.example .env; elif [ -f ../.env.example ]; then cp ../.env.example .env && cp ../.env.example ../.env; fi
|
||||
echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> .env
|
||||
if [ -f ../.env ]; then echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> ../.env; fi
|
||||
# Run the integration test using the built tag
|
||||
REPO_ROOT=$(git rev-parse --show-toplevel)
|
||||
timeout 60 python "$REPO_ROOT/.github/scripts/run_langgraph_cli_test.py" -t ${{ matrix.example.tag }}
|
||||
|
||||
- name: Build JS service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/js-examples
|
||||
run: |
|
||||
langgraph build -t langgraph-test-e
|
||||
|
||||
- name: Build JS monorepo service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/js-monorepo-example
|
||||
run: |
|
||||
langgraph build -t langgraph-test-f -c apps/agent/langgraph.json --build-command "yarn run turbo build" --install-command "yarn install"
|
||||
|
||||
- name: Build Python monorepo service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/python-monorepo-example
|
||||
run: |
|
||||
langgraph build -t langgraph-test-g -c apps/agent/langgraph.json
|
||||
- name: Test Python monorepo service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' && env.HAS_LANGSMITH_API_KEY == 'true' }}
|
||||
working-directory: libs/cli/python-monorepo-example
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: |
|
||||
cp apps/agent/.env.example apps/agent/.env
|
||||
echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> apps/agent/.env
|
||||
timeout 60 python ../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-g -c apps/agent/langgraph.json
|
||||
|
||||
- name: Build prerelease reqs service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/examples/graph_prerelease_reqs
|
||||
run: |
|
||||
langgraph build -t langgraph-test-h
|
||||
- name: Test prerelease reqs service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' && env.HAS_LANGSMITH_API_KEY == 'true' }}
|
||||
working-directory: libs/cli/examples/graph_prerelease_reqs
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: |
|
||||
cp ../.env.example .env
|
||||
echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> .env
|
||||
timeout 60 python ../../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-h
|
||||
echo "Finished starting up langgraph-test-h"
|
||||
LANGGRAPH_VERSION=$(docker run --rm --entrypoint "" langgraph-test-h python -c "import sys; from importlib.metadata import version; v = version('langgraph'); print(v);")
|
||||
if [ "$LANGGRAPH_VERSION" != "1.1.5" ]; then
|
||||
echo "LANGGRAPH_VERSION != 1.1.5; $LANGGRAPH_VERSION"
|
||||
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.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);")
|
||||
if [ "$LANGCHAIN_ANTHROPIC_VERSION" != "1.4.6" ]; then
|
||||
echo "LANGCHAIN_ANTHROPIC_VERSION != 1.4.6; $LANGCHAIN_ANTHROPIC_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build and test prerelease reqs fail service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/examples/graph_prerelease_reqs_fail
|
||||
run: |
|
||||
langgraph build -t langgraph-test-i || [ $? -eq 1 ]
|
||||
|
||||
- name: Build uv simple service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/uv-examples/simple
|
||||
run: |
|
||||
langgraph build -t langgraph-test-uv-simple
|
||||
- name: Test uv simple service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' && env.HAS_LANGSMITH_API_KEY == 'true' }}
|
||||
working-directory: libs/cli/uv-examples/simple
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: |
|
||||
cp .env.example .env
|
||||
echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> .env
|
||||
timeout 60 python ../../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-uv-simple
|
||||
|
||||
- name: Build uv monorepo service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' }}
|
||||
working-directory: libs/cli/uv-examples/monorepo/apps/agent
|
||||
run: |
|
||||
langgraph build -t langgraph-test-uv-monorepo
|
||||
- name: Test uv monorepo service
|
||||
if: ${{ (steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch') &&matrix.example.name == 'A' && env.HAS_LANGSMITH_API_KEY == 'true' }}
|
||||
working-directory: libs/cli/uv-examples/monorepo/apps/agent
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: |
|
||||
cp .env.example .env
|
||||
echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> .env
|
||||
timeout 60 python ../../../../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-uv-monorepo
|
||||
@@ -0,0 +1,78 @@
|
||||
name: lint
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
working-directory:
|
||||
required: true
|
||||
type: string
|
||||
description: "From which folder this pipeline executes"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
# This env var allows us to get inline annotations when ruff has complaints.
|
||||
RUFF_OUTPUT_FORMAT: github
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
# Only lint on the min and max supported Python versions.
|
||||
# It's extremely unlikely that there's a lint issue on any version in between
|
||||
# that doesn't show up on the min or max versions.
|
||||
#
|
||||
# GitHub rate-limits how many jobs can be running at any one time.
|
||||
# Starting new jobs is also relatively slow,
|
||||
# so linting on fewer versions makes CI faster.
|
||||
python-version:
|
||||
- "3.12"
|
||||
name: "lint #${{ matrix.python-version }}"
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Get changed files
|
||||
id: changed-files
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
uses: Ana06/get-changed-files@25f79e676e7ea1868813e21465014798211fad8c # v2.3.0
|
||||
with:
|
||||
filter: "${{ inputs.working-directory }}/**"
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
if: steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch'
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache-suffix: lint-${{ inputs.working-directory }}
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch'
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: uv sync --frozen --group lint
|
||||
|
||||
- name: Analysing package code with our lint
|
||||
if: steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch'
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
if make lint_package > /dev/null 2>&1; then
|
||||
make lint_package
|
||||
else
|
||||
echo "lint_package command not found, using lint instead"
|
||||
make lint
|
||||
fi
|
||||
|
||||
- name: Install test dependencies
|
||||
if: steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch'
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: uv sync --group lint
|
||||
|
||||
- name: Analysing tests with our lint
|
||||
if: steps.changed-files.outputs.all || github.event_name == 'workflow_dispatch'
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
if make lint_tests > /dev/null 2>&1; then
|
||||
make lint_tests
|
||||
else
|
||||
echo "lint_tests command not found, skipping step"
|
||||
fi
|
||||
@@ -0,0 +1,85 @@
|
||||
name: sdk-py integration test
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
LANGSMITH_API_KEY:
|
||||
required: false
|
||||
DOCKERHUB_USERNAME:
|
||||
required: false
|
||||
DOCKERHUB_RO_TOKEN:
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
name: "sdk-py integration"
|
||||
defaults:
|
||||
run:
|
||||
working-directory: libs/sdk-py
|
||||
env:
|
||||
HAS_LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY != '' }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: "3.13"
|
||||
cache-suffix: sdk-py-integration
|
||||
working-directory: libs/sdk-py
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
if: ${{ !github.event.pull_request.head.repo.fork }}
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_RO_TOKEN }}
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: uv sync --frozen --group test --no-dev
|
||||
|
||||
- name: Skip if LANGSMITH_API_KEY is not available
|
||||
if: env.HAS_LANGSMITH_API_KEY != 'true'
|
||||
run: |
|
||||
echo "LANGSMITH_API_KEY is not set (likely a fork PR). Skipping integration tests."
|
||||
exit 0
|
||||
|
||||
- name: Bring up integration stack
|
||||
if: env.HAS_LANGSMITH_API_KEY == 'true'
|
||||
working-directory: libs/sdk-py/integration
|
||||
env:
|
||||
LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
|
||||
run: docker compose up -d --build
|
||||
|
||||
- name: Wait for API healthcheck
|
||||
if: env.HAS_LANGSMITH_API_KEY == 'true'
|
||||
run: |
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf http://localhost:2024/ok >/dev/null; then
|
||||
echo "API ready after ${i}s"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "API failed to become healthy within 120s"
|
||||
docker compose -f libs/sdk-py/integration/docker-compose.yml logs api | tail -100
|
||||
exit 1
|
||||
|
||||
- name: Run integration suite
|
||||
if: env.HAS_LANGSMITH_API_KEY == 'true'
|
||||
run: uv run pytest tests/integration/ -m integration
|
||||
|
||||
- name: Dump api logs on failure
|
||||
if: failure() && env.HAS_LANGSMITH_API_KEY == 'true'
|
||||
working-directory: libs/sdk-py/integration
|
||||
run: docker compose logs api | tail -200
|
||||
|
||||
- name: Tear down stack
|
||||
if: always() && env.HAS_LANGSMITH_API_KEY == 'true'
|
||||
working-directory: libs/sdk-py/integration
|
||||
run: docker compose down -v
|
||||
@@ -0,0 +1,63 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
working-directory:
|
||||
required: true
|
||||
type: string
|
||||
description: "From which folder this pipeline executes"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- "3.10"
|
||||
- "3.11"
|
||||
- "3.12"
|
||||
- "3.13"
|
||||
- "3.14"
|
||||
|
||||
name: "test #${{ matrix.python-version }}"
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache-suffix: test-${{ inputs.working-directory }}
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
if: ${{ !github.event.pull_request.head.repo.fork }}
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_RO_TOKEN }}
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: uv sync --frozen --group test --no-dev
|
||||
|
||||
- name: Run tests
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: make test
|
||||
|
||||
- name: Ensure the tests did not create any additional files
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
set -eu
|
||||
|
||||
STATUS="$(git status)"
|
||||
echo "$STATUS"
|
||||
|
||||
# grep will exit non-zero if the target message isn't found,
|
||||
# and `set -e` above will cause the step to fail.
|
||||
echo "$STATUS" | grep 'nothing to commit, working tree clean'
|
||||
@@ -0,0 +1,65 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- "3.10"
|
||||
- "3.11"
|
||||
- "3.12"
|
||||
- "3.13"
|
||||
- "3.14"
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: libs/langgraph
|
||||
name: "test #${{ matrix.python-version }}"
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache-suffix: "test-langgraph"
|
||||
working-directory: libs/langgraph
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
if: ${{ !github.event.pull_request.head.repo.fork }}
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_RO_TOKEN }}
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: uv sync --frozen --group test --no-dev
|
||||
|
||||
- name: Run tests
|
||||
shell: bash
|
||||
run: make test_parallel
|
||||
|
||||
- name: Run strict msgpack pregel tests
|
||||
if: ${{ matrix.python-version == '3.13' }}
|
||||
shell: bash
|
||||
env:
|
||||
LANGGRAPH_STRICT_MSGPACK: "true"
|
||||
run: make test TEST="tests/test_pregel.py tests/test_pregel_async.py"
|
||||
|
||||
- name: Ensure the tests did not create any additional files
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
|
||||
STATUS="$(git status)"
|
||||
echo "$STATUS"
|
||||
|
||||
# grep will exit non-zero if the target message isn't found,
|
||||
# and `set -e` above will cause the step to fail.
|
||||
echo "$STATUS" | grep 'nothing to commit, working tree clean'
|
||||
@@ -0,0 +1,97 @@
|
||||
name: test-release
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
working-directory:
|
||||
required: true
|
||||
type: string
|
||||
description: "From which folder this pipeline executes"
|
||||
|
||||
env:
|
||||
PYTHON_VERSION: "3.10"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
pkg-name: ${{ steps.check-version.outputs.pkg-name }}
|
||||
version: ${{ steps.check-version.outputs.version }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python ${{ env.PYTHON_VERSION }}
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
cache-suffix: "release"
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
# We want to keep this build stage *separate* from the release stage,
|
||||
# so that there's no sharing of permissions between them.
|
||||
# The release stage has trusted publishing and GitHub repo contents write access,
|
||||
# and we want to keep the scope of that access limited just to the release job.
|
||||
# Otherwise, a malicious `build` step (e.g. via a compromised dependency)
|
||||
# could get access to our GitHub or PyPI credentials.
|
||||
#
|
||||
# Per the trusted publishing GitHub Action:
|
||||
# > It is strongly advised to separate jobs for building [...]
|
||||
# > from the publish job.
|
||||
# https://github.com/pypa/gh-action-pypi-publish#non-goals
|
||||
- name: Build project for distribution
|
||||
run: uv build
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- name: Upload build
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: test-dist
|
||||
path: ${{ inputs.working-directory }}/dist/
|
||||
|
||||
- name: Check Version
|
||||
id: check-version
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
echo pkg-name=$(grep -m 1 "^name = " pyproject.toml | cut -d '"' -f 2)
|
||||
echo version=$(grep -m 1 "^version = " pyproject.toml | cut -d '"' -f 2)
|
||||
|
||||
publish:
|
||||
needs:
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# This permission is used for trusted publishing:
|
||||
# https://blog.pypi.org/posts/2023-04-20-introducing-trusted-publishers/
|
||||
#
|
||||
# Trusted publishing has to also be configured on PyPI for each package:
|
||||
# https://docs.pypi.org/trusted-publishers/adding-a-publisher/
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: test-dist
|
||||
path: ${{ inputs.working-directory }}/dist/
|
||||
|
||||
- name: Publish to test PyPI
|
||||
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1
|
||||
with:
|
||||
packages-dir: ${{ inputs.working-directory }}/dist/
|
||||
verbose: true
|
||||
print-hash: true
|
||||
repository-url: https://test.pypi.org/legacy/
|
||||
|
||||
# We overwrite any existing distributions with the same name and version.
|
||||
# This is *only for CI use* and is *extremely dangerous* otherwise!
|
||||
# https://github.com/pypa/gh-action-pypi-publish#tolerating-release-package-file-duplicates
|
||||
skip-existing: true
|
||||
# Temp workaround since attestations are on by default as of gh-action-pypi-publish v1.11.0
|
||||
attestations: false
|
||||
@@ -0,0 +1,37 @@
|
||||
name: baseline
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "libs/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
benchmark:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: libs/langgraph
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- run: SHA=$(git rev-parse HEAD) && echo "SHA=$SHA" >> $GITHUB_ENV
|
||||
- name: Set up Python 3.11
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: "3.11"
|
||||
cache-suffix: "bench"
|
||||
working-directory: libs/langgraph
|
||||
- name: Install dependencies
|
||||
run: uv sync --group test
|
||||
- name: Run benchmarks
|
||||
run: OUTPUT=out/benchmark-baseline.json make -s benchmark
|
||||
- name: Save outputs
|
||||
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
key: ${{ runner.os }}-benchmark-baseline-${{ env.SHA }}
|
||||
path: |
|
||||
libs/langgraph/out/benchmark-baseline.json
|
||||
@@ -0,0 +1,75 @@
|
||||
name: bench
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "libs/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
benchmark:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: libs/langgraph
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- id: files
|
||||
name: Get changed files
|
||||
uses: Ana06/get-changed-files@25f79e676e7ea1868813e21465014798211fad8c # v2.3.0
|
||||
with:
|
||||
format: json
|
||||
- name: Set up Python 3.11
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: "3.11"
|
||||
cache-suffix: "bench"
|
||||
working-directory: libs/langgraph
|
||||
- name: Install dependencies
|
||||
run: uv sync --group test
|
||||
- name: Download baseline
|
||||
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
key: ${{ runner.os }}-benchmark-baseline
|
||||
restore-keys: |
|
||||
${{ runner.os }}-benchmark-baseline-
|
||||
fail-on-cache-miss: true
|
||||
path: |
|
||||
libs/langgraph/out/benchmark-baseline.json
|
||||
- name: Run benchmarks
|
||||
id: benchmark
|
||||
run: |
|
||||
{
|
||||
echo 'OUTPUT<<EOF'
|
||||
make -s benchmark-fast
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Compare benchmarks
|
||||
id: compare
|
||||
run: |
|
||||
{
|
||||
echo 'OUTPUT<<EOF'
|
||||
mv out/benchmark-baseline.json out/main.json
|
||||
mv out/benchmark.json out/changes.json
|
||||
uv run pyperf compare_to out/main.json out/changes.json --table --group-by-speed
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Annotation
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
CHANGED_FILES: ${{ steps.files.outputs.added_modified_renamed }}
|
||||
BENCHMARK_OUTPUT: ${{ steps.benchmark.outputs.OUTPUT }}
|
||||
COMPARE_OUTPUT: ${{ steps.compare.outputs.OUTPUT }}
|
||||
with:
|
||||
script: |
|
||||
const file = JSON.parse(process.env.CHANGED_FILES || "[]")[0]
|
||||
core.notice(process.env.BENCHMARK_OUTPUT || "", {
|
||||
title: 'Benchmark results',
|
||||
file,
|
||||
})
|
||||
core.notice(process.env.COMPARE_OUTPUT || "", {
|
||||
title: 'Comparison against main',
|
||||
file,
|
||||
})
|
||||
@@ -0,0 +1,198 @@
|
||||
---
|
||||
name: CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# If another push to the same PR or branch happens while this workflow is still running,
|
||||
# cancel the earlier run in favor of the next run.
|
||||
#
|
||||
# There's no point in testing an outdated version of the code. GitHub only allows
|
||||
# a limited number of job runners to be active at the same time, so it's better to cancel
|
||||
# pointless jobs early so that more useful jobs can run sooner.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
python: ${{ steps.filter.outputs.python || 'true' }}
|
||||
deps: ${{ steps.filter.outputs.deps || 'true' }}
|
||||
sdk_py: ${{ steps.filter.outputs.sdk_py || 'true' }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
python:
|
||||
- 'libs/langgraph/**'
|
||||
- 'libs/sdk-py/**'
|
||||
- 'libs/cli/**'
|
||||
- 'libs/checkpoint/**'
|
||||
- 'libs/checkpoint-sqlite/**'
|
||||
- 'libs/checkpoint-postgres/**'
|
||||
- 'libs/checkpoint-conformance/**'
|
||||
- 'libs/prebuilt/**'
|
||||
deps:
|
||||
- '**/pyproject.toml'
|
||||
- '**/uv.lock'
|
||||
sdk_py:
|
||||
- 'libs/sdk-py/**'
|
||||
# The integration suite runs the local langgraph core inside the
|
||||
# server (see libs/sdk-py/integration/Dockerfile), so any core
|
||||
# change is now exercised end-to-end and should trigger it.
|
||||
- 'libs/langgraph/**'
|
||||
|
||||
lint:
|
||||
needs: changes
|
||||
name: cd ${{ matrix.working-directory }}
|
||||
strategy:
|
||||
matrix:
|
||||
working-directory:
|
||||
[
|
||||
"libs/langgraph",
|
||||
"libs/sdk-py",
|
||||
"libs/cli",
|
||||
"libs/checkpoint",
|
||||
"libs/checkpoint-sqlite",
|
||||
"libs/checkpoint-postgres",
|
||||
"libs/checkpoint-conformance",
|
||||
"libs/prebuilt",
|
||||
]
|
||||
if: needs.changes.outputs.python == 'true' || needs.changes.outputs.deps == 'true'
|
||||
uses: ./.github/workflows/_lint.yml
|
||||
with:
|
||||
working-directory: ${{ matrix.working-directory }}
|
||||
secrets: inherit
|
||||
|
||||
test:
|
||||
needs: changes
|
||||
name: cd ${{ matrix.working-directory }}
|
||||
strategy:
|
||||
matrix:
|
||||
working-directory:
|
||||
[
|
||||
"libs/cli",
|
||||
"libs/checkpoint",
|
||||
"libs/checkpoint-sqlite",
|
||||
"libs/checkpoint-postgres",
|
||||
"libs/checkpoint-conformance",
|
||||
"libs/prebuilt",
|
||||
"libs/sdk-py",
|
||||
]
|
||||
if: needs.changes.outputs.python == 'true' || needs.changes.outputs.deps == 'true'
|
||||
uses: ./.github/workflows/_test.yml
|
||||
with:
|
||||
working-directory: ${{ matrix.working-directory }}
|
||||
secrets: inherit
|
||||
|
||||
# NOTE: we're testing langgraph separately because it requires a different matrix
|
||||
test-langgraph:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.python == 'true' || needs.changes.outputs.deps == 'true'
|
||||
name: "cd libs/langgraph"
|
||||
uses: ./.github/workflows/_test_langgraph.yml
|
||||
secrets: inherit
|
||||
|
||||
check-sdk-methods:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.python == 'true'
|
||||
name: "Check SDK methods matching"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Run check_sdk_methods script
|
||||
run: python .github/scripts/check_sdk_methods.py
|
||||
|
||||
check-schema:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.python == 'true'
|
||||
name: "Check CLI schema hasn't changed #${{ matrix.python-version }}"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- "3.13"
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: "3.13"
|
||||
cache-suffix: "schema-check-cli"
|
||||
working-directory: libs/cli
|
||||
- name: Install CLI dependencies
|
||||
run: |
|
||||
cd libs/cli
|
||||
uv sync
|
||||
- name: Generate schema and check for changes
|
||||
run: |
|
||||
cd libs/cli
|
||||
# Create a temporary copy of the current schema
|
||||
cp schemas/schema.json schemas/schema.current.json
|
||||
# Generate new schema
|
||||
uv run python generate_schema.py
|
||||
# Compare the new schema with the original
|
||||
if ! diff -q schemas/schema.json schemas/schema.current.json > /dev/null; then
|
||||
echo "Error: Langgraph.json configuration schema has changed. Please run 'uv run python generate_schema.py' in the libs/cli directory and commit the changes."
|
||||
diff schemas/schema.json schemas/schema.current.json
|
||||
exit 1
|
||||
fi
|
||||
echo "Schema check passed - no changes detected"
|
||||
|
||||
integration-test:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.python == 'true' || needs.changes.outputs.deps == 'true'
|
||||
name: CLI integration test
|
||||
uses: ./.github/workflows/_integration_test.yml
|
||||
secrets: inherit
|
||||
|
||||
sdk-py-integration-test:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.sdk_py == 'true'
|
||||
name: "sdk-py integration test"
|
||||
uses: ./.github/workflows/_sdk_integration_test.yml
|
||||
secrets: inherit
|
||||
|
||||
ci_success:
|
||||
name: "CI Success"
|
||||
needs:
|
||||
[
|
||||
lint,
|
||||
test,
|
||||
test-langgraph,
|
||||
check-sdk-methods,
|
||||
check-schema,
|
||||
integration-test,
|
||||
sdk-py-integration-test,
|
||||
]
|
||||
if: |
|
||||
always()
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
JOBS_JSON: ${{ toJSON(needs) }}
|
||||
RESULTS_JSON: ${{ toJSON(needs.*.result) }}
|
||||
EXIT_CODE: ${{!contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && '0' || '1'}}
|
||||
steps:
|
||||
- name: "CI Success"
|
||||
run: |
|
||||
echo $JOBS_JSON
|
||||
echo $RESULTS_JSON
|
||||
echo "Exiting with $EXIT_CODE"
|
||||
exit $EXIT_CODE
|
||||
@@ -0,0 +1,49 @@
|
||||
name: Deploy Redirects to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'docs/**'
|
||||
- '.github/workflows/deploy-redirects.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Generate redirect files
|
||||
run: python docs/generate_redirects.py
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
|
||||
with:
|
||||
path: 'docs/_site'
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0
|
||||
@@ -0,0 +1,47 @@
|
||||
name: PR Title Lint
|
||||
|
||||
permissions:
|
||||
pull-requests: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, edited, synchronize]
|
||||
|
||||
jobs:
|
||||
lint-pr-title:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate PR Title
|
||||
uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
types: |
|
||||
feat
|
||||
fix
|
||||
docs
|
||||
style
|
||||
refactor
|
||||
perf
|
||||
test
|
||||
build
|
||||
ci
|
||||
chore
|
||||
revert
|
||||
release
|
||||
scopes: |
|
||||
checkpoint
|
||||
checkpoint-postgres
|
||||
checkpoint-sqlite
|
||||
cli
|
||||
langgraph
|
||||
prebuilt
|
||||
scheduler-kafka
|
||||
sdk-py
|
||||
docs
|
||||
ci
|
||||
deps
|
||||
deps-dev
|
||||
requireScope: false
|
||||
ignoreLabels: |
|
||||
ignore-lint-pr-title
|
||||
@@ -0,0 +1,331 @@
|
||||
name: release
|
||||
run-name: Release ${{ inputs.working-directory }} by @${{ github.actor }}
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
working-directory:
|
||||
required: true
|
||||
type: string
|
||||
default: "libs/langgraph"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
PYTHON_VERSION: "3.11"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
pkg-name: ${{ steps.check-version.outputs.pkg-name }}
|
||||
short-pkg-name: ${{ steps.check-version.outputs.short-pkg-name }}
|
||||
version: ${{ steps.check-version.outputs.version }}
|
||||
tag: ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
cache-suffix: "release"
|
||||
enable-cache: false
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
# We want to keep this build stage *separate* from the release stage,
|
||||
# so that there's no sharing of permissions between them.
|
||||
# The release stage has trusted publishing and GitHub repo contents write access,
|
||||
# and we want to keep the scope of that access limited just to the release job.
|
||||
# Otherwise, a malicious `build` step (e.g. via a compromised dependency)
|
||||
# could get access to our GitHub or PyPI credentials.
|
||||
#
|
||||
# Per the trusted publishing GitHub Action:
|
||||
# > It is strongly advised to separate jobs for building [...]
|
||||
# > from the publish job.
|
||||
# https://github.com/pypa/gh-action-pypi-publish#non-goals
|
||||
- name: Build project for distribution
|
||||
run: uv build
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- name: Upload build
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: ${{ inputs.working-directory }}/dist/
|
||||
|
||||
- name: Check Version
|
||||
id: check-version
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
PKG_NAME=$(grep -m 1 "^name = " pyproject.toml | cut -d '"' -f 2)
|
||||
if grep -q 'dynamic.*=.*\[.*"version".*\]' pyproject.toml; then
|
||||
# handle dynamic versioning
|
||||
DIR_NAME=$(echo "$PKG_NAME" | tr '-' '_')
|
||||
VERSION=$(grep -m 1 '^__version__' "${DIR_NAME}/__init__.py" | cut -d '"' -f 2)
|
||||
else
|
||||
VERSION=$(grep -m 1 "^version = " pyproject.toml | cut -d '"' -f 2)
|
||||
fi
|
||||
SHORT_PKG_NAME="$(echo "$PKG_NAME" | sed -e 's/langgraph//g' -e 's/-//g')"
|
||||
if [ -z $SHORT_PKG_NAME ]; then
|
||||
TAG="$VERSION"
|
||||
else
|
||||
TAG="${SHORT_PKG_NAME}==${VERSION}"
|
||||
fi
|
||||
echo pkg-name="$PKG_NAME" >> $GITHUB_OUTPUT
|
||||
echo short-pkg-name="$SHORT_PKG_NAME" >> $GITHUB_OUTPUT
|
||||
echo version="$VERSION" >> $GITHUB_OUTPUT
|
||||
echo tag="$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
release-notes:
|
||||
needs:
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release-body: ${{ steps.generate-release-body.outputs.release-body }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
repository: langchain-ai/langgraph
|
||||
path: langgraph
|
||||
sparse-checkout: | # this only grabs files for relevant dir
|
||||
${{ inputs.working-directory }}
|
||||
ref: main # this scopes to just master branch
|
||||
fetch-depth: 0 # this fetches entire commit history
|
||||
- name: Check Tags
|
||||
id: check-tags
|
||||
shell: bash
|
||||
working-directory: langgraph/${{ inputs.working-directory }}
|
||||
env:
|
||||
PKG_NAME: ${{ needs.build.outputs.pkg-name }}
|
||||
SHORT_PKG_NAME: ${{ needs.build.outputs.short-pkg-name }}
|
||||
VERSION: ${{ needs.build.outputs.version }}
|
||||
TAG: ${{ needs.build.outputs.tag }}
|
||||
run: |
|
||||
if [ -z $SHORT_PKG_NAME ]; then
|
||||
REGEX="^\\d+\\.\\d+\\.\\d+((a|b|rc)\\d+)?\$"
|
||||
else
|
||||
REGEX="^$SHORT_PKG_NAME==\\d+\\.\\d+\\.\\d+((a|b|rc)\\d+)?\$"
|
||||
fi
|
||||
echo $REGEX
|
||||
PREV_TAG=$(git tag --sort=-creatordate | grep -P $REGEX | head -1 || echo "")
|
||||
echo $PREV_TAG
|
||||
if [ "$TAG" == "$PREV_TAG" ]; then
|
||||
echo "No new version to release"
|
||||
exit 1
|
||||
fi
|
||||
echo prev-tag="$PREV_TAG" >> $GITHUB_OUTPUT
|
||||
- name: Generate release body
|
||||
id: generate-release-body
|
||||
working-directory: langgraph
|
||||
env:
|
||||
WORKING_DIR: ${{ inputs.working-directory }}
|
||||
PKG_NAME: ${{ needs.build.outputs.pkg-name }}
|
||||
TAG: ${{ needs.build.outputs.tag }}
|
||||
PREV_TAG: ${{ steps.check-tags.outputs.prev-tag }}
|
||||
run: |
|
||||
{
|
||||
echo 'release-body<<EOF'
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
echo "Initial release"
|
||||
else
|
||||
echo "Changes since $PREV_TAG"
|
||||
echo
|
||||
git log --format="%s" "$PREV_TAG"..HEAD -- $WORKING_DIR | awk '{print "* " $0}'
|
||||
fi
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
test-pypi-publish:
|
||||
needs:
|
||||
- build
|
||||
- release-notes
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
uses: ./.github/workflows/_test_release.yml
|
||||
with:
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
secrets: inherit
|
||||
|
||||
pre-release-checks:
|
||||
needs:
|
||||
- build
|
||||
- release-notes
|
||||
- test-pypi-publish
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
# We explicitly *don't* set up caching here. This ensures our tests are
|
||||
# maximally sensitive to catching breakage.
|
||||
#
|
||||
# For example, here's a way that caching can cause a falsely-passing test:
|
||||
# - Make the langchain package manifest no longer list a dependency package
|
||||
# as a requirement. This means it won't be installed by `pip install`,
|
||||
# and attempting to use it would cause a crash.
|
||||
# - That dependency used to be required, so it may have been cached.
|
||||
# When restoring the venv packages from cache, that dependency gets included.
|
||||
# - Tests pass, because the dependency is present even though it wasn't specified.
|
||||
# - The package is published, and it breaks on the missing dependency when
|
||||
# used in the real world.
|
||||
|
||||
- name: Set up Python
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
enable-cache: false
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- name: Import published package
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
env:
|
||||
PKG_NAME: ${{ needs.build.outputs.pkg-name }}
|
||||
VERSION: ${{ needs.build.outputs.version }}
|
||||
# Here we use:
|
||||
# - The default regular PyPI index as the *primary* index, meaning
|
||||
# that it takes priority (https://pypi.org/simple)
|
||||
# - The test PyPI index as an extra index, so that any dependencies that
|
||||
# are not found on test PyPI can be resolved and installed anyway.
|
||||
# (https://test.pypi.org/simple). This will include the PKG_NAME==VERSION
|
||||
# package because VERSION will not have been uploaded to regular PyPI yet.
|
||||
# - attempt install again after 5 seconds if it fails because there is
|
||||
# sometimes a delay in availability on test pypi
|
||||
run: |
|
||||
uv run pip install \
|
||||
--extra-index-url https://test.pypi.org/simple/ \
|
||||
"$PKG_NAME==$VERSION" || \
|
||||
( \
|
||||
sleep 5 && \
|
||||
uv run pip install \
|
||||
--extra-index-url https://test.pypi.org/simple/ \
|
||||
"$PKG_NAME==$VERSION" \
|
||||
)
|
||||
|
||||
if [[ "$PKG_NAME" == *prebuilt* ]]; then
|
||||
uv run pip install langgraph
|
||||
fi
|
||||
|
||||
if [[ "$PKG_NAME" == *checkpoint* || "$PKG_NAME" == *prebuilt* ]]; then
|
||||
# since checkpoint packages are namespace packages, import them with . convention
|
||||
# i.e. import langgraph.checkpoint or langgraph.checkpoint.sqlite
|
||||
IMPORT_NAME="$(echo "$PKG_NAME" | sed s/-/./g)"
|
||||
else
|
||||
# Replace all dashes in the package name with underscores,
|
||||
# since that's how Python imports packages with dashes in the name.
|
||||
IMPORT_NAME="$(echo "$PKG_NAME" | sed s/-/_/g)"
|
||||
fi
|
||||
|
||||
uv run python -c "import $IMPORT_NAME; print(dir($IMPORT_NAME))"
|
||||
|
||||
- name: Import test dependencies
|
||||
run: uv sync --group test
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
# Overwrite the local version of the package with the test PyPI version.
|
||||
- name: Import published package (again)
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
shell: bash
|
||||
env:
|
||||
PKG_NAME: ${{ needs.build.outputs.pkg-name }}
|
||||
VERSION: ${{ needs.build.outputs.version }}
|
||||
run: |
|
||||
uv run pip install \
|
||||
--extra-index-url https://test.pypi.org/simple/ \
|
||||
"$PKG_NAME==$VERSION"
|
||||
|
||||
- name: Run unit tests
|
||||
run: make test
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
publish:
|
||||
needs:
|
||||
- build
|
||||
- release-notes
|
||||
- test-pypi-publish
|
||||
- pre-release-checks
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# This permission is used for trusted publishing:
|
||||
# https://blog.pypi.org/posts/2023-04-20-introducing-trusted-publishers/
|
||||
#
|
||||
# Trusted publishing has to also be configured on PyPI for each package:
|
||||
# https://docs.pypi.org/trusted-publishers/adding-a-publisher/
|
||||
id-token: write
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
cache-suffix: "release"
|
||||
enable-cache: false
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: ${{ inputs.working-directory }}/dist/
|
||||
|
||||
- name: Publish package distributions to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1
|
||||
with:
|
||||
packages-dir: ${{ inputs.working-directory }}/dist/
|
||||
verbose: true
|
||||
print-hash: true
|
||||
# Temp workaround since attestations are on by default as of gh-action-pypi-publish v1.11.0
|
||||
attestations: false
|
||||
|
||||
mark-release:
|
||||
needs:
|
||||
- build
|
||||
- release-notes
|
||||
- test-pypi-publish
|
||||
- pre-release-checks
|
||||
- publish
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# This permission is needed by `ncipollo/release-action` to
|
||||
# create the GitHub release.
|
||||
contents: write
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
cache-suffix: "release"
|
||||
enable-cache: false
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: ${{ inputs.working-directory }}/dist/
|
||||
|
||||
- name: Create Tag
|
||||
uses: ncipollo/release-action@339a81892b84b4eeb0f6e744e4574d79d0d9b8dd # v1
|
||||
with:
|
||||
artifacts: "dist/*"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
generateReleaseNotes: false
|
||||
tag: ${{needs.build.outputs.tag}}
|
||||
name: ${{ needs.build.outputs.pkg-name }}==${{ needs.build.outputs.version }}
|
||||
body: ${{ needs.release-notes.outputs.release-body }}
|
||||
commit: ${{ github.sha }}
|
||||
@@ -0,0 +1,195 @@
|
||||
# Reopen PRs that were auto-closed by require_issue_link.yml when the
|
||||
# contributor was not assigned to the linked issue. When a maintainer
|
||||
# assigns the contributor to the issue, this workflow finds matching
|
||||
# closed PRs, verifies the issue link, and reopens them.
|
||||
#
|
||||
# Uses the default GITHUB_TOKEN (not a PAT or app token) so that the
|
||||
# reopen and label-removal events do NOT re-trigger other workflows.
|
||||
# GitHub suppresses events created by the default GITHUB_TOKEN within
|
||||
# workflow runs to prevent infinite loops.
|
||||
|
||||
name: Reopen PR on Issue Assignment
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [assigned]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
reopen-linked-prs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Find and reopen matching PRs
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issueNumber = context.payload.issue.number;
|
||||
const assignee = context.payload.assignee.login;
|
||||
|
||||
console.log(
|
||||
`Issue #${issueNumber} assigned to ${assignee} — searching for closed PRs to reopen`,
|
||||
);
|
||||
|
||||
const q = [
|
||||
`is:pr`,
|
||||
`is:closed`,
|
||||
`author:${assignee}`,
|
||||
`label:missing-issue-link`,
|
||||
`repo:${owner}/${repo}`,
|
||||
].join(' ');
|
||||
|
||||
let data;
|
||||
try {
|
||||
({ data } = await github.rest.search.issuesAndPullRequests({
|
||||
q,
|
||||
per_page: 30,
|
||||
}));
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to search for closed PRs to reopen after assigning ${assignee} ` +
|
||||
`to #${issueNumber} (HTTP ${e.status ?? 'unknown'}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (data.total_count === 0) {
|
||||
console.log('No matching closed PRs found');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${data.total_count} candidate PR(s)`);
|
||||
|
||||
// Must stay in sync with the identical pattern in require_issue_link.yml
|
||||
const pattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*#(\d+)/gi;
|
||||
|
||||
for (const item of data.items) {
|
||||
const prNumber = item.number;
|
||||
const body = item.body || '';
|
||||
const matches = [...body.matchAll(pattern)];
|
||||
const referencedIssues = matches.map(m => parseInt(m[1], 10));
|
||||
|
||||
if (!referencedIssues.includes(issueNumber)) {
|
||||
console.log(`PR #${prNumber} does not reference #${issueNumber} — skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if already bypassed
|
||||
const labels = item.labels.map(l => l.name);
|
||||
if (labels.includes('bypass-issue-check')) {
|
||||
console.log(`PR #${prNumber} already has bypass-issue-check — skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Reopen first, remove label second — a closed PR that still has
|
||||
// missing-issue-link is recoverable; a closed PR with the label
|
||||
// stripped is invisible to both workflows.
|
||||
try {
|
||||
await github.rest.pulls.update({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
state: 'open',
|
||||
});
|
||||
console.log(`Reopened PR #${prNumber}`);
|
||||
} catch (e) {
|
||||
if (e.status === 422) {
|
||||
// Head branch deleted — PR is unrecoverable. Notify the
|
||||
// contributor so they know to open a new PR.
|
||||
core.warning(`Cannot reopen PR #${prNumber}: head branch was likely deleted`);
|
||||
try {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body:
|
||||
`You have been assigned to #${issueNumber}, but this PR could not be ` +
|
||||
`reopened because the head branch has been deleted. Please open a new ` +
|
||||
`PR referencing the issue.`,
|
||||
});
|
||||
} catch (commentErr) {
|
||||
core.warning(
|
||||
`Also failed to post comment on PR #${prNumber}: ${commentErr.message}`,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Transient errors (rate limit, 5xx) should fail the job so
|
||||
// the label is NOT removed and the run can be retried.
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Remove missing-issue-link label only after successful reopen
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
name: 'missing-issue-link',
|
||||
});
|
||||
console.log(`Removed missing-issue-link from PR #${prNumber}`);
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
|
||||
// Minimize stale enforcement comment (best-effort;
|
||||
// sync w/ require_issue_link.yml minimize blocks)
|
||||
try {
|
||||
const marker = '<!-- require-issue-link -->';
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const stale = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (stale) {
|
||||
await github.graphql(`
|
||||
mutation($id: ID!) {
|
||||
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
|
||||
minimizedComment { isMinimized }
|
||||
}
|
||||
}
|
||||
`, { id: stale.node_id });
|
||||
console.log(`Minimized stale enforcement comment ${stale.id} as outdated`);
|
||||
}
|
||||
} catch (e) {
|
||||
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
|
||||
// Re-run the failed require_issue_link check so it picks up the
|
||||
// new assignment. The re-run uses the original event payload but
|
||||
// fetches live issue data, so the assignment check will pass.
|
||||
//
|
||||
// Limitation: we look up runs by the PR's current head SHA. If the
|
||||
// contributor pushed new commits while the PR was closed, head.sha
|
||||
// won't match the SHA of the original failed run and the query will
|
||||
// return 0 results. This is acceptable because any push after reopen
|
||||
// triggers a fresh require_issue_link run against the new SHA.
|
||||
try {
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner, repo, pull_number: prNumber,
|
||||
});
|
||||
const { data: runs } = await github.rest.actions.listWorkflowRuns({
|
||||
owner, repo,
|
||||
workflow_id: 'require_issue_link.yml',
|
||||
head_sha: pr.head.sha,
|
||||
status: 'failure',
|
||||
per_page: 1,
|
||||
});
|
||||
if (runs.workflow_runs.length > 0) {
|
||||
await github.rest.actions.reRunWorkflowFailedJobs({
|
||||
owner, repo,
|
||||
run_id: runs.workflow_runs[0].id,
|
||||
});
|
||||
console.log(`Re-ran failed require_issue_link run ${runs.workflow_runs[0].id} for PR #${prNumber}`);
|
||||
} else {
|
||||
console.log(`No failed require_issue_link runs found for PR #${prNumber} — skipping re-run`);
|
||||
}
|
||||
} catch (e) {
|
||||
core.warning(`Could not re-run require_issue_link check for PR #${prNumber} (HTTP ${e.status ?? 'unknown'}): ${e.message}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
# Require external PRs to reference an approved issue (e.g. Fixes #NNN) and
|
||||
# the PR author to be assigned to that issue. On failure the PR is
|
||||
# labeled "missing-issue-link", commented on, and closed.
|
||||
#
|
||||
# Maintainer override: an org member can reopen the PR or remove
|
||||
# "missing-issue-link" — both add "bypass-issue-check" and reopen.
|
||||
#
|
||||
# Dependency: tag-external-prs.yml must apply the "external" label
|
||||
# first. This workflow does NOT trigger on "opened" (new PRs have no labels
|
||||
# yet, so the gate would always skip).
|
||||
|
||||
name: Require Issue Link
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
# NEVER CHECK OUT UNTRUSTED CODE FROM A PR's HEAD IN A pull_request_target JOB.
|
||||
# Doing so would allow attackers to execute arbitrary code in the context of your repository.
|
||||
types: [edited, reopened, labeled, unlabeled]
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Enforcement gate: set to 'true' to activate the issue link requirement.
|
||||
# When 'false', the workflow still runs the check logic (useful for dry-run
|
||||
# visibility) but will NOT label, comment, close, or fail PRs.
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
env:
|
||||
ENFORCE_ISSUE_LINK: "true"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-issue-link:
|
||||
# Run when the "external" label is added, on edit/reopen if already labeled,
|
||||
# or when "missing-issue-link" is removed (triggers maintainer override check).
|
||||
# Skip entirely when the PR already carries "trusted-contributor" or
|
||||
# "bypass-issue-check".
|
||||
if: >-
|
||||
!contains(github.event.pull_request.labels.*.name, 'trusted-contributor') &&
|
||||
!contains(github.event.pull_request.labels.*.name, 'bypass-issue-check') &&
|
||||
(
|
||||
(github.event.action == 'labeled' && github.event.label.name == 'external') ||
|
||||
(github.event.action == 'unlabeled' && github.event.label.name == 'missing-issue-link' && contains(github.event.pull_request.labels.*.name, 'external')) ||
|
||||
(github.event.action != 'labeled' && github.event.action != 'unlabeled' && contains(github.event.pull_request.labels.*.name, 'external'))
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Check for issue link and assignee
|
||||
id: check-link
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const prNumber = context.payload.pull_request.number;
|
||||
const action = context.payload.action;
|
||||
|
||||
// ── Helper: ensure a label exists, then add it to the PR ────────
|
||||
async function ensureAndAddLabel(labelName, color) {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: labelName });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner, repo, name: labelName, color });
|
||||
} catch (createErr) {
|
||||
// 422 = label was created by a concurrent run between our
|
||||
// GET and POST — safe to ignore.
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: prNumber, labels: [labelName],
|
||||
});
|
||||
}
|
||||
|
||||
// ── Helper: check if the user who triggered this event (reopened
|
||||
// the PR / removed the label) has write+ access on the repo ───
|
||||
// Uses the repo collaborator permission endpoint instead of the
|
||||
// org membership endpoint. The org endpoint requires the caller
|
||||
// to be an org member, which GITHUB_TOKEN (an app installation
|
||||
// token) never is — so it always returns 403.
|
||||
async function senderIsOrgMember() {
|
||||
const sender = context.payload.sender?.login;
|
||||
if (!sender) {
|
||||
throw new Error('Event has no sender — cannot check permissions');
|
||||
}
|
||||
try {
|
||||
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner, repo, username: sender,
|
||||
});
|
||||
const perm = data.permission;
|
||||
if (['admin', 'maintain', 'write'].includes(perm)) {
|
||||
console.log(`${sender} has ${perm} permission — treating as maintainer`);
|
||||
return { isMember: true, login: sender };
|
||||
}
|
||||
console.log(`${sender} has ${perm} permission — not a maintainer`);
|
||||
return { isMember: false, login: sender };
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`Cannot check permissions for ${sender} — treating as non-maintainer`);
|
||||
return { isMember: false, login: sender };
|
||||
}
|
||||
const status = e.status ?? 'unknown';
|
||||
throw new Error(
|
||||
`Permission check failed for ${sender} (HTTP ${status}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helper: apply maintainer bypass (shared by both override paths) ──
|
||||
async function applyMaintainerBypass(reason) {
|
||||
console.log(reason);
|
||||
|
||||
// Remove missing-issue-link if present
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: prNumber, name: 'missing-issue-link',
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
|
||||
// Reopen before adding bypass label — a failed reopen is more
|
||||
// actionable than a closed PR with a bypass label stuck on it.
|
||||
if (context.payload.pull_request.state === 'closed') {
|
||||
try {
|
||||
await github.rest.pulls.update({
|
||||
owner, repo, pull_number: prNumber, state: 'open',
|
||||
});
|
||||
console.log(`Reopened PR #${prNumber}`);
|
||||
} catch (e) {
|
||||
// 422 if head branch deleted; 403 if permissions insufficient.
|
||||
// Bypass labels still apply — maintainer can reopen manually.
|
||||
core.warning(
|
||||
`Could not reopen PR #${prNumber} (HTTP ${e.status ?? 'unknown'}): ${e.message}. ` +
|
||||
`Bypass labels were applied — a maintainer may need to reopen manually.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Add bypass-issue-check so future triggers skip enforcement
|
||||
await ensureAndAddLabel('bypass-issue-check', '0e8a16');
|
||||
|
||||
// Minimize stale enforcement comment (best-effort; must not
|
||||
// abort bypass — sync w/ reopen_on_assignment.yml & step below)
|
||||
try {
|
||||
const marker = '<!-- require-issue-link -->';
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const stale = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (stale) {
|
||||
await github.graphql(`
|
||||
mutation($id: ID!) {
|
||||
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
|
||||
minimizedComment { isMinimized }
|
||||
}
|
||||
}
|
||||
`, { id: stale.node_id });
|
||||
console.log(`Minimized stale enforcement comment ${stale.id} as outdated`);
|
||||
}
|
||||
} catch (e) {
|
||||
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
|
||||
core.setOutput('has-link', 'true');
|
||||
core.setOutput('is-assigned', 'true');
|
||||
}
|
||||
|
||||
// ── Maintainer override: removed "missing-issue-link" label ─────
|
||||
if (action === 'unlabeled') {
|
||||
const { isMember, login } = await senderIsOrgMember();
|
||||
if (isMember) {
|
||||
await applyMaintainerBypass(
|
||||
`Maintainer ${login} removed missing-issue-link from PR #${prNumber} — bypassing enforcement`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Non-member removed the label — re-add it defensively and
|
||||
// set failure outputs so downstream steps (comment, close) fire.
|
||||
// NOTE: addLabels fires a "labeled" event, but the job-level gate
|
||||
// only matches labeled events for "external", so no re-trigger.
|
||||
console.log(`Non-member ${login} removed missing-issue-link — re-adding`);
|
||||
try {
|
||||
await ensureAndAddLabel('missing-issue-link', 'b76e79');
|
||||
} catch (e) {
|
||||
core.warning(
|
||||
`Failed to re-add missing-issue-link (HTTP ${e.status ?? 'unknown'}): ${e.message}. ` +
|
||||
`Downstream step will retry.`,
|
||||
);
|
||||
}
|
||||
core.setOutput('has-link', 'false');
|
||||
core.setOutput('is-assigned', 'false');
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Maintainer override: reopened PR with "missing-issue-link" ──
|
||||
const prLabels = context.payload.pull_request.labels.map(l => l.name);
|
||||
if (action === 'reopened' && prLabels.includes('missing-issue-link')) {
|
||||
const { isMember, login } = await senderIsOrgMember();
|
||||
if (isMember) {
|
||||
await applyMaintainerBypass(
|
||||
`Maintainer ${login} reopened PR #${prNumber} — bypassing enforcement`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
console.log(`Non-member ${login} reopened PR — proceeding with check`);
|
||||
}
|
||||
|
||||
// ── Fetch live labels (race guard) ──────────────────────────────
|
||||
const { data: liveLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner, repo, issue_number: prNumber,
|
||||
});
|
||||
const liveNames = liveLabels.map(l => l.name);
|
||||
if (liveNames.includes('trusted-contributor') || liveNames.includes('bypass-issue-check')) {
|
||||
console.log('PR has trusted-contributor or bypass-issue-check label — bypassing');
|
||||
core.setOutput('has-link', 'true');
|
||||
core.setOutput('is-assigned', 'true');
|
||||
return;
|
||||
}
|
||||
|
||||
const body = context.payload.pull_request.body || '';
|
||||
const pattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*#(\d+)/gi;
|
||||
const matches = [...body.matchAll(pattern)];
|
||||
|
||||
if (matches.length === 0) {
|
||||
console.log('No issue link found in PR body');
|
||||
core.setOutput('has-link', 'false');
|
||||
core.setOutput('is-assigned', 'false');
|
||||
return;
|
||||
}
|
||||
|
||||
const issues = matches.map(m => `#${m[1]}`).join(', ');
|
||||
console.log(`Found issue link(s): ${issues}`);
|
||||
core.setOutput('has-link', 'true');
|
||||
|
||||
// Check whether the PR author is assigned to at least one linked issue
|
||||
const prAuthor = context.payload.pull_request.user.login;
|
||||
const MAX_ISSUES = 5;
|
||||
const allIssueNumbers = [...new Set(matches.map(m => parseInt(m[1], 10)))];
|
||||
const issueNumbers = allIssueNumbers.slice(0, MAX_ISSUES);
|
||||
if (allIssueNumbers.length > MAX_ISSUES) {
|
||||
core.warning(
|
||||
`PR references ${allIssueNumbers.length} issues — only checking the first ${MAX_ISSUES}`,
|
||||
);
|
||||
}
|
||||
|
||||
let assignedToAny = false;
|
||||
for (const num of issueNumbers) {
|
||||
try {
|
||||
const { data: issue } = await github.rest.issues.get({
|
||||
owner, repo, issue_number: num,
|
||||
});
|
||||
const assignees = issue.assignees.map(a => a.login.toLowerCase());
|
||||
if (assignees.includes(prAuthor.toLowerCase())) {
|
||||
console.log(`PR author "${prAuthor}" is assigned to #${num}`);
|
||||
assignedToAny = true;
|
||||
break;
|
||||
} else {
|
||||
console.log(`PR author "${prAuthor}" is NOT assigned to #${num} (assignees: ${assignees.join(', ') || 'none'})`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
console.log(`Issue #${num} not found — skipping`);
|
||||
} else {
|
||||
// Non-404 errors (rate limit, server error) must not be
|
||||
// silently skipped — they could cause false enforcement
|
||||
// (closing a legitimate PR whose assignment can't be verified).
|
||||
throw new Error(
|
||||
`Cannot verify assignee for issue #${num} (${error.status}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput('is-assigned', assignedToAny ? 'true' : 'false');
|
||||
|
||||
- name: Add missing-issue-link label
|
||||
if: >-
|
||||
env.ENFORCE_ISSUE_LINK == 'true' &&
|
||||
(steps.check-link.outputs.has-link != 'true' || steps.check-link.outputs.is-assigned != 'true')
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const prNumber = context.payload.pull_request.number;
|
||||
const labelName = 'missing-issue-link';
|
||||
|
||||
// Ensure the label exists (no checkout/shared helper available)
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: labelName });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner, repo, name: labelName, color: 'b76e79',
|
||||
});
|
||||
} catch (createErr) {
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: prNumber, labels: [labelName],
|
||||
});
|
||||
|
||||
- name: Remove missing-issue-link label and reopen PR
|
||||
if: >-
|
||||
env.ENFORCE_ISSUE_LINK == 'true' &&
|
||||
steps.check-link.outputs.has-link == 'true' && steps.check-link.outputs.is-assigned == 'true'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const prNumber = context.payload.pull_request.number;
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: prNumber, name: 'missing-issue-link',
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
|
||||
// Reopen if this workflow previously closed the PR. We check the
|
||||
// event payload labels (not live labels) because we already removed
|
||||
// missing-issue-link above; the payload still reflects pre-step state.
|
||||
const labels = context.payload.pull_request.labels.map(l => l.name);
|
||||
if (context.payload.pull_request.state === 'closed' && labels.includes('missing-issue-link')) {
|
||||
await github.rest.pulls.update({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
state: 'open',
|
||||
});
|
||||
console.log(`Reopened PR #${prNumber}`);
|
||||
}
|
||||
|
||||
// Minimize stale enforcement comment (best-effort;
|
||||
// sync w/ applyMaintainerBypass above & reopen_on_assignment.yml)
|
||||
try {
|
||||
const marker = '<!-- require-issue-link -->';
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const stale = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (stale) {
|
||||
await github.graphql(`
|
||||
mutation($id: ID!) {
|
||||
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
|
||||
minimizedComment { isMinimized }
|
||||
}
|
||||
}
|
||||
`, { id: stale.node_id });
|
||||
console.log(`Minimized stale enforcement comment ${stale.id} as outdated`);
|
||||
}
|
||||
} catch (e) {
|
||||
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
|
||||
- name: Post comment, close PR, and fail
|
||||
if: >-
|
||||
env.ENFORCE_ISSUE_LINK == 'true' &&
|
||||
(steps.check-link.outputs.has-link != 'true' || steps.check-link.outputs.is-assigned != 'true')
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const prNumber = context.payload.pull_request.number;
|
||||
const hasLink = '${{ steps.check-link.outputs.has-link }}' === 'true';
|
||||
const isAssigned = '${{ steps.check-link.outputs.is-assigned }}' === 'true';
|
||||
const marker = '<!-- require-issue-link -->';
|
||||
|
||||
let lines;
|
||||
if (!hasLink) {
|
||||
lines = [
|
||||
marker,
|
||||
'**This PR has been automatically closed** because it does not link to an approved issue.',
|
||||
'',
|
||||
'All external contributions must reference an approved issue or discussion. Please:',
|
||||
'1. Find or [open an issue](https://github.com/' + owner + '/' + repo + '/issues/new/choose) describing the change',
|
||||
'2. Wait for a maintainer to approve and assign you',
|
||||
'3. Add `Fixes #<issue_number>`, `Closes #<issue_number>`, or `Resolves #<issue_number>` to your PR description and the PR will be reopened automatically',
|
||||
'',
|
||||
'*Maintainers: reopen this PR or remove the `missing-issue-link` label to bypass this check.*',
|
||||
];
|
||||
} else {
|
||||
lines = [
|
||||
marker,
|
||||
'**This PR has been automatically closed** because you are not assigned to the linked issue.',
|
||||
'',
|
||||
'External contributors must be assigned to an issue before opening a PR for it. Please:',
|
||||
'1. Comment on the linked issue to request assignment from a maintainer',
|
||||
'2. Once assigned, your PR will be reopened automatically',
|
||||
'',
|
||||
'*Maintainers: reopen this PR or remove the `missing-issue-link` label to bypass this check.*',
|
||||
];
|
||||
}
|
||||
|
||||
const body = lines.join('\n');
|
||||
|
||||
// Deduplicate: check for existing comment with the marker
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const existing = comments.find(c => c.body && c.body.includes(marker));
|
||||
|
||||
if (!existing) {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
console.log('Posted requirement comment');
|
||||
} else if (existing.body !== body) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
console.log('Updated existing comment with new message');
|
||||
} else {
|
||||
console.log('Comment already exists — skipping');
|
||||
}
|
||||
|
||||
// Close the PR
|
||||
if (context.payload.pull_request.state === 'open') {
|
||||
await github.rest.pulls.update({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
state: 'closed',
|
||||
});
|
||||
console.log(`Closed PR #${prNumber}`);
|
||||
}
|
||||
|
||||
// Cancel all other in-progress and queued workflow runs for this PR
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
for (const status of ['in_progress', 'queued']) {
|
||||
const runs = await github.paginate(
|
||||
github.rest.actions.listWorkflowRunsForRepo,
|
||||
{ owner, repo, head_sha: headSha, status, per_page: 100 },
|
||||
);
|
||||
for (const run of runs) {
|
||||
if (run.id === context.runId) continue;
|
||||
try {
|
||||
await github.rest.actions.cancelWorkflowRun({
|
||||
owner, repo, run_id: run.id,
|
||||
});
|
||||
console.log(`Cancelled ${status} run ${run.id} (${run.name})`);
|
||||
} catch (err) {
|
||||
console.log(`Could not cancel run ${run.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reason = !hasLink
|
||||
? 'PR must reference an issue using auto-close keywords (e.g., "Fixes #123").'
|
||||
: 'PR author must be assigned to the linked issue.';
|
||||
core.setFailed(reason);
|
||||
@@ -0,0 +1,402 @@
|
||||
# Automatically tag issues as "external" or "internal" based on whether
|
||||
# the author is a member of the langchain-ai GitHub organization, and
|
||||
# apply contributor tier labels to external contributors based on their
|
||||
# merged PR history.
|
||||
#
|
||||
# PR labeling is handled by tag-external-prs.yml.
|
||||
# PR + issue backfill lives in the backfill job below (workflow_dispatch).
|
||||
#
|
||||
# Setup Requirements:
|
||||
# 1. Create a GitHub App with permissions:
|
||||
# - Repository: Issues (write), Pull requests (write)
|
||||
# - Organization: Members (read)
|
||||
# 2. Install the app on your organization and this repository
|
||||
# 3. Add these repository secrets:
|
||||
# - ORG_MEMBERSHIP_APP_ID: Your app's ID
|
||||
# - ORG_MEMBERSHIP_APP_PRIVATE_KEY: Your app's private key
|
||||
#
|
||||
# The GitHub App token is required to check private organization membership.
|
||||
# Without it, the workflow will fail.
|
||||
|
||||
name: Tag External Issues
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
backfill_type:
|
||||
description: "Backfill type (for initial run)"
|
||||
default: "both"
|
||||
type: choice
|
||||
options:
|
||||
- prs
|
||||
- issues
|
||||
- both
|
||||
max_items:
|
||||
description: "Maximum number of items to process"
|
||||
default: "100"
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
tag-external:
|
||||
if: github.event_name == 'issues'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
steps:
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ORG_MEMBERSHIP_APP_ID }}
|
||||
private-key: ${{ secrets.ORG_MEMBERSHIP_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Check if contributor is external
|
||||
if: steps.app-token.outcome == 'success'
|
||||
id: check-membership
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ steps.app-token.outputs.token }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const author = context.payload.sender.login;
|
||||
const senderType = context.payload.sender.type;
|
||||
|
||||
if (senderType === 'Bot') {
|
||||
console.log(`${author} is a Bot — treating as internal`);
|
||||
core.setOutput('is-external', 'false');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const membership = await github.rest.orgs.getMembershipForUser({
|
||||
org: 'langchain-ai',
|
||||
username: author,
|
||||
});
|
||||
const isExternal = membership.data.state !== 'active';
|
||||
console.log(
|
||||
isExternal
|
||||
? `${author} has pending membership — treating as external`
|
||||
: `${author} is an active member of langchain-ai`,
|
||||
);
|
||||
core.setOutput('is-external', isExternal ? 'true' : 'false');
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`${author} is not a member of langchain-ai`);
|
||||
core.setOutput('is-external', 'true');
|
||||
} else {
|
||||
throw new Error(
|
||||
`Membership check failed for ${author} (${e.status}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
- name: Apply contributor tier label
|
||||
if: steps.check-membership.outputs.is-external == 'true'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issue = context.payload.issue;
|
||||
const author = issue.user.login;
|
||||
const issueNumber = issue.number;
|
||||
|
||||
const TRUSTED_THRESHOLD = 5;
|
||||
const LABEL_COLOR = 'b76e79';
|
||||
|
||||
let mergedCount;
|
||||
try {
|
||||
const result = await github.rest.search.issuesAndPullRequests({
|
||||
q: `repo:${owner}/${repo} is:pr is:merged author:"${author}"`,
|
||||
per_page: 1,
|
||||
});
|
||||
mergedCount = result?.data?.total_count;
|
||||
} catch (error) {
|
||||
if (error?.status !== 422) throw error;
|
||||
core.warning(`Search failed for ${author}; skipping tier label.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mergedCount == null) {
|
||||
core.warning(`Search response missing total_count for ${author}; skipping tier label.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const tierLabel = mergedCount >= TRUSTED_THRESHOLD ? 'trusted-contributor' : null;
|
||||
|
||||
if (tierLabel) {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: tierLabel });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner, repo, name: tierLabel, color: LABEL_COLOR });
|
||||
} catch (createErr) {
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: issueNumber, labels: [tierLabel],
|
||||
});
|
||||
console.log(`Applied '${tierLabel}' to #${issueNumber} (${mergedCount} merged PRs)`);
|
||||
} else {
|
||||
console.log(`No tier label for ${author} (${mergedCount} merged PRs)`);
|
||||
}
|
||||
|
||||
- name: Add external label
|
||||
if: steps.check-membership.outputs.is-external == 'true'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = context.payload.issue.number;
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number, labels: ['external'],
|
||||
});
|
||||
console.log(`Added 'external' label to issue #${issue_number}`);
|
||||
|
||||
- name: Add internal label
|
||||
if: steps.check-membership.outputs.is-external == 'false'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = context.payload.issue.number;
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number, labels: ['internal'],
|
||||
});
|
||||
console.log(`Added 'internal' label to issue #${issue_number}`);
|
||||
|
||||
backfill:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ORG_MEMBERSHIP_APP_ID }}
|
||||
private-key: ${{ secrets.ORG_MEMBERSHIP_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Backfill labels
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ steps.app-token.outputs.token }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const rawMax = '${{ inputs.max_items }}';
|
||||
const maxItems = parseInt(rawMax, 10);
|
||||
if (isNaN(maxItems) || maxItems <= 0) {
|
||||
core.setFailed(`Invalid max_items: "${rawMax}" — must be a positive integer`);
|
||||
return;
|
||||
}
|
||||
const backfillType = '${{ inputs.backfill_type }}';
|
||||
|
||||
const TRUSTED_THRESHOLD = 5;
|
||||
const LABEL_COLOR = 'b76e79';
|
||||
|
||||
const tierLabels = ['trusted-contributor'];
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────
|
||||
|
||||
async function ensureLabel(name) {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner, repo, name, color: LABEL_COLOR });
|
||||
} catch (createErr) {
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function checkMembership(author, userType) {
|
||||
if (userType === 'Bot') {
|
||||
console.log(`${author} is a Bot — treating as internal`);
|
||||
return { isExternal: false };
|
||||
}
|
||||
try {
|
||||
const membership = await github.rest.orgs.getMembershipForUser({
|
||||
org: 'langchain-ai',
|
||||
username: author,
|
||||
});
|
||||
const isExternal = membership.data.state !== 'active';
|
||||
console.log(
|
||||
isExternal
|
||||
? `${author} has pending membership — treating as external`
|
||||
: `${author} is an active member of langchain-ai`,
|
||||
);
|
||||
return { isExternal };
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`${author} is not a member of langchain-ai`);
|
||||
return { isExternal: true };
|
||||
}
|
||||
throw new Error(
|
||||
`Membership check failed for ${author} (${e.status}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function getContributorInfo(contributorCache, author, userType) {
|
||||
if (contributorCache.has(author)) return contributorCache.get(author);
|
||||
|
||||
const { isExternal } = await checkMembership(author, userType);
|
||||
|
||||
let mergedCount = null;
|
||||
if (isExternal) {
|
||||
try {
|
||||
const result = await github.rest.search.issuesAndPullRequests({
|
||||
q: `repo:${owner}/${repo} is:pr is:merged author:"${author}"`,
|
||||
per_page: 1,
|
||||
});
|
||||
mergedCount = result?.data?.total_count ?? null;
|
||||
} catch (e) {
|
||||
if (e?.status !== 422) throw e;
|
||||
core.warning(`Search failed for ${author}; skipping tier.`);
|
||||
}
|
||||
}
|
||||
|
||||
const info = { isExternal, mergedCount };
|
||||
contributorCache.set(author, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
// ── Setup ────────────────────────────────────────────────────
|
||||
|
||||
for (const name of tierLabels) {
|
||||
await ensureLabel(name);
|
||||
}
|
||||
|
||||
const contributorCache = new Map();
|
||||
|
||||
let processed = 0;
|
||||
let failures = 0;
|
||||
|
||||
// ── Backfill PRs ─────────────────────────────────────────────
|
||||
|
||||
if (backfillType === 'prs' || backfillType === 'both') {
|
||||
const prs = await github.paginate(github.rest.pulls.list, {
|
||||
owner, repo, state: 'open', per_page: 100,
|
||||
});
|
||||
|
||||
for (const pr of prs) {
|
||||
if (processed >= maxItems) break;
|
||||
|
||||
try {
|
||||
const author = pr.user.login;
|
||||
const info = await getContributorInfo(contributorCache, author, pr.user.type);
|
||||
|
||||
const labels = [info.isExternal ? 'external' : 'internal'];
|
||||
if (info.isExternal && info.mergedCount != null && info.mergedCount >= TRUSTED_THRESHOLD) {
|
||||
labels.push('trusted-contributor');
|
||||
}
|
||||
|
||||
// Ensure all labels exist before batch add
|
||||
for (const name of labels) {
|
||||
await ensureLabel(name);
|
||||
}
|
||||
|
||||
// Remove stale tier labels
|
||||
const currentLabels = (await github.paginate(
|
||||
github.rest.issues.listLabelsOnIssue,
|
||||
{ owner, repo, issue_number: pr.number, per_page: 100 },
|
||||
)).map(l => l.name ?? '');
|
||||
for (const name of currentLabels) {
|
||||
if (tierLabels.includes(name) && !labels.includes(name)) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: pr.number, name,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: pr.number, labels,
|
||||
});
|
||||
console.log(`PR #${pr.number} (${author}): ${labels.join(', ')}`);
|
||||
processed++;
|
||||
} catch (e) {
|
||||
failures++;
|
||||
core.warning(`Failed to process PR #${pr.number}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Backfill issues ──────────────────────────────────────────
|
||||
|
||||
if (backfillType === 'issues' || backfillType === 'both') {
|
||||
const issues = await github.paginate(github.rest.issues.listForRepo, {
|
||||
owner, repo, state: 'open', per_page: 100,
|
||||
});
|
||||
|
||||
for (const issue of issues) {
|
||||
if (processed >= maxItems) break;
|
||||
if (issue.pull_request) continue;
|
||||
|
||||
try {
|
||||
const author = issue.user.login;
|
||||
const info = await getContributorInfo(contributorCache, author, issue.user.type);
|
||||
|
||||
const labels = [info.isExternal ? 'external' : 'internal'];
|
||||
if (info.isExternal && info.mergedCount != null && info.mergedCount >= TRUSTED_THRESHOLD) {
|
||||
labels.push('trusted-contributor');
|
||||
}
|
||||
|
||||
// Ensure all labels exist before batch add
|
||||
for (const name of labels) {
|
||||
await ensureLabel(name);
|
||||
}
|
||||
|
||||
// Remove stale tier labels
|
||||
const currentLabels = (await github.paginate(
|
||||
github.rest.issues.listLabelsOnIssue,
|
||||
{ owner, repo, issue_number: issue.number, per_page: 100 },
|
||||
)).map(l => l.name ?? '');
|
||||
for (const name of currentLabels) {
|
||||
if (tierLabels.includes(name) && !labels.includes(name)) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: issue.number, name,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: issue.number, labels,
|
||||
});
|
||||
console.log(`Issue #${issue.number} (${author}): ${labels.join(', ')}`);
|
||||
processed++;
|
||||
} catch (e) {
|
||||
failures++;
|
||||
core.warning(`Failed to process issue #${issue.number}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nBackfill complete. Processed ${processed} items, ${failures} failures. ${contributorCache.size} unique authors.`);
|
||||
@@ -0,0 +1,173 @@
|
||||
# Automatically tag pull requests as "external" or "internal" based on
|
||||
# whether the author is a member of the langchain-ai GitHub organization,
|
||||
# and apply contributor tier labels to external contributors based on
|
||||
# their merged PR history.
|
||||
#
|
||||
# Issue labeling is handled by tag-external-issues.yml.
|
||||
# Backfill (workflow_dispatch) also lives in tag-external-issues.yml.
|
||||
#
|
||||
# Setup Requirements:
|
||||
# 1. Create a GitHub App with permissions:
|
||||
# - Repository: Pull requests (write)
|
||||
# - Organization: Members (read)
|
||||
# 2. Install the app on your organization and this repository
|
||||
# 3. Add these repository secrets:
|
||||
# - ORG_MEMBERSHIP_APP_ID: Your app's ID
|
||||
# - ORG_MEMBERSHIP_APP_PRIVATE_KEY: Your app's private key
|
||||
#
|
||||
# The GitHub App token is required to check private organization membership.
|
||||
# Without it, the workflow will fail.
|
||||
|
||||
name: Tag External PRs
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
tag-external:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ORG_MEMBERSHIP_APP_ID }}
|
||||
private-key: ${{ secrets.ORG_MEMBERSHIP_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Check if contributor is external
|
||||
if: steps.app-token.outcome == 'success'
|
||||
id: check-membership
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ steps.app-token.outputs.token }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const author = context.payload.sender.login;
|
||||
const senderType = context.payload.sender.type;
|
||||
|
||||
if (senderType === 'Bot') {
|
||||
console.log(`${author} is a Bot — treating as internal`);
|
||||
core.setOutput('is-external', 'false');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const membership = await github.rest.orgs.getMembershipForUser({
|
||||
org: 'langchain-ai',
|
||||
username: author,
|
||||
});
|
||||
const isExternal = membership.data.state !== 'active';
|
||||
console.log(
|
||||
isExternal
|
||||
? `${author} has pending membership — treating as external`
|
||||
: `${author} is an active member of langchain-ai`,
|
||||
);
|
||||
core.setOutput('is-external', isExternal ? 'true' : 'false');
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`${author} is not a member of langchain-ai`);
|
||||
core.setOutput('is-external', 'true');
|
||||
} else {
|
||||
throw new Error(
|
||||
`Membership check failed for ${author} (${e.status}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
# Apply tier label BEFORE the external label so that
|
||||
# "trusted-contributor" is already present when the "external" labeled
|
||||
# event fires and triggers require_issue_link.yml.
|
||||
- name: Apply contributor tier label
|
||||
if: steps.check-membership.outputs.is-external == 'true'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
# Use App token so the "labeled" event propagates to downstream
|
||||
# workflows (e.g. require_issue_link.yml).
|
||||
github-token: ${{ steps.app-token.outputs.token }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const pr = context.payload.pull_request;
|
||||
const author = pr.user.login;
|
||||
const prNumber = pr.number;
|
||||
|
||||
const TRUSTED_THRESHOLD = 5;
|
||||
const LABEL_COLOR = 'b76e79';
|
||||
|
||||
let mergedCount;
|
||||
try {
|
||||
const result = await github.rest.search.issuesAndPullRequests({
|
||||
q: `repo:${owner}/${repo} is:pr is:merged author:"${author}"`,
|
||||
per_page: 1,
|
||||
});
|
||||
mergedCount = result?.data?.total_count;
|
||||
} catch (error) {
|
||||
if (error?.status !== 422) throw error;
|
||||
core.warning(`Search failed for ${author}; skipping tier label.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mergedCount == null) {
|
||||
core.warning(`Search response missing total_count for ${author}; skipping tier label.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const tierLabel = mergedCount >= TRUSTED_THRESHOLD ? 'trusted-contributor' : null;
|
||||
|
||||
if (tierLabel) {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: tierLabel });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner, repo, name: tierLabel, color: LABEL_COLOR });
|
||||
} catch (createErr) {
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: prNumber, labels: [tierLabel],
|
||||
});
|
||||
console.log(`Applied '${tierLabel}' to PR #${prNumber} (${mergedCount} merged PRs)`);
|
||||
} else {
|
||||
console.log(`No tier label for ${author} (${mergedCount} merged PRs)`);
|
||||
}
|
||||
|
||||
- name: Add external label
|
||||
if: steps.check-membership.outputs.is-external == 'true'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
# Use App token so the "labeled" event propagates to downstream
|
||||
# workflows (e.g. require_issue_link.yml). Events created by the
|
||||
# default GITHUB_TOKEN do not trigger additional workflow runs.
|
||||
github-token: ${{ steps.app-token.outputs.token }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = context.payload.pull_request.number;
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number, labels: ['external'],
|
||||
});
|
||||
console.log(`Added 'external' label to PR #${issue_number}`);
|
||||
|
||||
- name: Add internal label
|
||||
if: steps.check-membership.outputs.is-external == 'false'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = context.payload.pull_request.number;
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number, labels: ['internal'],
|
||||
});
|
||||
console.log(`Added 'internal' label to PR #${issue_number}`);
|
||||
@@ -0,0 +1,43 @@
|
||||
name: UV Lock Upgrade
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# run at midnight every Sunday
|
||||
- cron: '0 0 * * 0'
|
||||
# allow manual triggering
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
upgrade-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up uv
|
||||
uses: ./.github/actions/uv_setup
|
||||
with:
|
||||
python-version: "3.10"
|
||||
cache-suffix: "uv-lock-upgrade"
|
||||
|
||||
- name: Run uv lock --upgrade in all Python packages
|
||||
run: make lock-upgrade
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
commit-message: "chore(deps): upgrade dependencies with `uv lock --upgrade`"
|
||||
title: "chore(deps): upgrade dependencies with `uv lock --upgrade`"
|
||||
body: |
|
||||
This PR updates the dependencies in all Python packages using `uv lock --upgrade`.
|
||||
|
||||
This is an automated PR created by the UV Lock Upgrade workflow.
|
||||
branch: deps/uv-lock-upgrade
|
||||
delete-branch: true
|
||||
labels: |
|
||||
dependencies
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
.vs/
|
||||
.vscode/
|
||||
.idea/
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
notebooks/
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
.venvs
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# macOS display setting files
|
||||
.DS_Store
|
||||
|
||||
.vercel
|
||||
.turbo
|
||||
.editorconfig
|
||||
.scratch
|
||||
.worktrees/
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"MD013": false,
|
||||
"MD024": {
|
||||
"siblings_only": true
|
||||
},
|
||||
"MD025": false,
|
||||
"MD033": false,
|
||||
"MD034": false,
|
||||
"MD036": false,
|
||||
"MD041": false,
|
||||
"MD046": {
|
||||
"style": "fenced"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# AGENTS Instructions
|
||||
|
||||
This repository is a monorepo. Each library lives in a subdirectory under `libs/`.
|
||||
|
||||
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
|
||||
- `make lint` – run the linter
|
||||
- `make test` – execute the test suite
|
||||
|
||||
To run a particular test file or to pass additional pytest options you can specify the `TEST` variable:
|
||||
|
||||
```txt
|
||||
TEST=path/to/test.py make test
|
||||
```
|
||||
|
||||
Other pytest arguments can also be supplied inside the `TEST` variable.
|
||||
|
||||
## Libraries
|
||||
|
||||
The repository contains several Python and JavaScript/TypeScript libraries.
|
||||
Below is a high-level overview:
|
||||
|
||||
- **checkpoint** – base interfaces for LangGraph checkpointers.
|
||||
- **checkpoint-postgres** – Postgres implementation of the checkpoint saver.
|
||||
- **checkpoint-sqlite** – SQLite implementation of the checkpoint saver.
|
||||
- **cli** – official command-line interface for LangGraph.
|
||||
- **langgraph** – core framework for building stateful, multi-actor agents.
|
||||
- **prebuilt** – high-level APIs for creating and running agents and tools.
|
||||
- **sdk-js** – JS/TS SDK for interacting with the LangGraph REST API.
|
||||
- **sdk-py** – Python SDK for the LangGraph Server API.
|
||||
|
||||
### Dependency map
|
||||
|
||||
The diagram below lists downstream libraries for each production dependency as
|
||||
declared in that library's `pyproject.toml` (or `package.json`).
|
||||
|
||||
```text
|
||||
checkpoint
|
||||
├── checkpoint-postgres
|
||||
├── checkpoint-sqlite
|
||||
├── prebuilt
|
||||
└── langgraph
|
||||
|
||||
prebuilt
|
||||
└── langgraph
|
||||
|
||||
sdk-py
|
||||
├── langgraph
|
||||
└── cli
|
||||
|
||||
sdk-js (standalone)
|
||||
```
|
||||
|
||||
Changes to a library may impact all of its dependents shown above.
|
||||
|
||||
- Do NOT use Sphinx-style double backtick formatting (` ``code`` `). Use single backticks (`` `code` ``) for inline code references in docstrings and comments.
|
||||
@@ -0,0 +1,57 @@
|
||||
# AGENTS Instructions
|
||||
|
||||
This repository is a monorepo. Each library lives in a subdirectory under `libs/`.
|
||||
|
||||
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
|
||||
- `make lint` – run the linter
|
||||
- `make test` – execute the test suite
|
||||
|
||||
To run a particular test file or to pass additional pytest options you can specify the `TEST` variable:
|
||||
|
||||
```
|
||||
TEST=path/to/test.py make test
|
||||
```
|
||||
|
||||
Other pytest arguments can also be supplied inside the `TEST` variable.
|
||||
|
||||
## Libraries
|
||||
|
||||
The repository contains several Python and JavaScript/TypeScript libraries.
|
||||
Below is a high-level overview:
|
||||
|
||||
- **checkpoint** – base interfaces for LangGraph checkpointers.
|
||||
- **checkpoint-postgres** – Postgres implementation of the checkpoint saver.
|
||||
- **checkpoint-sqlite** – SQLite implementation of the checkpoint saver.
|
||||
- **cli** – official command-line interface for LangGraph.
|
||||
- **langgraph** – core framework for building stateful, multi-actor agents.
|
||||
- **prebuilt** – high-level APIs for creating and running agents and tools.
|
||||
- **sdk-js** – JS/TS SDK for interacting with the LangGraph REST API.
|
||||
- **sdk-py** – Python SDK for the LangGraph Server API.
|
||||
|
||||
### Dependency map
|
||||
|
||||
The diagram below lists downstream libraries for each production dependency as
|
||||
declared in that library's `pyproject.toml` (or `package.json`).
|
||||
|
||||
```text
|
||||
checkpoint
|
||||
├── checkpoint-postgres
|
||||
├── checkpoint-sqlite
|
||||
├── prebuilt
|
||||
└── langgraph
|
||||
|
||||
prebuilt
|
||||
└── langgraph
|
||||
|
||||
sdk-py
|
||||
├── langgraph
|
||||
└── cli
|
||||
|
||||
sdk-js (standalone)
|
||||
```
|
||||
|
||||
Changes to a library may impact all of its dependents shown above.
|
||||
|
||||
- Do NOT use Sphinx-style double backtick formatting (` ``code`` `). Use single backticks (`` `code` ``) for inline code references in docstrings and comments.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 LangChain, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Define the directories containing projects
|
||||
LIBS_DIRS := $(wildcard libs/*)
|
||||
|
||||
# Default target
|
||||
.PHONY: all
|
||||
all: lint format lock test
|
||||
|
||||
# Install dependencies for all projects
|
||||
.PHONY: install
|
||||
install:
|
||||
@echo "Creating virtual environment..."
|
||||
@uv venv
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/pyproject.toml ]; then \
|
||||
echo "Installing dependencies for $$dir"; \
|
||||
uv pip install -e $$dir; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# Lint all projects
|
||||
.PHONY: lint
|
||||
lint:
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/Makefile ]; then \
|
||||
echo "Running lint in $$dir"; \
|
||||
$(MAKE) -C $$dir lint; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# Format all projects
|
||||
.PHONY: format
|
||||
format:
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/Makefile ]; then \
|
||||
echo "Running format in $$dir"; \
|
||||
$(MAKE) -C $$dir format; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# Lock all projects
|
||||
.PHONY: lock
|
||||
lock:
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/Makefile ]; then \
|
||||
echo "Running lock in $$dir"; \
|
||||
(cd $$dir && uv lock); \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# Lock all projects and upgrade dependencies
|
||||
.PHONY: lock-upgrade
|
||||
lock-upgrade:
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/Makefile ]; then \
|
||||
echo "Running lock-upgrade in $$dir"; \
|
||||
(cd $$dir && uv lock --upgrade); \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# Test all projects
|
||||
.PHONY: test
|
||||
test:
|
||||
@for dir in $(LIBS_DIRS); do \
|
||||
if [ -f $$dir/Makefile ]; then \
|
||||
echo "Running test in $$dir"; \
|
||||
$(MAKE) -C $$dir test; \
|
||||
fi; \
|
||||
done
|
||||
@@ -0,0 +1,82 @@
|
||||
<div align="center">
|
||||
<a href="https://www.langchain.com/langgraph">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset=".github/images/logo-dark.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset=".github/images/logo-light.svg">
|
||||
<img alt="LangGraph Logo" src=".github/images/logo-dark.svg" width="50%">
|
||||
</picture>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<h3>Low-level orchestration framework for building stateful agents.</h3>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://opensource.org/licenses/MIT" target="_blank"><img src="https://img.shields.io/pypi/l/langgraph" alt="PyPI - License"></a>
|
||||
<a href="https://pypistats.org/packages/langgraph" target="_blank"><img src="https://img.shields.io/pepy/dt/langgraph" alt="PyPI - Downloads"></a>
|
||||
<a href="https://pypi.org/project/langgraph/" target="_blank"><img src="https://img.shields.io/pypi/v/langgraph.svg?label=%20" alt="Version"></a>
|
||||
<a href="https://x.com/langchain_oss" target="_blank"><img src="https://img.shields.io/twitter/url/https/twitter.com/langchain_oss.svg?style=social&label=Follow%20%40LangChain" alt="Twitter / X"></a>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
Trusted by companies shaping the future of agents – including Klarna, Replit, Elastic, and more – LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents.
|
||||
|
||||
```bash
|
||||
pip install -U langgraph
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> If you're looking to quickly build agents, check out **[Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview)** — a higher-level package built on LangGraph for agents that can plan, use subagents, and leverage file systems for complex tasks.
|
||||
|
||||
For an equivalent JS/TS library, check out [LangGraph.js](https://github.com/langchain-ai/langgraphjs) and the [JS docs](https://docs.langchain.com/oss/javascript/langgraph/overview).
|
||||
|
||||
## Why use LangGraph?
|
||||
|
||||
LangGraph provides low-level supporting infrastructure for *any* long-running, stateful workflow or agent:
|
||||
|
||||
- **[Durable execution](https://docs.langchain.com/oss/python/langgraph/durable-execution)** — Build agents that persist through failures and can run for extended periods, automatically resuming from exactly where they left off.
|
||||
- **[Human-in-the-loop](https://docs.langchain.com/oss/python/langgraph/interrupts)** — Seamlessly incorporate human oversight by inspecting and modifying agent state at any point during execution.
|
||||
- **[Comprehensive memory](https://docs.langchain.com/oss/python/langgraph/memory)** — Create truly stateful agents with both short-term working memory for ongoing reasoning and long-term persistent memory across sessions.
|
||||
- **[Debugging with LangSmith](https://www.langchain.com/langsmith)** — Gain deep visibility into complex agent behavior with visualization tools that trace execution paths, capture state transitions, and provide detailed runtime metrics.
|
||||
- **[Production-ready deployment](https://docs.langchain.com/langsmith/deployments)** — Deploy sophisticated agent systems confidently with scalable infrastructure designed to handle the unique challenges of stateful, long-running workflows.
|
||||
|
||||
> [!TIP]
|
||||
> For developing, debugging, and deploying AI agents and LLM applications, see [LangSmith](https://docs.langchain.com/langsmith/home).
|
||||
|
||||
## LangGraph ecosystem
|
||||
|
||||
While LangGraph can be used standalone, it also integrates seamlessly with any LangChain product, giving developers a full suite of tools for building agents.
|
||||
|
||||
To improve your LLM application development, pair LangGraph with:
|
||||
|
||||
- [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) – Build agents that can plan, use subagents, and leverage file systems for complex tasks.
|
||||
- [LangChain](https://docs.langchain.com/oss/python/langchain/overview) – Provides integrations and composable components to streamline LLM application development.
|
||||
- [LangSmith](https://www.langchain.com/langsmith) – Helpful for agent evals and observability. Debug poor-performing LLM app runs, evaluate agent trajectories, gain visibility in production, and improve performance over time.
|
||||
- [LangSmith Deployment](https://docs.langchain.com/langsmith/deployments) – Deploy and scale agents effortlessly with a purpose-built deployment platform for long-running, stateful workflows. Discover, reuse, configure, and share agents across teams – and iterate quickly with visual prototyping in [LangSmith Studio](https://docs.langchain.com/langsmith/studio).
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- [docs.langchain.com](https://docs.langchain.com/oss/python/langgraph/overview) – Comprehensive documentation, including conceptual overviews and guides
|
||||
- [reference.langchain.com/python/langgraph](https://reference.langchain.com/python/langgraph) – API reference docs for LangGraph packages
|
||||
- [LangGraph Quickstart](https://docs.langchain.com/oss/python/langgraph/quickstart) – Get started building with LangGraph
|
||||
- [Chat LangChain](https://chat.langchain.com/) – Chat with the LangChain documentation and get answers to your questions
|
||||
|
||||
**Discussions**: Visit the [LangChain Forum](https://forum.langchain.com) to connect with the community and share all of your technical questions, ideas, and feedback.
|
||||
|
||||
## Additional resources
|
||||
|
||||
- **[Guides](https://docs.langchain.com/oss/python/learn)** – Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
|
||||
- **[LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph)** – Learn the basics of LangGraph in our free, structured course.
|
||||
- **[Case studies](https://www.langchain.com/built-with-langgraph)** – Hear how industry leaders use LangGraph to ship AI applications at scale.
|
||||
- [Contributing Guide](https://docs.langchain.com/oss/python/contributing/overview) – Learn how to contribute to LangChain projects and find good first issues.
|
||||
- [Code of Conduct](https://github.com/langchain-ai/langchain/?tab=coc-ov-file) – Our community guidelines and standards for participation.
|
||||
|
||||
---
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
LangGraph is inspired by [Pregel](https://research.google/pubs/pub37252/) and [Apache Beam](https://beam.apache.org/). The public interface draws inspiration from [NetworkX](https://networkx.org/documentation/latest/). LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
|
||||
@@ -0,0 +1,7 @@
|
||||
# WeHub 来源说明
|
||||
|
||||
- 原始项目:`langchain-ai/langgraph`
|
||||
- 原始仓库:https://github.com/langchain-ai/langgraph
|
||||
- 导入方式:上游默认分支的最新快照
|
||||
- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准
|
||||
- 本文件仅用于记录来源,不代表 WeHub 是原项目作者
|
||||
@@ -0,0 +1 @@
|
||||
_site/
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate HTML redirect files from redirects.json.
|
||||
|
||||
Usage:
|
||||
python generate_redirects.py
|
||||
|
||||
This script reads redirects.json and generates individual HTML files
|
||||
for each redirect path. Each HTML file uses meta refresh (0 delay)
|
||||
which is SEO-friendly and treated similarly to 301 redirects by Google.
|
||||
|
||||
To add new redirects, simply edit redirects.json and re-run this script.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Default fallback URL for any path not in the redirect map
|
||||
DEFAULT_REDIRECT = "https://docs.langchain.com/oss/python/langgraph/overview"
|
||||
|
||||
HTML_TEMPLATE = """<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Redirecting...</title>
|
||||
<link rel="canonical" href="{url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<script>var anchor=window.location.hash.substr(1);location.href="{url}"+(anchor?"#"+anchor:"")</script>
|
||||
<meta http-equiv="refresh" content="0; url={url}">
|
||||
</head>
|
||||
<body>
|
||||
Redirecting...
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
ROOT_HTML_TEMPLATE = """<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Redirecting to LangGraph Documentation</title>
|
||||
<link rel="canonical" href="{url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<script>var anchor=window.location.hash.substr(1);location.href="{url}"+(anchor?"#"+anchor:"")</script>
|
||||
<meta http-equiv="refresh" content="0; url={url}">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Documentation has moved</h1>
|
||||
<p>The LangGraph documentation has moved to <a href="{url}">docs.langchain.com</a>.</p>
|
||||
<p>Redirecting you now...</p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
CATCHALL_404_TEMPLATE = """<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Redirecting to LangGraph Documentation</title>
|
||||
<link rel="canonical" href="{default_url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<script>
|
||||
// Catchall redirect for any unmapped paths
|
||||
window.location.replace("{default_url}");
|
||||
</script>
|
||||
<meta http-equiv="refresh" content="0; url={default_url}">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Documentation has moved</h1>
|
||||
<p>The LangGraph documentation has moved to <a href="{default_url}">docs.langchain.com</a>.</p>
|
||||
<p>Redirecting you now...</p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def generate_redirects():
|
||||
script_dir = Path(__file__).parent
|
||||
output_dir = script_dir / "_site"
|
||||
|
||||
# Load redirects
|
||||
with open(script_dir / "redirects.json") as f:
|
||||
redirects = json.load(f)
|
||||
|
||||
# Clean output directory
|
||||
if output_dir.exists():
|
||||
import shutil
|
||||
shutil.rmtree(output_dir)
|
||||
output_dir.mkdir(parents=True)
|
||||
|
||||
# Generate individual HTML files for each redirect
|
||||
for old_path, new_url in redirects.items():
|
||||
# Remove leading slash and create directory structure
|
||||
path = old_path.lstrip("/")
|
||||
|
||||
# Check if path has a file extension (e.g., .txt, .xml)
|
||||
# If so, create the file directly instead of a directory with index.html
|
||||
path_obj = Path(path)
|
||||
has_extension = path_obj.suffix and len(path_obj.suffix) <= 5
|
||||
|
||||
if not path:
|
||||
html_path = output_dir / "index.html"
|
||||
elif has_extension:
|
||||
# For files with extensions, create the file directly
|
||||
html_path = output_dir / path
|
||||
else:
|
||||
# For directory-style URLs, create index.html inside
|
||||
html_path = output_dir / path / "index.html"
|
||||
|
||||
# Create parent directories
|
||||
html_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write the redirect HTML
|
||||
html_path.write_text(HTML_TEMPLATE.format(url=new_url))
|
||||
print(f"Created: {html_path}")
|
||||
|
||||
# Create root index.html
|
||||
root_index = output_dir / "index.html"
|
||||
if not root_index.exists():
|
||||
root_index.write_text(ROOT_HTML_TEMPLATE.format(url=DEFAULT_REDIRECT))
|
||||
print(f"Created: {root_index}")
|
||||
|
||||
# Create 404.html for catchall
|
||||
catchall_404 = output_dir / "404.html"
|
||||
catchall_404.write_text(CATCHALL_404_TEMPLATE.format(default_url=DEFAULT_REDIRECT))
|
||||
print(f"Created: {catchall_404}")
|
||||
|
||||
# Copy static files (like llms.txt) that can't be redirected via HTML
|
||||
static_files = ["llms.txt"]
|
||||
for static_file in static_files:
|
||||
src = script_dir / static_file
|
||||
if src.exists():
|
||||
dst = output_dir / static_file
|
||||
dst.write_text(src.read_text())
|
||||
print(f"Copied: {dst}")
|
||||
|
||||
print(f"\nGenerated {len(redirects)} redirect files in {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_redirects()
|
||||
@@ -0,0 +1,35 @@
|
||||
# LangGraph
|
||||
|
||||
LangGraph documentation has moved to docs.langchain.com.
|
||||
|
||||
## Overview
|
||||
|
||||
- [LangGraph Overview](https://docs.langchain.com/oss/python/langgraph/overview): Introduction to LangGraph, a library for building stateful, multi-actor applications with LLMs.
|
||||
- [Why LangGraph?](https://docs.langchain.com/oss/python/langgraph/why-langgraph): Motivation for LangGraph and its key features.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
- [Graph API](https://docs.langchain.com/oss/python/langgraph/graph-api): Learn how to define state, create nodes, and connect them with edges.
|
||||
- [Streaming](https://docs.langchain.com/oss/python/langgraph/streaming): Stream outputs from your graph for better UX.
|
||||
- [Persistence](https://docs.langchain.com/oss/python/langgraph/persistence): Add memory and checkpointing to your graphs.
|
||||
- [Add Memory](https://docs.langchain.com/oss/python/langgraph/add-memory): Implement short-term and long-term memory.
|
||||
- [Workflows & Agents](https://docs.langchain.com/oss/python/langgraph/workflows-agents): Build agents and workflows with LangGraph.
|
||||
|
||||
## How-To Guides
|
||||
|
||||
- [Use Subgraphs](https://docs.langchain.com/oss/python/langgraph/use-subgraphs): Compose graphs using subgraphs.
|
||||
- [Observability](https://docs.langchain.com/oss/python/langgraph/observability): Add tracing and debugging to your graphs.
|
||||
- [Common Errors](https://docs.langchain.com/oss/python/langgraph/common-errors): Troubleshoot common LangGraph errors.
|
||||
|
||||
## Tutorials
|
||||
|
||||
- [Agentic RAG](https://docs.langchain.com/oss/python/langgraph/agentic-rag): Build an agentic RAG system with LangGraph.
|
||||
- [SQL Agent](https://docs.langchain.com/oss/python/langgraph/sql-agent): Create a SQL agent with LangGraph.
|
||||
|
||||
## Reference
|
||||
|
||||
- [API Reference](https://reference.langchain.com/python/langgraph/): Complete API documentation for LangGraph.
|
||||
|
||||
## LangGraph Platform
|
||||
|
||||
For deploying LangGraph applications in production, see the [LangSmith documentation](https://docs.langchain.com/langsmith/agent-server).
|
||||
@@ -0,0 +1,296 @@
|
||||
{
|
||||
"/how-tos/stream-values": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/stream-updates": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/streaming-content": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/stream-multiple": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/streaming-tokens-without-langchain": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/streaming-from-final-node": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/streaming-events-from-within-tools-without-langchain": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/state-reducers": "https://docs.langchain.com/oss/python/langgraph/graph-api#define-and-update-state",
|
||||
"/how-tos/sequence": "https://docs.langchain.com/oss/python/langgraph/graph-api#create-a-sequence-of-steps",
|
||||
"/how-tos/branching": "https://docs.langchain.com/oss/python/langgraph/graph-api#create-branches",
|
||||
"/how-tos/recursion-limit": "https://docs.langchain.com/oss/python/langgraph/graph-api#create-and-control-loops",
|
||||
"/how-tos/visualization": "https://docs.langchain.com/oss/python/langgraph/graph-api#visualize-your-graph",
|
||||
"/how-tos/input_output_schema": "https://docs.langchain.com/oss/python/langgraph/graph-api#define-input-and-output-schemas",
|
||||
"/how-tos/pass_private_state": "https://docs.langchain.com/oss/python/langgraph/graph-api#pass-private-state-between-nodes",
|
||||
"/how-tos/state-model": "https://docs.langchain.com/oss/python/langgraph/graph-api#use-pydantic-models-for-graph-state",
|
||||
"/how-tos/map-reduce": "https://docs.langchain.com/oss/python/langgraph/graph-api#map-reduce-and-the-send-api",
|
||||
"/how-tos/command": "https://docs.langchain.com/oss/python/langgraph/graph-api#combine-control-flow-and-state-updates-with-command",
|
||||
"/how-tos/configuration": "https://docs.langchain.com/oss/python/langgraph/graph-api#add-runtime-configuration",
|
||||
"/how-tos/node-retries": "https://docs.langchain.com/oss/python/langgraph/graph-api#add-retry-policies",
|
||||
"/how-tos/return-when-recursion-limit-hits": "https://docs.langchain.com/oss/python/langgraph/graph-api#impose-a-recursion-limit",
|
||||
"/how-tos/async": "https://docs.langchain.com/oss/python/langgraph/graph-api#async",
|
||||
"/how-tos/memory/manage-conversation-history": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/memory/delete-messages": "https://docs.langchain.com/oss/python/langgraph/add-memory#delete-messages",
|
||||
"/how-tos/memory/add-summary-conversation-history": "https://docs.langchain.com/oss/python/langgraph/add-memory#summarize-messages",
|
||||
"/how-tos/memory": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/agents/memory": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/subgraph-transform-state": "https://docs.langchain.com/oss/python/langgraph/use-subgraphs#different-state-schemas",
|
||||
"/how-tos/subgraphs-manage-state": "https://docs.langchain.com/oss/python/langgraph/use-subgraphs#add-persistence",
|
||||
"/how-tos/persistence_postgres": "https://docs.langchain.com/oss/python/langgraph/add-memory#use-in-production",
|
||||
"/how-tos/persistence_mongodb": "https://docs.langchain.com/oss/python/langgraph/add-memory#use-in-production",
|
||||
"/how-tos/persistence_redis": "https://docs.langchain.com/oss/python/langgraph/add-memory#use-in-production",
|
||||
"/how-tos/subgraph-persistence": "https://docs.langchain.com/oss/python/langgraph/add-memory#use-with-subgraphs",
|
||||
"/how-tos/cross-thread-persistence": "https://docs.langchain.com/oss/python/langgraph/add-memory#add-long-term-memory",
|
||||
"/cloud/how-tos/copy_threads": "https://docs.langchain.com/langsmith/use-threads",
|
||||
"/cloud/how-tos/check-thread-status": "https://docs.langchain.com/langsmith/use-threads",
|
||||
"/cloud/concepts/threads": "https://docs.langchain.com/oss/python/langgraph/persistence#threads",
|
||||
"/how-tos/persistence": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/tool-calling-errors": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/how-tos/pass-config-to-tools": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/how-tos/pass-run-time-values-to-tools": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/how-tos/update-state-from-tools": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/agents/tools": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/how-tos/agent-handoffs": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/multi-agent-network": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/multi-agent-multi-turn-convo": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/cloud/index": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/cloud/how-tos/index": "https://docs.langchain.com/langsmith/home",
|
||||
"/cloud/concepts/api": "https://docs.langchain.com/langsmith/agent-server",
|
||||
"/cloud/concepts/cloud": "https://docs.langchain.com/langsmith/cloud",
|
||||
"/cloud/faq/studio": "https://docs.langchain.com/langsmith/studio",
|
||||
"/cloud/how-tos/human_in_the_loop_edit_state": "https://docs.langchain.com/langsmith/add-human-in-the-loop",
|
||||
"/cloud/how-tos/human_in_the_loop_user_input": "https://docs.langchain.com/langsmith/add-human-in-the-loop",
|
||||
"/concepts/platform_architecture": "https://docs.langchain.com/langsmith/cloud#architecture",
|
||||
"/cloud/how-tos/stream_values": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/how-tos/stream_updates": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/how-tos/stream_messages": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/how-tos/stream_events": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/how-tos/stream_debug": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/how-tos/stream_multiple": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/concepts/streaming": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/agents/streaming": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/create-react-agent": "https://docs.langchain.com/oss/python/langchain/agents#basic-configuration",
|
||||
"/how-tos/create-react-agent-memory": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/create-react-agent-system-prompt": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/create-react-agent-structured-output": "https://docs.langchain.com/oss/python/langchain/agents#structured-output",
|
||||
"/prebuilt": "https://docs.langchain.com/oss/python/langchain/agents",
|
||||
"/reference/prebuilt": "https://reference.langchain.com/python/langgraph/agents/",
|
||||
"/concepts/high_level": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/concepts/index": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/concepts/v0-human-in-the-loop": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/how-tos/index": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/introduction": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/agents/deployment": "https://docs.langchain.com/oss/python/langgraph/local-server",
|
||||
"/how-tos/deploy-self-hosted": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/concepts/self_hosted": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/tutorials/deployment": "https://docs.langchain.com/langsmith/deployments",
|
||||
"/cloud/how-tos/assistant_versioning": "https://docs.langchain.com/langsmith/configuration-cloud",
|
||||
"/cloud/concepts/runs": "https://docs.langchain.com/langsmith/assistants#execution",
|
||||
"/how-tos/wait-user-input-functional": "https://docs.langchain.com/oss/python/langgraph/functional-api",
|
||||
"/how-tos/review-tool-calls-functional": "https://docs.langchain.com/oss/python/langgraph/functional-api",
|
||||
"/how-tos/create-react-agent-hitl": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/agents/human-in-the-loop": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/how-tos/human_in_the_loop/dynamic_breakpoints": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/concepts/breakpoints": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/how-tos/human_in_the_loop/breakpoints": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/cloud/how-tos/human_in_the_loop_breakpoint": "https://docs.langchain.com/langsmith/add-human-in-the-loop",
|
||||
"/how-tos/human_in_the_loop/edit-graph-state": "https://docs.langchain.com/oss/python/langgraph/use-time-travel",
|
||||
"/examples/index": "https://docs.langchain.com/oss/python/langgraph/case-studies",
|
||||
"/guides/index": "https://docs.langchain.com/oss/python/langchain/overview",
|
||||
"/tutorials/index": "https://docs.langchain.com/oss/python/learn",
|
||||
"/llms-txt-overview": "https://docs.langchain.com/llms.txt",
|
||||
"/tutorials/rag/langgraph_adaptive_rag": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/multi_agent/multi-agent-collaboration": "https://docs.langchain.com/oss/python/langchain/multi-agent",
|
||||
"/how-tos/create-react-agent-manage-message-history": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/many-tools": "https://docs.langchain.com/oss/python/langchain/tools",
|
||||
"/tutorials/customer-support/customer-support": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/how-tos/react-agent-structured-output": "https://docs.langchain.com/oss/python/langchain/agents#structured-output",
|
||||
"/tutorials/code_assistant/langgraph_code_assistant": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/multi_agent/hierarchical_agent_teams": "https://docs.langchain.com/oss/python/langchain/supervisor",
|
||||
"/tutorials/auth/getting_started": "https://docs.langchain.com/langsmith/auth",
|
||||
"/tutorials/auth/resource_auth": "https://docs.langchain.com/langsmith/resource-auth",
|
||||
"/tutorials/auth/add_auth_server": "https://docs.langchain.com/langsmith/add-auth-server",
|
||||
"/how-tos/use-remote-graph": "https://docs.langchain.com/langsmith/use-remote-graph",
|
||||
"/how-tos/autogen-integration": "https://docs.langchain.com/langsmith/autogen-integration",
|
||||
"/how-tos/human_in_the_loop/wait-user-input": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/cloud/how-tos/use_stream_react": "https://docs.langchain.com/langsmith/use-stream-react",
|
||||
"/cloud/how-tos/generative_ui_react": "https://docs.langchain.com/langsmith/generative-ui-react",
|
||||
"/concepts/langgraph_platform": "https://docs.langchain.com/langsmith/home",
|
||||
"/concepts/langgraph_components": "https://docs.langchain.com/langsmith/components",
|
||||
"/concepts/langgraph_server": "https://docs.langchain.com/langsmith/agent-server",
|
||||
"/concepts/langgraph_data_plane": "https://docs.langchain.com/langsmith/data-plane",
|
||||
"/concepts/langgraph_control_plane": "https://docs.langchain.com/langsmith/control-plane",
|
||||
"/concepts/langgraph_cli": "https://docs.langchain.com/langsmith/cli",
|
||||
"/concepts/langgraph_studio": "https://docs.langchain.com/langsmith/studio",
|
||||
"/cloud/how-tos/studio/quick_start": "https://docs.langchain.com/langsmith/quick-start-studio",
|
||||
"/cloud/how-tos/invoke_studio": "https://docs.langchain.com/langsmith/use-studio",
|
||||
"/cloud/how-tos/studio/manage_assistants": "https://docs.langchain.com/langsmith/use-studio",
|
||||
"/cloud/how-tos/threads_studio": "https://docs.langchain.com/langsmith/use-threads",
|
||||
"/cloud/how-tos/iterate_graph_studio": "https://docs.langchain.com/langsmith/use-studio",
|
||||
"/cloud/how-tos/studio/run_evals": "https://docs.langchain.com/langsmith/observability",
|
||||
"/cloud/how-tos/clone_traces_studio": "https://docs.langchain.com/langsmith/observability",
|
||||
"/cloud/how-tos/datasets_studio": "https://docs.langchain.com/langsmith/use-studio",
|
||||
"/concepts/sdk": "https://docs.langchain.com/langsmith/sdk",
|
||||
"/concepts/plans": "https://docs.langchain.com/langsmith/home",
|
||||
"/concepts/application_structure": "https://docs.langchain.com/langsmith/application-structure",
|
||||
"/concepts/scalability_and_resilience": "https://docs.langchain.com/langsmith/scalability-and-resilience",
|
||||
"/concepts/auth": "https://docs.langchain.com/langsmith/auth",
|
||||
"/how-tos/auth/custom_auth": "https://docs.langchain.com/langsmith/custom-auth",
|
||||
"/how-tos/auth/openapi_security": "https://docs.langchain.com/langsmith/openapi-security",
|
||||
"/concepts/assistants": "https://docs.langchain.com/langsmith/assistants",
|
||||
"/cloud/how-tos/configuration_cloud": "https://docs.langchain.com/langsmith/configuration-cloud",
|
||||
"/cloud/how-tos/use_threads": "https://docs.langchain.com/langsmith/use-threads",
|
||||
"/cloud/how-tos/background_run": "https://docs.langchain.com/langsmith/background-run",
|
||||
"/cloud/how-tos/same-thread": "https://docs.langchain.com/langsmith/same-thread",
|
||||
"/cloud/how-tos/stateless_runs": "https://docs.langchain.com/langsmith/stateless-runs",
|
||||
"/cloud/how-tos/configurable_headers": "https://docs.langchain.com/langsmith/configurable-headers",
|
||||
"/concepts/double_texting": "https://docs.langchain.com/langsmith/double-texting",
|
||||
"/cloud/how-tos/interrupt_concurrent": "https://docs.langchain.com/langsmith/interrupt-concurrent",
|
||||
"/cloud/how-tos/rollback_concurrent": "https://docs.langchain.com/langsmith/rollback-concurrent",
|
||||
"/cloud/how-tos/reject_concurrent": "https://docs.langchain.com/langsmith/reject-concurrent",
|
||||
"/cloud/how-tos/enqueue_concurrent": "https://docs.langchain.com/langsmith/enqueue-concurrent",
|
||||
"/cloud/concepts/webhooks": "https://docs.langchain.com/langsmith/use-webhooks",
|
||||
"/cloud/how-tos/webhooks": "https://docs.langchain.com/langsmith/use-webhooks",
|
||||
"/cloud/concepts/cron_jobs": "https://docs.langchain.com/langsmith/cron-jobs",
|
||||
"/cloud/how-tos/cron_jobs": "https://docs.langchain.com/langsmith/cron-jobs",
|
||||
"/how-tos/http/custom_lifespan": "https://docs.langchain.com/langsmith/custom-lifespan",
|
||||
"/how-tos/http/custom_middleware": "https://docs.langchain.com/langsmith/custom-middleware",
|
||||
"/how-tos/http/custom_routes": "https://docs.langchain.com/langsmith/custom-routes",
|
||||
"/cloud/concepts/data_storage_and_privacy": "https://docs.langchain.com/langsmith/data-storage-and-privacy",
|
||||
"/cloud/deployment/semantic_search": "https://docs.langchain.com/langsmith/semantic-search",
|
||||
"/how-tos/ttl/configure_ttl": "https://docs.langchain.com/langsmith/configure-ttl",
|
||||
"/concepts/deployment_options": "https://docs.langchain.com/langsmith/deployments",
|
||||
"/cloud/quick_start": "https://docs.langchain.com/langsmith/deployment-quickstart",
|
||||
"/cloud/deployment/setup": "https://docs.langchain.com/langsmith/setup-app-requirements-txt",
|
||||
"/cloud/deployment/setup_pyproject": "https://docs.langchain.com/langsmith/setup-pyproject",
|
||||
"/cloud/deployment/setup_javascript": "https://docs.langchain.com/langsmith/setup-javascript",
|
||||
"/cloud/deployment/custom_docker": "https://docs.langchain.com/langsmith/custom-docker",
|
||||
"/cloud/deployment/graph_rebuild": "https://docs.langchain.com/langsmith/graph-rebuild",
|
||||
"/concepts/langgraph_cloud": "https://docs.langchain.com/langsmith/cloud",
|
||||
"/concepts/langgraph_self_hosted_data_plane": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/concepts/langgraph_self_hosted_control_plane": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/concepts/langgraph_standalone_container": "https://docs.langchain.com/langsmith/docker",
|
||||
"/cloud/deployment/cloud": "https://docs.langchain.com/langsmith/cloud",
|
||||
"/cloud/deployment/self_hosted_data_plane": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/cloud/deployment/self_hosted_control_plane": "https://docs.langchain.com/langsmith/platform-setup",
|
||||
"/cloud/deployment/standalone_container": "https://docs.langchain.com/langsmith/docker",
|
||||
"/concepts/server-mcp": "https://docs.langchain.com/langsmith/server-mcp",
|
||||
"/cloud/how-tos/human_in_the_loop_time_travel": "https://docs.langchain.com/langsmith/human-in-the-loop-time-travel",
|
||||
"/cloud/how-tos/add-human-in-the-loop": "https://docs.langchain.com/langsmith/add-human-in-the-loop",
|
||||
"/cloud/deployment/egress": "https://docs.langchain.com/langsmith/env-var",
|
||||
"/cloud/how-tos/streaming": "https://docs.langchain.com/langsmith/streaming",
|
||||
"/cloud/reference/api/api_ref": "https://docs.langchain.com/langsmith/server-api-ref",
|
||||
"/cloud/reference/langgraph_server_changelog": "https://docs.langchain.com/langsmith/agent-server-changelog",
|
||||
"/cloud/reference/api/api_ref_control_plane": "https://docs.langchain.com/langsmith/api-ref-control-plane",
|
||||
"/cloud/reference/cli": "https://docs.langchain.com/langsmith/cli",
|
||||
"/cloud/reference/env_var": "https://docs.langchain.com/langsmith/env-var",
|
||||
"/troubleshooting/studio": "https://docs.langchain.com/langsmith/troubleshooting-studio",
|
||||
"/index": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/agents/agents": "https://docs.langchain.com/oss/python/langchain/agents",
|
||||
"/concepts/why-langgraph": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/get-started/1-build-basic-chatbot": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/get-started/2-add-tools": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/get-started/3-add-memory": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/get-started/4-human-in-the-loop": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/get-started/5-customize-state": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/get-started/6-time-travel": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/tutorials/langsmith/local-server": "https://docs.langchain.com/oss/python/langgraph/local-server",
|
||||
"/tutorials/workflows": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/tutorials/plan-and-execute/plan-and-execute": "https://docs.langchain.com/oss/python/langchain/middleware/built-in#to-do-list",
|
||||
"/tutorials/langgraph-platform/local-server/local-server": "https://docs.langchain.com/langsmith/local-server",
|
||||
"/concepts/agentic_concepts": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/agents/overview": "https://docs.langchain.com/oss/python/langchain/agents",
|
||||
"/agents/run_agents": "https://docs.langchain.com/oss/python/langgraph/quickstart",
|
||||
"/concepts/low_level": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/graph-api": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/react-agent-from-scratch": "https://docs.langchain.com/oss/python/langchain/quickstart",
|
||||
"/concepts/functional_api": "https://docs.langchain.com/oss/python/langgraph/functional-api",
|
||||
"/how-tos/use-functional-api": "https://docs.langchain.com/oss/python/langgraph/functional-api",
|
||||
"/concepts/pregel": "https://docs.langchain.com/oss/python/langgraph/pregel",
|
||||
"/concepts/streaming": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/streaming": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/concepts/persistence": "https://docs.langchain.com/oss/python/langgraph/persistence",
|
||||
"/concepts/durable_execution": "https://docs.langchain.com/oss/python/langgraph/durable-execution",
|
||||
"/concepts/memory": "https://docs.langchain.com/oss/python/langgraph/memory",
|
||||
"/how-tos/memory/add-memory": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/agents/context": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/agents/models": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/concepts/tools": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/how-tos/tool-calling": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/concepts/human_in_the_loop": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/how-tos/human_in_the_loop/add-human-in-the-loop": "https://docs.langchain.com/oss/python/langgraph/interrupts",
|
||||
"/concepts/time-travel": "https://docs.langchain.com/oss/python/langgraph/persistence",
|
||||
"/how-tos/human_in_the_loop/time-travel": "https://docs.langchain.com/oss/python/langgraph/use-time-travel",
|
||||
"/concepts/subgraphs": "https://docs.langchain.com/oss/python/langgraph/use-subgraphs",
|
||||
"/how-tos/subgraph": "https://docs.langchain.com/oss/python/langgraph/use-subgraphs",
|
||||
"/concepts/multi_agent": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/agents/multi-agent": "https://docs.langchain.com/oss/python/langchain/multi-agent",
|
||||
"/how-tos/multi_agent": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/concepts/mcp": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/agents/mcp": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/concepts/tracing": "https://docs.langchain.com/oss/python/langgraph/observability",
|
||||
"/how-tos/enable-tracing": "https://docs.langchain.com/oss/python/langgraph/observability",
|
||||
"/agents/evals": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/concepts/template_applications": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/rag/langgraph_agentic_rag": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/multi_agent/agent_supervisor": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/tutorials/sql/sql-agent": "https://docs.langchain.com/oss/python/langgraph/sql-agent",
|
||||
"/agents/ui": "https://docs.langchain.com/oss/python/langgraph/ui",
|
||||
"/how-tos/run-id-langsmith": "https://docs.langchain.com/oss/python/langgraph/observability",
|
||||
"/troubleshooting/errors/index": "https://docs.langchain.com/oss/python/langgraph/common-errors",
|
||||
"/troubleshooting/errors/INVALID_CHAT_HISTORY": "https://docs.langchain.com/oss/python/langgraph/INVALID_CHAT_HISTORY",
|
||||
"/troubleshooting/errors/INVALID_LICENSE": "https://docs.langchain.com/oss/python/langgraph/common-errors",
|
||||
"/adopters": "https://docs.langchain.com/oss/python/langgraph/case-studies",
|
||||
"/concepts/faq": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/agents/prebuilt": "https://docs.langchain.com/oss/python/langchain/agents",
|
||||
"/reference/index": "https://reference.langchain.com/python/langgraph/",
|
||||
"/reference/graphs": "https://reference.langchain.com/python/langgraph/graphs/",
|
||||
"/reference/func": "https://reference.langchain.com/python/langgraph/func/",
|
||||
"/reference/pregel": "https://reference.langchain.com/python/langgraph/pregel/",
|
||||
"/reference/checkpoints": "https://reference.langchain.com/python/langgraph/checkpoints/",
|
||||
"/reference/store": "https://reference.langchain.com/python/langgraph/store/",
|
||||
"/reference/cache": "https://reference.langchain.com/python/langgraph/cache/",
|
||||
"/reference/types": "https://reference.langchain.com/python/langgraph/types/",
|
||||
"/reference/runtime": "https://reference.langchain.com/python/langgraph/runtime/",
|
||||
"/reference/config": "https://reference.langchain.com/python/langgraph/config/",
|
||||
"/reference/errors": "https://reference.langchain.com/python/langgraph/errors/",
|
||||
"/reference/constants": "https://reference.langchain.com/python/langgraph/constants/",
|
||||
"/reference/channels": "https://reference.langchain.com/python/langgraph/channels/",
|
||||
"/reference/agents": "https://reference.langchain.com/python/langgraph/agents/",
|
||||
"/reference/supervisor": "https://reference.langchain.com/python/langgraph/supervisor/",
|
||||
"/reference/swarm": "https://reference.langchain.com/python/langgraph/swarm/",
|
||||
"/reference/mcp": "https://reference.langchain.com/python/langgraph/mcp/",
|
||||
"/cloud/reference/sdk/python_sdk_ref": "https://reference.langchain.com/python/langsmith/deployment/sdk/",
|
||||
"/reference/remote_graph": "https://reference.langchain.com/python/langsmith/deployment/remote_graph/",
|
||||
"/additional-resources/index": "https://docs.langchain.com/oss/python/langchain/overview",
|
||||
"/cloud/reference/sdk/js_ts_sdk_ref": "https://reference.langchain.com/javascript/modules/langsmith.html",
|
||||
"/snippets/chat_model_tabs": "https://docs.langchain.com/oss/python/langchain/overview",
|
||||
"/troubleshooting/errors/GRAPH_RECURSION_LIMIT": "https://docs.langchain.com/oss/python/langgraph/GRAPH_RECURSION_LIMIT",
|
||||
"/troubleshooting/errors/INVALID_CONCURRENT_GRAPH_UPDATE": "https://docs.langchain.com/oss/python/langgraph/INVALID_CONCURRENT_GRAPH_UPDATE",
|
||||
"/troubleshooting/errors/INVALID_GRAPH_NODE_RETURN_VALUE": "https://docs.langchain.com/oss/python/langgraph/INVALID_GRAPH_NODE_RETURN_VALUE",
|
||||
"/troubleshooting/errors/MULTIPLE_SUBGRAPHS": "https://docs.langchain.com/oss/python/langgraph/MULTIPLE_SUBGRAPHS",
|
||||
"/tutorials/rag/langgraph_self_rag": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/additional-resources": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/examples": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/guides": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/how-tos/autogen-integration-functional": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/how-tos/cross-thread-persistence-functional": "https://docs.langchain.com/oss/python/langgraph/add-memory#add-long-term-memory",
|
||||
"/how-tos/disable-streaming": "https://docs.langchain.com/oss/python/langgraph/streaming",
|
||||
"/how-tos/memory/semantic-search": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/multi-agent-multi-turn-convo-functional": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/multi-agent-network-functional": "https://docs.langchain.com/oss/python/langgraph/graph-api",
|
||||
"/how-tos/persistence-functional": "https://docs.langchain.com/oss/python/langgraph/add-memory",
|
||||
"/how-tos/react-agent-from-scratch-functional": "https://docs.langchain.com/oss/python/langgraph/workflows-agents",
|
||||
"/reference": "https://reference.langchain.com/python/langgraph/",
|
||||
"/troubleshooting/errors": "https://docs.langchain.com/oss/python/langgraph/common-errors",
|
||||
"/tutorials/chatbot-simulation-evaluation/agent-simulation-evaluation": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/chatbot-simulation-evaluation/langsmith-agent-simulation-evaluation": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/chatbots/information-gather-prompting": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/extraction/retries": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/langgraph-platform/local-server": "https://docs.langchain.com/langsmith/agent-server",
|
||||
"/tutorials/lats/lats": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/llm-compiler/LLMCompiler": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/rag/langgraph_adaptive_rag_local": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/rag/langgraph_crag": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/rag/langgraph_crag_local": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/rag/langgraph_self_rag_local": "https://docs.langchain.com/oss/python/langgraph/agentic-rag",
|
||||
"/tutorials/reflection/reflection": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/reflexion/reflexion": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/rewoo/rewoo": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/self-discover/self-discover": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/tnt-llm/tnt-llm": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/tot/tot": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/usaco/usaco": "https://docs.langchain.com/oss/python/langgraph/overview",
|
||||
"/tutorials/web-navigation/web_voyager": "https://docs.langchain.com/oss/python/langgraph/overview"
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# LangGraph examples
|
||||
|
||||
This directory is retained purely for archival purposes and is no longer updated.
|
||||
|
||||
## 🤔 What is this?
|
||||
|
||||
The examples previously found here have been moved to the consolidated LangChain documentation. This directory remains available for historical reference, but new examples and usage guidance are published in the docs.
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
For up-to-date LangGraph examples, tutorials, and guides, see the [LangGraph Docs](https://docs.langchain.com/oss/python/langgraph/overview). Get started with the [LangGraph Quickstart](https://docs.langchain.com/oss/python/langgraph/quickstart).
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "10251c1c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c5fc63df",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.1"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a4351a24",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/chatbot-simulation-evaluation/langsmith-agent-simulation-evaluation.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4cc9af1e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import functools
|
||||
from typing import Annotated, Any, Callable, Dict, List, Optional, Union
|
||||
|
||||
from langchain_community.adapters.openai import convert_message_to_dict
|
||||
from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, HumanMessage
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from langchain_core.runnables import Runnable, RunnableLambda
|
||||
from langchain_core.runnables import chain as as_runnable
|
||||
from langchain_openai import ChatOpenAI
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from langgraph.graph import END, StateGraph, START
|
||||
|
||||
|
||||
def langchain_to_openai_messages(messages: List[BaseMessage]):
|
||||
"""
|
||||
Convert a list of langchain base messages to a list of openai messages.
|
||||
|
||||
Parameters:
|
||||
messages (List[BaseMessage]): A list of langchain base messages.
|
||||
|
||||
Returns:
|
||||
List[dict]: A list of openai messages.
|
||||
"""
|
||||
|
||||
return [
|
||||
convert_message_to_dict(m) if isinstance(m, BaseMessage) else m
|
||||
for m in messages
|
||||
]
|
||||
|
||||
|
||||
def create_simulated_user(
|
||||
system_prompt: str, llm: Runnable | None = None
|
||||
) -> Runnable[Dict, AIMessage]:
|
||||
"""
|
||||
Creates a simulated user for chatbot simulation.
|
||||
|
||||
Args:
|
||||
system_prompt (str): The system prompt to be used by the simulated user.
|
||||
llm (Runnable | None, optional): The language model to be used for the simulation.
|
||||
Defaults to gpt-3.5-turbo.
|
||||
|
||||
Returns:
|
||||
Runnable[Dict, AIMessage]: The simulated user for chatbot simulation.
|
||||
"""
|
||||
return ChatPromptTemplate.from_messages(
|
||||
[
|
||||
("system", system_prompt),
|
||||
MessagesPlaceholder(variable_name="messages"),
|
||||
]
|
||||
) | (llm or ChatOpenAI(model="gpt-3.5-turbo")).with_config(
|
||||
run_name="simulated_user"
|
||||
)
|
||||
|
||||
|
||||
Messages = Union[list[AnyMessage], AnyMessage]
|
||||
|
||||
|
||||
def add_messages(left: Messages, right: Messages) -> Messages:
|
||||
if not isinstance(left, list):
|
||||
left = [left]
|
||||
if not isinstance(right, list):
|
||||
right = [right]
|
||||
return left + right
|
||||
|
||||
|
||||
class SimulationState(TypedDict):
|
||||
"""
|
||||
Represents the state of a simulation.
|
||||
|
||||
Attributes:
|
||||
messages (List[AnyMessage]): A list of messages in the simulation.
|
||||
inputs (Optional[dict[str, Any]]): Optional inputs for the simulation.
|
||||
"""
|
||||
|
||||
messages: Annotated[List[AnyMessage], add_messages]
|
||||
inputs: Optional[dict[str, Any]]
|
||||
|
||||
|
||||
def create_chat_simulator(
|
||||
assistant: (
|
||||
Callable[[List[AnyMessage]], str | AIMessage]
|
||||
| Runnable[List[AnyMessage], str | AIMessage]
|
||||
),
|
||||
simulated_user: Runnable[Dict, AIMessage],
|
||||
*,
|
||||
input_key: str,
|
||||
max_turns: int = 6,
|
||||
should_continue: Optional[Callable[[SimulationState], str]] = None,
|
||||
):
|
||||
"""Creates a chat simulator for evaluating a chatbot.
|
||||
|
||||
Args:
|
||||
assistant: The chatbot assistant function or runnable object.
|
||||
simulated_user: The simulated user object.
|
||||
input_key: The key for the input to the chat simulation.
|
||||
max_turns: The maximum number of turns in the chat simulation. Default is 6.
|
||||
should_continue: Optional function to determine if the simulation should continue.
|
||||
If not provided, a default function will be used.
|
||||
|
||||
Returns:
|
||||
The compiled chat simulation graph.
|
||||
|
||||
"""
|
||||
graph_builder = StateGraph(SimulationState)
|
||||
graph_builder.add_node(
|
||||
"user",
|
||||
_create_simulated_user_node(simulated_user),
|
||||
)
|
||||
graph_builder.add_node(
|
||||
"assistant", _fetch_messages | assistant | _coerce_to_message
|
||||
)
|
||||
graph_builder.add_edge("assistant", "user")
|
||||
graph_builder.add_conditional_edges(
|
||||
"user",
|
||||
should_continue or functools.partial(_should_continue, max_turns=max_turns),
|
||||
)
|
||||
# If your dataset has a 'leading question/input', then we route first to the assistant, otherwise, we let the user take the lead.
|
||||
graph_builder.add_edge(START, "assistant" if input_key is not None else "user")
|
||||
|
||||
return (
|
||||
RunnableLambda(_prepare_example).bind(input_key=input_key)
|
||||
| graph_builder.compile()
|
||||
)
|
||||
|
||||
|
||||
## Private methods
|
||||
|
||||
|
||||
def _prepare_example(inputs: dict[str, Any], input_key: Optional[str] = None):
|
||||
if input_key is not None:
|
||||
if input_key not in inputs:
|
||||
raise ValueError(
|
||||
f"Dataset's example input must contain the provided input key: '{input_key}'.\nFound: {list(inputs.keys())}"
|
||||
)
|
||||
messages = [HumanMessage(content=inputs[input_key])]
|
||||
return {
|
||||
"inputs": {k: v for k, v in inputs.items() if k != input_key},
|
||||
"messages": messages,
|
||||
}
|
||||
return {"inputs": inputs, "messages": []}
|
||||
|
||||
|
||||
def _invoke_simulated_user(state: SimulationState, simulated_user: Runnable):
|
||||
"""Invoke the simulated user node."""
|
||||
runnable = (
|
||||
simulated_user
|
||||
if isinstance(simulated_user, Runnable)
|
||||
else RunnableLambda(simulated_user)
|
||||
)
|
||||
inputs = state.get("inputs", {})
|
||||
inputs["messages"] = state["messages"]
|
||||
return runnable.invoke(inputs)
|
||||
|
||||
|
||||
def _swap_roles(state: SimulationState):
|
||||
new_messages = []
|
||||
for m in state["messages"]:
|
||||
if isinstance(m, AIMessage):
|
||||
new_messages.append(HumanMessage(content=m.content))
|
||||
else:
|
||||
new_messages.append(AIMessage(content=m.content))
|
||||
return {
|
||||
"inputs": state.get("inputs", {}),
|
||||
"messages": new_messages,
|
||||
}
|
||||
|
||||
|
||||
@as_runnable
|
||||
def _fetch_messages(state: SimulationState):
|
||||
"""Invoke the simulated user node."""
|
||||
return state["messages"]
|
||||
|
||||
|
||||
def _convert_to_human_message(message: BaseMessage):
|
||||
return {"messages": [HumanMessage(content=message.content)]}
|
||||
|
||||
|
||||
def _create_simulated_user_node(simulated_user: Runnable):
|
||||
"""Simulated user accepts a {"messages": [...]} argument and returns a single message."""
|
||||
return (
|
||||
_swap_roles
|
||||
| RunnableLambda(_invoke_simulated_user).bind(simulated_user=simulated_user)
|
||||
| _convert_to_human_message
|
||||
)
|
||||
|
||||
|
||||
def _coerce_to_message(assistant_output: str | BaseMessage):
|
||||
if isinstance(assistant_output, str):
|
||||
return {"messages": [AIMessage(content=assistant_output)]}
|
||||
else:
|
||||
return {"messages": [assistant_output]}
|
||||
|
||||
|
||||
def _should_continue(state: SimulationState, max_turns: int = 6):
|
||||
messages = state["messages"]
|
||||
# TODO support other stop criteria
|
||||
if len(messages) > max_turns:
|
||||
return END
|
||||
elif messages[-1].content.strip() == "FINISHED":
|
||||
return END
|
||||
else:
|
||||
return "assistant"
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a9014f94",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/chatbots/information-gather-prompting.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f47ce992",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1f2f13ca",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/code_assistant/langgraph_code_assistant.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5e4c9bfe",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a8232bc9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/customer-support/customer-support.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "63da8671",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
# delta-channel-dump
|
||||
|
||||
Recover messages (and other channels) from a Postgres-backed LangGraph thread
|
||||
written by **langgraph >= 1.2** (DeltaChannel format) — including **LangGraph
|
||||
Server / langgraph-api** deployments on the Postgres runtime, **deepagents
|
||||
0.6.x**, or any OSS app using `PostgresSaver` — before rolling back to an older
|
||||
runtime such as **deepagents 0.5.x / langgraph < 1.2**.
|
||||
|
||||
langgraph-api uses the same `checkpoints` / `checkpoint_blobs` / `checkpoint_writes`
|
||||
schema as OSS `checkpoint-postgres`; this script reads those tables directly.
|
||||
|
||||
On the older runtime, `add_messages` does not understand the `EXT_DELTA_SNAPSHOT`
|
||||
msgpack ext code and silently returns an empty list for affected channels. This
|
||||
tool reads the raw checkpoint blobs from Postgres and emits JSON you can inspect
|
||||
and re-apply via `update_state` (LangGraph Server SDK) or `graph.update_state`
|
||||
(OSS).
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install "psycopg[binary]" ormsgpack
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
export DATABASE_URI=postgres://user:pass@host:5432/dbname
|
||||
python3 dump.py \
|
||||
--thread-id <uuid> \
|
||||
--channel messages \
|
||||
[--channel files ...] \
|
||||
[--checkpoint-id <uuid>] \
|
||||
[--checkpoint-ns ""] \
|
||||
--output recovery.json
|
||||
```
|
||||
|
||||
- `--thread-id` (required): thread UUID
|
||||
- `--channel` (required, repeatable): channel names to recover
|
||||
- `--checkpoint-id` (optional): target checkpoint; defaults to latest
|
||||
- `--checkpoint-ns` (optional): namespace; defaults to `""`
|
||||
- `--database-uri` (optional): Postgres URI; defaults to `DATABASE_URI` env var
|
||||
- `--output` (optional): output file; defaults to stdout
|
||||
|
||||
## Output
|
||||
|
||||
```json
|
||||
{
|
||||
"thread_id": "...",
|
||||
"checkpoint_ns": "",
|
||||
"target_checkpoint_id": "...",
|
||||
"parent_checkpoint_id": "...",
|
||||
"channels": {
|
||||
"messages": {
|
||||
"delta_kind": "snapshot",
|
||||
"seed_checkpoint_id": "...",
|
||||
"seed_version": "...",
|
||||
"seed": [{ "type": "ai", "content": "...", "id": "ai-0" }],
|
||||
"writes": [
|
||||
{
|
||||
"checkpoint_id": "...",
|
||||
"task_id": "...",
|
||||
"idx": 0,
|
||||
"value": [{ "type": "ai", "content": "...", "id": "ai-10" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`delta_kind` is one of:
|
||||
|
||||
- `snapshot` — DeltaChannel snapshot blob (`channel_values[ch] == true`)
|
||||
- `legacy_plain` — pre-DeltaChannel inline or blob value
|
||||
- `no_seed` — walked to root without finding a populated ancestor
|
||||
|
||||
`writes` are ordered oldest-to-newest (the order a reducer would replay them).
|
||||
|
||||
## Reducing back to a single list
|
||||
|
||||
For deepagents-style messages, combine seed and writes, then deduplicate:
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
data = json.load(open("recovery.json"))
|
||||
ch = data["channels"]["messages"]
|
||||
messages = list(ch["seed"] or [])
|
||||
for w in ch["writes"]:
|
||||
messages.extend(w["value"] or [])
|
||||
|
||||
# Dedup by id, keep last; drop RemoveMessage tombstones
|
||||
by_id = {}
|
||||
for m in messages:
|
||||
if isinstance(m, dict) and m.get("type") == "remove":
|
||||
by_id.pop(m.get("id"), None)
|
||||
elif isinstance(m, dict) and m.get("id"):
|
||||
by_id[m["id"]] = m
|
||||
else:
|
||||
by_id[id(m)] = m
|
||||
reduced = list(by_id.values())
|
||||
```
|
||||
|
||||
This approximates `_messages_delta_reducer` semantics; adjust for your graph.
|
||||
|
||||
## Re-applying
|
||||
|
||||
```python
|
||||
from langgraph_sdk import get_client
|
||||
|
||||
client = get_client(url="http://localhost:8123")
|
||||
await client.threads.update_state(
|
||||
thread_id,
|
||||
values={"messages": reduced},
|
||||
)
|
||||
```
|
||||
|
||||
Review the recovered JSON before calling `update_state`. This tool is
|
||||
read-only and intentionally does not mutate the database.
|
||||
|
||||
## Scope / non-goals (v1)
|
||||
|
||||
- **Postgres only** — OSS `PostgresSaver` or langgraph-api Postgres runtime; not
|
||||
inmem, gRPC core, Mongo, or Redis checkpointer backends
|
||||
- **No AES decryption** (`LANGGRAPH_AES_KEY`) or custom encryption
|
||||
- **No reducer** — raw seed + writes only
|
||||
- **No automatic `update_state`** — operator applies manually
|
||||
|
||||
## Copying
|
||||
|
||||
`dump.py` is self-contained. Copy it anywhere; only `psycopg[binary]` and
|
||||
`ormsgpack` are required at runtime. No langgraph imports.
|
||||
Executable
+469
@@ -0,0 +1,469 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recover delta-channel state from a Postgres-backed LangGraph thread.
|
||||
|
||||
Works with OSS ``PostgresSaver`` and LangGraph Server / langgraph-api on the
|
||||
Postgres runtime (same checkpoint schema). Use after rolling back from
|
||||
langgraph >= 1.2 / deepagents 0.6.x to an older runtime that does not
|
||||
understand ``EXT_DELTA_SNAPSHOT`` msgpack blobs. The script walks the checkpoint
|
||||
parent chain, decodes msgpack blobs, and emits a JSON dump of per-channel
|
||||
``seed`` plus oldest-to-newest ``writes``. Apply the recovered values manually
|
||||
via ``client.threads.update_state(...)`` (Server) or ``graph.update_state``
|
||||
(OSS).
|
||||
|
||||
Install::
|
||||
|
||||
pip install "psycopg[binary]" ormsgpack
|
||||
|
||||
Run::
|
||||
|
||||
export DATABASE_URI=postgres://...
|
||||
python3 dump.py --thread-id <uuid> --channel messages --output recovery.json
|
||||
|
||||
Scope (v1): Postgres only; no AES/custom encryption; no reducer application.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import ormsgpack
|
||||
import psycopg
|
||||
|
||||
# LangGraph msgpack EXT type codes (langgraph/checkpoint/serde/jsonplus.py).
|
||||
EXT_CONSTRUCTOR_SINGLE_ARG = 0
|
||||
EXT_CONSTRUCTOR_POS_ARGS = 1
|
||||
EXT_CONSTRUCTOR_KW_ARGS = 2
|
||||
EXT_METHOD_SINGLE_ARG = 3
|
||||
EXT_PYDANTIC_V1 = 4
|
||||
EXT_PYDANTIC_V2 = 5
|
||||
EXT_NUMPY_ARRAY = 6
|
||||
EXT_DELTA_SNAPSHOT = 7
|
||||
|
||||
_MSGPACK_OPTION = ormsgpack.OPT_NON_STR_KEYS
|
||||
|
||||
|
||||
def ext_hook(code: int, data: bytes) -> Any:
|
||||
"""Decode LangGraph msgpack EXT payloads to JSON-friendly Python values."""
|
||||
if code == EXT_DELTA_SNAPSHOT:
|
||||
inner = ormsgpack.unpackb(data, ext_hook=ext_hook, option=_MSGPACK_OPTION)
|
||||
return {"__delta_snapshot__": inner}
|
||||
if code == EXT_CONSTRUCTOR_SINGLE_ARG:
|
||||
try:
|
||||
tup = ormsgpack.unpackb(data, ext_hook=ext_hook, option=_MSGPACK_OPTION)
|
||||
if tup[0] == "uuid" and tup[1] == "UUID":
|
||||
hex_ = tup[2]
|
||||
return (
|
||||
f"{hex_[:8]}-{hex_[8:12]}-{hex_[12:16]}-"
|
||||
f"{hex_[16:20]}-{hex_[20:]}"
|
||||
)
|
||||
return tup[2]
|
||||
except Exception:
|
||||
return None
|
||||
if code == EXT_CONSTRUCTOR_POS_ARGS:
|
||||
try:
|
||||
tup = ormsgpack.unpackb(data, ext_hook=ext_hook, option=_MSGPACK_OPTION)
|
||||
if tup[0] == "langgraph.types" and tup[1] == "Send":
|
||||
args = tup[2]
|
||||
if len(args) == 2:
|
||||
return {"__send__": {"node": args[0], "arg": args[1]}}
|
||||
return {
|
||||
"__send__": {
|
||||
"node": args[0],
|
||||
"arg": args[1],
|
||||
"timeout": args[2],
|
||||
}
|
||||
}
|
||||
return tup[2]
|
||||
except Exception:
|
||||
return None
|
||||
if code in (EXT_CONSTRUCTOR_KW_ARGS, EXT_METHOD_SINGLE_ARG):
|
||||
try:
|
||||
tup = ormsgpack.unpackb(data, ext_hook=ext_hook, option=_MSGPACK_OPTION)
|
||||
return tup[2]
|
||||
except Exception:
|
||||
return None
|
||||
if code in (EXT_PYDANTIC_V1, EXT_PYDANTIC_V2):
|
||||
try:
|
||||
tup = ormsgpack.unpackb(data, ext_hook=ext_hook, option=_MSGPACK_OPTION)
|
||||
return tup[2]
|
||||
except Exception:
|
||||
return None
|
||||
if code == EXT_NUMPY_ARRAY:
|
||||
try:
|
||||
dtype_str, shape, order, buf = ormsgpack.unpackb(
|
||||
data, ext_hook=ext_hook, option=_MSGPACK_OPTION
|
||||
)
|
||||
return {
|
||||
"__numpy_array__": {
|
||||
"dtype": dtype_str,
|
||||
"shape": shape,
|
||||
"order": order,
|
||||
"data_b64": base64.b64encode(buf).decode("ascii"),
|
||||
}
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def decode_blob(blob_type: str, blob_bytes: bytes | None) -> Any:
|
||||
if blob_type in ("empty", "null") or blob_bytes is None:
|
||||
return None
|
||||
if blob_type == "msgpack":
|
||||
return ormsgpack.unpackb(
|
||||
blob_bytes, ext_hook=ext_hook, option=_MSGPACK_OPTION
|
||||
)
|
||||
if blob_type in ("bytes", "bytearray"):
|
||||
return base64.b64encode(blob_bytes).decode("ascii")
|
||||
raise RuntimeError(
|
||||
f"Unknown blob type {blob_type!r}. "
|
||||
"AES/custom-encrypted deployments are out of scope for v1."
|
||||
)
|
||||
|
||||
|
||||
def delta_unwrap(value: Any) -> Any:
|
||||
if isinstance(value, dict) and "__delta_snapshot__" in value:
|
||||
return value["__delta_snapshot__"]
|
||||
return value
|
||||
|
||||
|
||||
def json_default(obj: Any) -> Any:
|
||||
if isinstance(obj, (bytes, bytearray)):
|
||||
return base64.b64encode(bytes(obj)).decode("ascii")
|
||||
if isinstance(obj, uuid.UUID):
|
||||
return str(obj)
|
||||
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
|
||||
|
||||
|
||||
def resolve_target_checkpoint_id(
|
||||
conn: psycopg.Connection[Any],
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
checkpoint_id: str | None,
|
||||
) -> str:
|
||||
if checkpoint_id is not None:
|
||||
return checkpoint_id
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT checkpoint_id::text
|
||||
FROM checkpoints
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s
|
||||
ORDER BY checkpoint_id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(thread_id, checkpoint_ns),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise SystemExit(
|
||||
f"No checkpoints found for thread_id={thread_id!r} "
|
||||
f"checkpoint_ns={checkpoint_ns!r}"
|
||||
)
|
||||
return row[0]
|
||||
|
||||
|
||||
def _load_checkpoint(
|
||||
conn: psycopg.Connection[Any],
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
checkpoint_id: str,
|
||||
) -> tuple[dict[str, Any], str | None] | None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT checkpoint, parent_checkpoint_id::text
|
||||
FROM checkpoints
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s AND checkpoint_id = %s
|
||||
""",
|
||||
(thread_id, checkpoint_ns, checkpoint_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return row[0], row[1]
|
||||
|
||||
|
||||
def _load_seed(
|
||||
conn: psycopg.Connection[Any],
|
||||
*,
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
channel: str,
|
||||
checkpoint_id: str,
|
||||
channel_values: dict[str, Any],
|
||||
channel_versions: dict[str, str],
|
||||
) -> dict[str, Any]:
|
||||
cv = channel_values[channel]
|
||||
version = channel_versions.get(channel)
|
||||
if cv is True:
|
||||
blob_row = conn.execute(
|
||||
"""
|
||||
SELECT type, blob
|
||||
FROM checkpoint_blobs
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s
|
||||
AND channel = %s AND version = %s
|
||||
""",
|
||||
(thread_id, checkpoint_ns, channel, version),
|
||||
).fetchone()
|
||||
seed_value = None
|
||||
if blob_row is not None and blob_row[0] != "empty":
|
||||
seed_value = delta_unwrap(decode_blob(blob_row[0], blob_row[1]))
|
||||
return {
|
||||
"delta_kind": "snapshot",
|
||||
"seed_checkpoint_id": checkpoint_id,
|
||||
"seed_version": version,
|
||||
"seed": seed_value,
|
||||
}
|
||||
if isinstance(cv, (int, float, str, bool)) or cv is None:
|
||||
return {
|
||||
"delta_kind": "legacy_plain",
|
||||
"seed_checkpoint_id": checkpoint_id,
|
||||
"seed_version": version,
|
||||
"seed": cv,
|
||||
}
|
||||
blob_row = conn.execute(
|
||||
"""
|
||||
SELECT type, blob
|
||||
FROM checkpoint_blobs
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s
|
||||
AND channel = %s AND version = %s
|
||||
""",
|
||||
(thread_id, checkpoint_ns, channel, version),
|
||||
).fetchone()
|
||||
seed_value = cv if blob_row is None else decode_blob(blob_row[0], blob_row[1])
|
||||
return {
|
||||
"delta_kind": "legacy_plain",
|
||||
"seed_checkpoint_id": checkpoint_id,
|
||||
"seed_version": version,
|
||||
"seed": seed_value,
|
||||
}
|
||||
|
||||
|
||||
def _load_writes_for_checkpoint(
|
||||
conn: psycopg.Connection[Any],
|
||||
*,
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
checkpoint_id: str,
|
||||
channel: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Load writes for one checkpoint, newest-first by ``(task_id, idx)``.
|
||||
|
||||
``walk_channel`` reverses the accumulated flat list before returning;
|
||||
DESC here yields oldest-first within each checkpoint in the final output,
|
||||
matching ``PostgresSaver._build_delta_channels_writes_history``.
|
||||
"""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT task_id::text, idx, type, blob
|
||||
FROM checkpoint_writes
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s
|
||||
AND checkpoint_id = %s AND channel = %s
|
||||
ORDER BY task_id DESC, idx DESC
|
||||
""",
|
||||
(thread_id, checkpoint_ns, checkpoint_id, channel),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"checkpoint_id": checkpoint_id,
|
||||
"task_id": task_id,
|
||||
"idx": idx,
|
||||
"value": decode_blob(blob_type, blob_bytes),
|
||||
}
|
||||
for task_id, idx, blob_type, blob_bytes in rows
|
||||
]
|
||||
|
||||
|
||||
def walk_channel(
|
||||
conn: psycopg.Connection[Any],
|
||||
*,
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
start_checkpoint_id: str | None,
|
||||
channel: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Walk one channel's parent chain from target.parent backward to seed."""
|
||||
chain_writes_newest_first: list[dict[str, Any]] = []
|
||||
cur = start_checkpoint_id
|
||||
while cur is not None:
|
||||
loaded = _load_checkpoint(conn, thread_id, checkpoint_ns, cur)
|
||||
if loaded is None:
|
||||
break
|
||||
checkpoint_json, parent_id = loaded
|
||||
channel_values = checkpoint_json.get("channel_values") or {}
|
||||
channel_versions = checkpoint_json.get("channel_versions") or {}
|
||||
|
||||
chain_writes_newest_first.extend(
|
||||
_load_writes_for_checkpoint(
|
||||
conn,
|
||||
thread_id=thread_id,
|
||||
checkpoint_ns=checkpoint_ns,
|
||||
checkpoint_id=cur,
|
||||
channel=channel,
|
||||
)
|
||||
)
|
||||
|
||||
if channel in channel_values:
|
||||
seed = _load_seed(
|
||||
conn,
|
||||
thread_id=thread_id,
|
||||
checkpoint_ns=checkpoint_ns,
|
||||
channel=channel,
|
||||
checkpoint_id=cur,
|
||||
channel_values=channel_values,
|
||||
channel_versions=channel_versions,
|
||||
)
|
||||
seed["writes"] = list(reversed(chain_writes_newest_first))
|
||||
return seed
|
||||
|
||||
cur = parent_id
|
||||
|
||||
return {
|
||||
"delta_kind": "no_seed",
|
||||
"seed_checkpoint_id": None,
|
||||
"seed_version": None,
|
||||
"seed": None,
|
||||
"writes": list(reversed(chain_writes_newest_first)),
|
||||
}
|
||||
|
||||
|
||||
def walk_parent_chain(
|
||||
conn: psycopg.Connection[Any],
|
||||
*,
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
target_checkpoint_id: str,
|
||||
channels: list[str],
|
||||
) -> tuple[str | None, dict[str, dict[str, Any]]]:
|
||||
"""Walk parent chain and return per-channel seed + writes (oldest-first)."""
|
||||
parent_row = conn.execute(
|
||||
"""
|
||||
SELECT parent_checkpoint_id::text
|
||||
FROM checkpoints
|
||||
WHERE thread_id = %s AND checkpoint_ns = %s AND checkpoint_id = %s
|
||||
""",
|
||||
(thread_id, checkpoint_ns, target_checkpoint_id),
|
||||
).fetchone()
|
||||
if parent_row is None:
|
||||
raise SystemExit(
|
||||
f"Checkpoint {target_checkpoint_id!r} not found for thread {thread_id!r}"
|
||||
)
|
||||
parent_checkpoint_id = parent_row[0]
|
||||
|
||||
result = {
|
||||
ch: walk_channel(
|
||||
conn,
|
||||
thread_id=thread_id,
|
||||
checkpoint_ns=checkpoint_ns,
|
||||
start_checkpoint_id=parent_checkpoint_id,
|
||||
channel=ch,
|
||||
)
|
||||
for ch in channels
|
||||
}
|
||||
return parent_checkpoint_id, result
|
||||
|
||||
|
||||
def build_output(
|
||||
*,
|
||||
thread_id: str,
|
||||
checkpoint_ns: str,
|
||||
target_checkpoint_id: str,
|
||||
parent_checkpoint_id: str | None,
|
||||
channels: dict[str, dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"thread_id": thread_id,
|
||||
"checkpoint_ns": checkpoint_ns,
|
||||
"target_checkpoint_id": target_checkpoint_id,
|
||||
"parent_checkpoint_id": parent_checkpoint_id,
|
||||
"channels": channels,
|
||||
}
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Recover delta-channel seed + writes from Postgres checkpoint data."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--thread-id", required=True, help="Thread UUID")
|
||||
parser.add_argument(
|
||||
"--channel",
|
||||
action="append",
|
||||
required=True,
|
||||
dest="channels",
|
||||
help="Channel name (repeatable)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--checkpoint-id",
|
||||
default=None,
|
||||
help="Target checkpoint UUID (default: latest for thread)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--checkpoint-ns",
|
||||
default="",
|
||||
help='Checkpoint namespace (default: "")',
|
||||
)
|
||||
parser.add_argument(
|
||||
"--database-uri",
|
||||
default=os.environ.get("DATABASE_URI"),
|
||||
help="Postgres URI (default: DATABASE_URI env var)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default="-",
|
||||
help="Output JSON file path (default: stdout)",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
if not args.database_uri:
|
||||
print(
|
||||
"error: --database-uri or DATABASE_URI is required",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
|
||||
thread_id = str(uuid.UUID(args.thread_id))
|
||||
channels = list(dict.fromkeys(args.channels))
|
||||
|
||||
with psycopg.connect(args.database_uri) as conn:
|
||||
target_checkpoint_id = resolve_target_checkpoint_id(
|
||||
conn,
|
||||
thread_id,
|
||||
args.checkpoint_ns,
|
||||
args.checkpoint_id,
|
||||
)
|
||||
parent_checkpoint_id, channel_data = walk_parent_chain(
|
||||
conn,
|
||||
thread_id=thread_id,
|
||||
checkpoint_ns=args.checkpoint_ns,
|
||||
target_checkpoint_id=target_checkpoint_id,
|
||||
channels=channels,
|
||||
)
|
||||
|
||||
output = build_output(
|
||||
thread_id=thread_id,
|
||||
checkpoint_ns=args.checkpoint_ns,
|
||||
target_checkpoint_id=target_checkpoint_id,
|
||||
parent_checkpoint_id=parent_checkpoint_id,
|
||||
channels=channel_data,
|
||||
)
|
||||
payload = json.dumps(output, indent=2, default=json_default)
|
||||
|
||||
if args.output == "-":
|
||||
print(payload)
|
||||
else:
|
||||
with open(args.output, "w", encoding="utf-8") as f:
|
||||
f.write(payload)
|
||||
f.write("\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8dbdba5b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/extraction/retries.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1d444b7f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3ecab357",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/human_in_the_loop/wait-user-input.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3f2866bd",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "09038b53",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/lats/lats.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b1669748",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "85205e97",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/llm-compiler/LLMCompiler.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "2fdab366",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5cc8a2ad",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/multi_agent/hierarchical_agent_teams.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b9f3508a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d2b507b9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/multi_agent/multi-agent-collaboration.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "41a8f10a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9138f92e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/plan-and-execute/plan-and-execute.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "093678ba",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "294995c4",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/react-agent-from-scratch.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "40f0d107",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/react-agent-structured-output.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "658773a2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/reflection/reflection.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1cb60657",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "caf07859",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/reflexion/reflexion.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cd1df0e0",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "961f43ec",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/rewoo/rewoo.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7f00c427",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bbd6e9b8",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/run-id-langsmith.md)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f6db1873",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/self-discover/self-discover.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "219a78f9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f49876e1",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/subgraph.md)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7fd8bd65",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/how-tos/tool-calling.md)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "83c2223f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/sql/sql-agent.md)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "57f924b1",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "11140167",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/tnt-llm/tnt-llm.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1a2ba3e6",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9dffdb54",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/usaco/usaco.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "579c9959",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "007ea2e9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"[This file has been moved](https://github.com/langchain-ai/langgraph/blob/23961cff61a42b52525f3b20b4094d8d2fba1744/docs/docs/tutorials/web-navigation/web_voyager.ipynb)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f0d7b895",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This directory is retained purely for archival purposes and is no longer updated. The examples previously found here have been moved to the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.PHONY: format lint test
|
||||
|
||||
format:
|
||||
uv run ruff format .
|
||||
uv run ruff check --fix .
|
||||
|
||||
lint:
|
||||
uv run ruff check .
|
||||
uv run ty check
|
||||
|
||||
test:
|
||||
uv run pytest $(TEST)
|
||||
@@ -0,0 +1,134 @@
|
||||
# LangGraph Checkpoint Conformance
|
||||
|
||||
[](https://pypi.org/project/langgraph-checkpoint-conformance/#history)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://pypistats.org/packages/langgraph-checkpoint-conformance)
|
||||
[](https://x.com/langchain_oss)
|
||||
|
||||
To help you ship LangGraph apps to production faster, check out [LangSmith](https://www.langchain.com/langsmith).
|
||||
[LangSmith](https://www.langchain.com/langsmith) is a unified developer platform for building, testing, and monitoring LLM applications.
|
||||
|
||||
## Quick Install
|
||||
|
||||
```bash
|
||||
uv add langgraph-checkpoint-conformance
|
||||
```
|
||||
|
||||
## 🤔 What is this?
|
||||
|
||||
This library provides a conformance test suite for [LangGraph](https://github.com/langchain-ai/langgraph) checkpointer implementations. It validates that a `BaseCheckpointSaver` subclass correctly implements the checkpoint storage contract — blob round-trips, metadata preservation, namespace isolation, incremental channel updates, and more.
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
For full documentation, see the [API reference](https://reference.langchain.com/python/langgraph/). For conceptual guides on persistence and memory, see the [LangGraph Docs](https://docs.langchain.com/oss/python/langgraph/overview).
|
||||
|
||||
## Quick start
|
||||
|
||||
Register your checkpointer with `@checkpointer_test` and run `validate()`:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from langgraph.checkpoint.conformance import checkpointer_test, validate
|
||||
|
||||
@checkpointer_test(name="MyCheckpointer")
|
||||
async def my_checkpointer():
|
||||
saver = MyCheckpointer(...)
|
||||
yield saver
|
||||
# cleanup runs after yield
|
||||
|
||||
async def main():
|
||||
report = await validate(my_checkpointer)
|
||||
report.print_report()
|
||||
assert report.passed_all_base()
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
Or in a pytest test:
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from langgraph.checkpoint.conformance import checkpointer_test, validate
|
||||
|
||||
@checkpointer_test(name="MyCheckpointer")
|
||||
async def my_checkpointer():
|
||||
yield MyCheckpointer(...)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conformance():
|
||||
report = await validate(my_checkpointer)
|
||||
report.print_report()
|
||||
assert report.passed_all_base()
|
||||
```
|
||||
|
||||
## Capabilities
|
||||
|
||||
The suite tests **base** capabilities (required) and **extended** capabilities (optional, auto-detected):
|
||||
|
||||
| Capability | Required | Method |
|
||||
|---|---|---|
|
||||
| `put` | yes | `aput` |
|
||||
| `put_writes` | yes | `aput_writes` |
|
||||
| `get_tuple` | yes | `aget_tuple` |
|
||||
| `list` | yes | `alist` |
|
||||
| `delete_thread` | yes | `adelete_thread` |
|
||||
| `delete_for_runs` | no | `adelete_for_runs` |
|
||||
| `copy_thread` | no | `acopy_thread` |
|
||||
| `prune` | no | `aprune` |
|
||||
| `delta_channel_history` | no | `aget_delta_channel_history` |
|
||||
|
||||
Extended capabilities are detected by checking whether the method is overridden from `BaseCheckpointSaver`. If not overridden, those tests are skipped.
|
||||
|
||||
## Options
|
||||
|
||||
### Progress output
|
||||
|
||||
```python
|
||||
from langgraph.checkpoint.conformance.report import ProgressCallbacks
|
||||
|
||||
# Dot-style progress (. per pass, F per fail)
|
||||
report = await validate(my_checkpointer, progress=ProgressCallbacks.default())
|
||||
|
||||
# Verbose (per-test names + stacktraces on failure)
|
||||
report = await validate(my_checkpointer, progress=ProgressCallbacks.verbose())
|
||||
```
|
||||
|
||||
### Skip capabilities
|
||||
|
||||
```python
|
||||
@checkpointer_test(name="MyCheckpointer", skip_capabilities={"prune"})
|
||||
async def my_checkpointer():
|
||||
yield MyCheckpointer(...)
|
||||
```
|
||||
|
||||
### Run specific capabilities
|
||||
|
||||
```python
|
||||
report = await validate(my_checkpointer, capabilities={"put", "list"})
|
||||
```
|
||||
|
||||
### Lifespan (one-time setup/teardown)
|
||||
|
||||
For expensive setup like database creation:
|
||||
|
||||
```python
|
||||
async def db_lifespan():
|
||||
await create_database()
|
||||
yield
|
||||
await drop_database()
|
||||
|
||||
@checkpointer_test(name="PostgresSaver", lifespan=db_lifespan)
|
||||
async def pg_checkpointer():
|
||||
async with PostgresSaver.from_conn_string(CONN_STRING) as saver:
|
||||
yield saver
|
||||
```
|
||||
|
||||
## 📕 Releases & Versioning
|
||||
|
||||
See our [Releases](https://docs.langchain.com/oss/python/release-policy) and [Versioning](https://docs.langchain.com/oss/python/versioning) policies.
|
||||
|
||||
## 💁 Contributing
|
||||
|
||||
As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
|
||||
|
||||
For detailed information on how to contribute, see the [Contributing Guide](https://docs.langchain.com/oss/python/contributing/overview).
|
||||
@@ -0,0 +1,9 @@
|
||||
"""langgraph-checkpoint-conformance: conformance test suite for checkpointer implementations."""
|
||||
|
||||
from langgraph.checkpoint.conformance.initializer import checkpointer_test
|
||||
from langgraph.checkpoint.conformance.validate import validate
|
||||
|
||||
__all__ = [
|
||||
"checkpointer_test",
|
||||
"validate",
|
||||
]
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Capability detection for checkpointer implementations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
|
||||
class Capability(str, Enum):
|
||||
"""Capabilities that a checkpointer may support."""
|
||||
|
||||
PUT = "put"
|
||||
PUT_WRITES = "put_writes"
|
||||
GET_TUPLE = "get_tuple"
|
||||
LIST = "list"
|
||||
DELETE_THREAD = "delete_thread"
|
||||
DELETE_FOR_RUNS = "delete_for_runs"
|
||||
COPY_THREAD = "copy_thread"
|
||||
PRUNE = "prune"
|
||||
DELTA_CHANNEL_HISTORY = "delta_channel_history"
|
||||
|
||||
|
||||
# Capabilities that every checkpointer must support.
|
||||
BASE_CAPABILITIES = frozenset(
|
||||
{
|
||||
Capability.PUT,
|
||||
Capability.PUT_WRITES,
|
||||
Capability.GET_TUPLE,
|
||||
Capability.LIST,
|
||||
Capability.DELETE_THREAD,
|
||||
}
|
||||
)
|
||||
|
||||
# Capabilities that are optional extensions.
|
||||
EXTENDED_CAPABILITIES = frozenset(
|
||||
{
|
||||
Capability.DELETE_FOR_RUNS,
|
||||
Capability.COPY_THREAD,
|
||||
Capability.PRUNE,
|
||||
Capability.DELTA_CHANNEL_HISTORY,
|
||||
}
|
||||
)
|
||||
|
||||
ALL_CAPABILITIES = BASE_CAPABILITIES | EXTENDED_CAPABILITIES
|
||||
|
||||
# Maps capability to the async method name on BaseCheckpointSaver (or subclass).
|
||||
_CAPABILITY_METHOD_MAP: dict[Capability, str] = {
|
||||
Capability.PUT: "aput",
|
||||
Capability.PUT_WRITES: "aput_writes",
|
||||
Capability.GET_TUPLE: "aget_tuple",
|
||||
Capability.LIST: "alist",
|
||||
Capability.DELETE_THREAD: "adelete_thread",
|
||||
Capability.DELETE_FOR_RUNS: "adelete_for_runs",
|
||||
Capability.COPY_THREAD: "acopy_thread",
|
||||
Capability.PRUNE: "aprune",
|
||||
Capability.DELTA_CHANNEL_HISTORY: "aget_delta_channel_history",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DetectedCapabilities:
|
||||
"""Result of capability detection for a checkpointer type."""
|
||||
|
||||
detected: frozenset[Capability]
|
||||
missing: frozenset[Capability]
|
||||
|
||||
@classmethod
|
||||
def from_instance(cls, saver: BaseCheckpointSaver) -> DetectedCapabilities:
|
||||
"""Detect capabilities from a checkpointer instance."""
|
||||
inner_type = type(saver)
|
||||
detected: set[Capability] = set()
|
||||
|
||||
for cap, method_name in _CAPABILITY_METHOD_MAP.items():
|
||||
if _is_overridden(inner_type, method_name):
|
||||
detected.add(cap)
|
||||
|
||||
detected_fs = frozenset(detected)
|
||||
return cls(
|
||||
detected=detected_fs,
|
||||
missing=ALL_CAPABILITIES - detected_fs,
|
||||
)
|
||||
|
||||
|
||||
def _is_overridden(inner_type: type, method: str) -> bool:
|
||||
"""Check if *method* on *inner_type* differs from the base class default."""
|
||||
base = getattr(BaseCheckpointSaver, method, None)
|
||||
impl = getattr(inner_type, method, None)
|
||||
if base is None or impl is None:
|
||||
return impl is not None
|
||||
return impl is not base
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Checkpointer test registration and factory management."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator, Callable
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
# Type for the lifespan async context manager factory.
|
||||
LifespanFactory = Callable[[], AsyncGenerator[None, None]]
|
||||
|
||||
# Module-level registry of decorated checkpointer factories.
|
||||
_REGISTRY: dict[str, RegisteredCheckpointer] = {}
|
||||
|
||||
|
||||
async def _noop_lifespan() -> AsyncGenerator[None, None]:
|
||||
yield
|
||||
|
||||
|
||||
@dataclass
|
||||
class RegisteredCheckpointer:
|
||||
"""A registered checkpointer test factory."""
|
||||
|
||||
name: str
|
||||
factory: Callable[[], AsyncGenerator[BaseCheckpointSaver, None]]
|
||||
skip_capabilities: set[str] = field(default_factory=set)
|
||||
lifespan: LifespanFactory = _noop_lifespan
|
||||
|
||||
@asynccontextmanager
|
||||
async def create(self) -> AsyncGenerator[BaseCheckpointSaver, None]:
|
||||
"""Create a fresh checkpointer instance via the async generator."""
|
||||
gen = self.factory()
|
||||
try:
|
||||
saver = await gen.__anext__()
|
||||
yield saver
|
||||
finally:
|
||||
try:
|
||||
await gen.__anext__()
|
||||
except StopAsyncIteration:
|
||||
pass
|
||||
|
||||
@asynccontextmanager
|
||||
async def enter_lifespan(self) -> AsyncGenerator[None, None]:
|
||||
"""Enter the lifespan context (once per validation run)."""
|
||||
gen = self.lifespan()
|
||||
try:
|
||||
await gen.__anext__()
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
await gen.__anext__()
|
||||
except StopAsyncIteration:
|
||||
pass
|
||||
|
||||
|
||||
def checkpointer_test(
|
||||
name: str,
|
||||
*,
|
||||
skip_capabilities: set[str] | None = None,
|
||||
lifespan: LifespanFactory | None = None,
|
||||
) -> Callable[[Any], RegisteredCheckpointer]:
|
||||
"""Register an async generator as a checkpointer test factory.
|
||||
|
||||
The factory is called once per capability suite to create a fresh
|
||||
checkpointer. The optional `lifespan` is an async generator that
|
||||
runs once for the entire validation run (e.g. to create/destroy a
|
||||
database).
|
||||
|
||||
Example::
|
||||
|
||||
@checkpointer_test(name="InMemorySaver")
|
||||
async def memory_checkpointer():
|
||||
yield InMemorySaver()
|
||||
|
||||
With lifespan::
|
||||
|
||||
async def pg_lifespan():
|
||||
await create_database()
|
||||
yield
|
||||
await drop_database()
|
||||
|
||||
@checkpointer_test(name="PostgresSaver", lifespan=pg_lifespan)
|
||||
async def pg_checkpointer():
|
||||
yield PostgresSaver(conn_string="...")
|
||||
"""
|
||||
|
||||
def decorator(fn: Any) -> RegisteredCheckpointer:
|
||||
registered = RegisteredCheckpointer(
|
||||
name=name,
|
||||
factory=fn,
|
||||
skip_capabilities=skip_capabilities or set(),
|
||||
lifespan=lifespan or _noop_lifespan,
|
||||
)
|
||||
_REGISTRY[name] = registered
|
||||
return registered
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Capability report: results, progress callbacks, and pretty-printing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from langgraph.checkpoint.conformance.capabilities import (
|
||||
BASE_CAPABILITIES,
|
||||
EXTENDED_CAPABILITIES,
|
||||
Capability,
|
||||
)
|
||||
|
||||
# Callback type for per-test progress reporting.
|
||||
# (capability_name, test_name, passed, error_msg_or_None) -> None
|
||||
OnTestResult = Callable[[str, str, bool, str | None], None]
|
||||
|
||||
# Callback type for capability-level events.
|
||||
# (capability_name, detected) -> None
|
||||
OnCapabilityStart = Callable[[str, bool], None]
|
||||
|
||||
|
||||
class ProgressCallbacks:
|
||||
"""Grouped callbacks for progress reporting during validation."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
on_capability_start: Callable[[str, bool], None] | None = None,
|
||||
on_test_result: OnTestResult | None = None,
|
||||
on_capability_end: Callable[[str], None] | None = None,
|
||||
) -> None:
|
||||
self.on_capability_start = on_capability_start
|
||||
self.on_test_result = on_test_result
|
||||
self.on_capability_end = on_capability_end
|
||||
|
||||
@classmethod
|
||||
def default(cls) -> ProgressCallbacks:
|
||||
"""Dot-style progress: ``.`` per pass, ``F`` per fail."""
|
||||
|
||||
def _cap_start(capability: str, detected: bool) -> None:
|
||||
if detected:
|
||||
print(f" {capability}: ", end="", flush=True)
|
||||
else:
|
||||
print(f" ⊘ {capability} (not implemented)")
|
||||
|
||||
def _test_result(
|
||||
capability: str, test_name: str, passed: bool, error: str | None
|
||||
) -> None:
|
||||
print("." if passed else "F", end="", flush=True)
|
||||
|
||||
def _cap_end(capability: str) -> None:
|
||||
print() # newline after dots
|
||||
|
||||
return cls(
|
||||
on_capability_start=_cap_start,
|
||||
on_test_result=_test_result,
|
||||
on_capability_end=_cap_end,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def verbose(cls) -> ProgressCallbacks:
|
||||
"""Per-test output with names and errors."""
|
||||
|
||||
def _cap_start(capability: str, detected: bool) -> None:
|
||||
if detected:
|
||||
print(f" {capability}:")
|
||||
else:
|
||||
print(f" ⊘ {capability} (not implemented)")
|
||||
|
||||
def _test_result(
|
||||
capability: str, test_name: str, passed: bool, error: str | None
|
||||
) -> None:
|
||||
icon = "✓" if passed else "✗"
|
||||
print(f" {icon} {test_name}")
|
||||
if error:
|
||||
for line in error.rstrip().splitlines():
|
||||
print(f" {line}")
|
||||
|
||||
return cls(
|
||||
on_capability_start=_cap_start,
|
||||
on_test_result=_test_result,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def quiet(cls) -> ProgressCallbacks:
|
||||
"""No progress output."""
|
||||
return cls()
|
||||
|
||||
|
||||
@dataclass
|
||||
class CapabilityResult:
|
||||
"""Result of running a single capability's test suite."""
|
||||
|
||||
detected: bool = False
|
||||
passed: bool | None = None # None = skipped
|
||||
tests_passed: int = 0
|
||||
tests_failed: int = 0
|
||||
tests_skipped: int = 0
|
||||
failures: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CapabilityReport:
|
||||
"""Aggregate report across all capabilities."""
|
||||
|
||||
checkpointer_name: str
|
||||
results: dict[str, CapabilityResult] = field(default_factory=dict)
|
||||
|
||||
def passed_all_base(self) -> bool:
|
||||
"""Whether all base capability tests passed."""
|
||||
for cap in BASE_CAPABILITIES:
|
||||
result = self.results.get(cap.value)
|
||||
if result is None or result.passed is not True:
|
||||
return False
|
||||
return True
|
||||
|
||||
def passed_all(self) -> bool:
|
||||
"""Whether every detected capability's tests passed."""
|
||||
for result in self.results.values():
|
||||
if result.detected and result.passed is not True:
|
||||
return False
|
||||
return True
|
||||
|
||||
def conformance_level(self) -> str:
|
||||
"""Return a human-readable conformance level string."""
|
||||
if self.passed_all():
|
||||
return "FULL"
|
||||
if self.passed_all_base():
|
||||
return "BASE+PARTIAL"
|
||||
return "BASE" if self._any_base_passed() else "NONE"
|
||||
|
||||
def _any_base_passed(self) -> bool:
|
||||
for cap in BASE_CAPABILITIES:
|
||||
result = self.results.get(cap.value)
|
||||
if result and result.passed is True:
|
||||
return True
|
||||
return False
|
||||
|
||||
def print_report(self) -> None:
|
||||
"""Pretty-print the report to stdout."""
|
||||
width = 52
|
||||
border = "=" * width
|
||||
print(f"\n{'':>2}{border}")
|
||||
print(f"{'':>2} Checkpointer Validation: {self.checkpointer_name}")
|
||||
print(f"{'':>2}{border}")
|
||||
|
||||
def _section(title: str, caps: frozenset[Capability]) -> None:
|
||||
print(f"{'':>2} {title}")
|
||||
for cap in sorted(caps, key=lambda c: c.value):
|
||||
result = self.results.get(cap.value)
|
||||
if result is None:
|
||||
icon = " "
|
||||
suffix = "(no tests)"
|
||||
elif not result.detected:
|
||||
icon = "⊘ "
|
||||
suffix = "(not implemented)"
|
||||
elif result.passed is True:
|
||||
icon = "✅"
|
||||
suffix = ""
|
||||
elif result.passed is False:
|
||||
icon = "❌"
|
||||
suffix = f"({result.tests_failed} failed)"
|
||||
else:
|
||||
icon = "⏭ "
|
||||
suffix = "(skipped)"
|
||||
print(f"{'':>2} {icon} {cap.value:20s} {suffix}")
|
||||
print()
|
||||
|
||||
_section("BASE CAPABILITIES", BASE_CAPABILITIES)
|
||||
_section("EXTENDED CAPABILITIES", EXTENDED_CAPABILITIES)
|
||||
|
||||
total = sum(1 for r in self.results.values() if r.detected)
|
||||
passed = sum(
|
||||
1 for r in self.results.values() if r.detected and r.passed is True
|
||||
)
|
||||
level = self.conformance_level()
|
||||
print(f"{'':>2} Result: {level} ({passed}/{total})")
|
||||
print(f"{'':>2}{border}\n")
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Return a JSON-serializable dict."""
|
||||
return {
|
||||
"checkpointer_name": self.checkpointer_name,
|
||||
"conformance_level": self.conformance_level(),
|
||||
"results": {
|
||||
name: {
|
||||
"detected": r.detected,
|
||||
"passed": r.passed,
|
||||
"tests_passed": r.tests_passed,
|
||||
"tests_failed": r.tests_failed,
|
||||
"tests_skipped": r.tests_skipped,
|
||||
"failures": r.failures,
|
||||
}
|
||||
for name, r in self.results.items()
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Test spec modules for each checkpointer capability."""
|
||||
|
||||
from langgraph.checkpoint.conformance.spec.test_copy_thread import (
|
||||
run_copy_thread_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_delete_for_runs import (
|
||||
run_delete_for_runs_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_delete_thread import (
|
||||
run_delete_thread_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_delta_channel_history import (
|
||||
run_delta_channel_history_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_get_tuple import run_get_tuple_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_list import run_list_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_prune import run_prune_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_put import run_put_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_put_writes import run_put_writes_tests
|
||||
|
||||
__all__ = [
|
||||
"run_put_tests",
|
||||
"run_put_writes_tests",
|
||||
"run_get_tuple_tests",
|
||||
"run_list_tests",
|
||||
"run_delete_thread_tests",
|
||||
"run_delete_for_runs_tests",
|
||||
"run_copy_thread_tests",
|
||||
"run_prune_tests",
|
||||
"run_delta_channel_history_tests",
|
||||
]
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Shared fixtures for delta-channel conformance tests.
|
||||
|
||||
Builds a parent chain with `_DeltaSnapshot` blobs at known positions via
|
||||
direct `aput` / `aput_writes` calls. No langgraph or Pregel dependency.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver, Checkpoint
|
||||
from langgraph.checkpoint.base.id import uuid6
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import generate_metadata
|
||||
|
||||
|
||||
async def build_delta_chain(
|
||||
saver: BaseCheckpointSaver,
|
||||
*,
|
||||
thread_id: str | None = None,
|
||||
checkpoint_ns: str = "",
|
||||
channel: str = "messages",
|
||||
snapshots_at_steps: Sequence[int] = (0,),
|
||||
total_steps: int = 6,
|
||||
write_value_fn: Any | None = None,
|
||||
) -> list[RunnableConfig]:
|
||||
"""Build a parent chain with `_DeltaSnapshot` at known positions.
|
||||
|
||||
Args:
|
||||
saver: Checkpointer instance.
|
||||
thread_id: Defaults to a random UUID.
|
||||
checkpoint_ns: Namespace (default root).
|
||||
channel: Channel name used for snapshots and writes.
|
||||
snapshots_at_steps: Steps at which a `_DeltaSnapshot` blob is stored
|
||||
in `channel_values[channel]`. Step 0 is the oldest checkpoint.
|
||||
total_steps: Number of checkpoints in the chain.
|
||||
write_value_fn: Callable(step) -> write value. Defaults to step index.
|
||||
|
||||
Returns:
|
||||
List of stored configs (oldest first), one per step.
|
||||
"""
|
||||
if write_value_fn is None:
|
||||
|
||||
def write_value_fn(step: int) -> Any:
|
||||
return step
|
||||
|
||||
from langgraph.checkpoint.serde.types import _DeltaSnapshot
|
||||
|
||||
thread_id = thread_id or str(uuid4())
|
||||
snapshot_set = set(snapshots_at_steps)
|
||||
stored: list[RunnableConfig] = []
|
||||
parent_cfg: RunnableConfig | None = None
|
||||
|
||||
for step in range(total_steps):
|
||||
config: RunnableConfig = {
|
||||
"configurable": {
|
||||
"thread_id": thread_id,
|
||||
"checkpoint_ns": checkpoint_ns,
|
||||
}
|
||||
}
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
|
||||
channel_values: dict[str, Any] = {}
|
||||
channel_versions: dict[str, int] = {}
|
||||
if step in snapshot_set:
|
||||
channel_values[channel] = _DeltaSnapshot(
|
||||
write_value_fn(step),
|
||||
)
|
||||
channel_versions[channel] = step + 1
|
||||
|
||||
cp = Checkpoint(
|
||||
v=1,
|
||||
id=str(uuid6(clock_seq=-1)),
|
||||
ts="",
|
||||
channel_values=channel_values,
|
||||
channel_versions=channel_versions,
|
||||
versions_seen={},
|
||||
updated_channels=None,
|
||||
)
|
||||
new_versions = dict(channel_versions)
|
||||
parent_cfg = await saver.aput(
|
||||
config, cp, generate_metadata(step=step), new_versions
|
||||
)
|
||||
stored.append(parent_cfg)
|
||||
|
||||
# Write a pending write for non-snapshot steps so the walk has
|
||||
# something to collect.
|
||||
if step not in snapshot_set:
|
||||
await saver.aput_writes(
|
||||
parent_cfg, [(channel, write_value_fn(step))], str(uuid4())
|
||||
)
|
||||
|
||||
return stored
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
"""COPY_THREAD capability tests — acopy_thread."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def _setup_source_thread(
|
||||
saver: BaseCheckpointSaver,
|
||||
tid: str,
|
||||
*,
|
||||
n: int = 3,
|
||||
namespaces: list[str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""Create n checkpoints on tid (optionally across namespaces). Returns stored configs."""
|
||||
nss = namespaces or [""]
|
||||
stored = []
|
||||
for ns in nss:
|
||||
parent_cfg = None
|
||||
for i in range(n):
|
||||
config = generate_config(tid, checkpoint_ns=ns)
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint(channel_values={"step": i})
|
||||
cp["channel_versions"] = {"step": 1}
|
||||
parent_cfg = await saver.aput(
|
||||
config, cp, generate_metadata(step=i), {"step": 1}
|
||||
)
|
||||
stored.append(parent_cfg)
|
||||
return stored
|
||||
|
||||
|
||||
async def test_copy_thread_basic(saver: BaseCheckpointSaver) -> None:
|
||||
"""Checkpoints appear on target thread."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src)
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(dst)):
|
||||
results.append(tup)
|
||||
assert len(results) == 3, f"Expected 3 copied checkpoints, got {len(results)}"
|
||||
|
||||
|
||||
async def test_copy_thread_all_checkpoints(saver: BaseCheckpointSaver) -> None:
|
||||
"""All checkpoints copied, not just latest."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src, n=3)
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
src_results = []
|
||||
async for tup in saver.alist(generate_config(src)):
|
||||
src_results.append(tup)
|
||||
|
||||
dst_results = []
|
||||
async for tup in saver.alist(generate_config(dst)):
|
||||
dst_results.append(tup)
|
||||
|
||||
assert len(dst_results) == len(src_results)
|
||||
# Verify content matches
|
||||
for s, d in zip(
|
||||
sorted(src_results, key=lambda t: t.checkpoint["id"]),
|
||||
sorted(dst_results, key=lambda t: t.checkpoint["id"]),
|
||||
strict=True,
|
||||
):
|
||||
assert s.checkpoint["channel_values"] == d.checkpoint["channel_values"], (
|
||||
f"channel_values mismatch for checkpoint {s.checkpoint['id']}"
|
||||
)
|
||||
|
||||
|
||||
async def test_copy_thread_preserves_metadata(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Metadata intact on copied checkpoints."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src, n=2)
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
src_tuples = []
|
||||
async for tup in saver.alist(generate_config(src)):
|
||||
src_tuples.append(tup)
|
||||
|
||||
dst_tuples = []
|
||||
async for tup in saver.alist(generate_config(dst)):
|
||||
dst_tuples.append(tup)
|
||||
|
||||
for s, d in zip(
|
||||
sorted(src_tuples, key=lambda t: t.metadata.get("step", 0)),
|
||||
sorted(dst_tuples, key=lambda t: t.metadata.get("step", 0)),
|
||||
strict=True,
|
||||
):
|
||||
for key in s.metadata:
|
||||
assert s.metadata.get(key) == d.metadata.get(key), (
|
||||
f"metadata[{key!r}] mismatch: {s.metadata.get(key)!r} != {d.metadata.get(key)!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_copy_thread_preserves_namespaces(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Root + child namespaces copied."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src, n=1, namespaces=["", "child:1"])
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
for ns in ["", "child:1"]:
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(dst, checkpoint_ns=ns)):
|
||||
results.append(tup)
|
||||
assert len(results) == 1, (
|
||||
f"Expected 1 checkpoint in namespace '{ns}', got {len(results)}"
|
||||
)
|
||||
|
||||
|
||||
async def test_copy_thread_preserves_writes(saver: BaseCheckpointSaver) -> None:
|
||||
"""Pending writes copied."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
configs = await _setup_source_thread(saver, src, n=1)
|
||||
|
||||
# Add a write to the source
|
||||
await saver.aput_writes(configs[-1], [("ch", "write_val")], str(uuid4()))
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
tup = await saver.aget_tuple(generate_config(dst))
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 1, (
|
||||
f"Expected 1 write, got {len(tup.pending_writes)}"
|
||||
)
|
||||
assert tup.pending_writes[0][1] == "ch", (
|
||||
f"channel mismatch: {tup.pending_writes[0][1]!r}"
|
||||
)
|
||||
assert tup.pending_writes[0][2] == "write_val", (
|
||||
f"value mismatch: {tup.pending_writes[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_copy_thread_preserves_ordering(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Checkpoint order maintained."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src, n=4)
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
src_ids = []
|
||||
async for tup in saver.alist(generate_config(src)):
|
||||
src_ids.append(tup.checkpoint["id"])
|
||||
|
||||
dst_ids = []
|
||||
async for tup in saver.alist(generate_config(dst)):
|
||||
dst_ids.append(tup.checkpoint["id"])
|
||||
|
||||
# Order should match (both newest-first)
|
||||
assert src_ids == dst_ids
|
||||
|
||||
|
||||
async def test_copy_thread_source_unchanged(saver: BaseCheckpointSaver) -> None:
|
||||
"""Source thread still intact after copy."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
await _setup_source_thread(saver, src, n=2)
|
||||
|
||||
# Snapshot source before copy
|
||||
src_before = []
|
||||
async for tup in saver.alist(generate_config(src)):
|
||||
src_before.append(tup.checkpoint["id"])
|
||||
|
||||
await saver.acopy_thread(src, dst)
|
||||
# Source should be unchanged
|
||||
src_after = []
|
||||
async for tup in saver.alist(generate_config(src)):
|
||||
src_after.append(tup.checkpoint["id"])
|
||||
|
||||
assert src_before == src_after
|
||||
|
||||
|
||||
async def test_copy_thread_nonexistent_source(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Graceful handling of non-existent source thread."""
|
||||
src = str(uuid4())
|
||||
dst = str(uuid4())
|
||||
|
||||
# Should not raise (or raise a known error)
|
||||
try:
|
||||
await saver.acopy_thread(src, dst)
|
||||
except Exception:
|
||||
pass # Some implementations may raise; that's acceptable
|
||||
|
||||
# Destination should be empty
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(dst)):
|
||||
results.append(tup)
|
||||
assert len(results) == 0
|
||||
|
||||
|
||||
ALL_COPY_THREAD_TESTS = [
|
||||
test_copy_thread_basic,
|
||||
test_copy_thread_all_checkpoints,
|
||||
test_copy_thread_preserves_metadata,
|
||||
test_copy_thread_preserves_namespaces,
|
||||
test_copy_thread_preserves_writes,
|
||||
test_copy_thread_preserves_ordering,
|
||||
test_copy_thread_source_unchanged,
|
||||
test_copy_thread_nonexistent_source,
|
||||
]
|
||||
|
||||
|
||||
async def run_copy_thread_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all copy_thread tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_COPY_THREAD_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("copy_thread", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"copy_thread", test_fn.__name__, False, traceback.format_exc()
|
||||
)
|
||||
return passed, failed, failures
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
"""DELETE_FOR_RUNS capability tests — adelete_for_runs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def _put_with_run_id(
|
||||
saver: BaseCheckpointSaver,
|
||||
tid: str,
|
||||
run_id: str,
|
||||
*,
|
||||
checkpoint_ns: str = "",
|
||||
parent_config: dict | None = None,
|
||||
) -> dict:
|
||||
"""Put a checkpoint with a run_id in metadata, return stored config."""
|
||||
config = generate_config(tid, checkpoint_ns=checkpoint_ns)
|
||||
if parent_config:
|
||||
config["configurable"]["checkpoint_id"] = parent_config["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata(run_id=run_id)
|
||||
return await saver.aput(config, cp, md, {})
|
||||
|
||||
|
||||
async def test_delete_for_runs_single(saver: BaseCheckpointSaver) -> None:
|
||||
"""One run_id removed."""
|
||||
tid = str(uuid4())
|
||||
run1, run2 = str(uuid4()), str(uuid4())
|
||||
|
||||
stored1 = await _put_with_run_id(saver, tid, run1)
|
||||
await _put_with_run_id(saver, tid, run2, parent_config=stored1)
|
||||
|
||||
# Pre-delete: verify both runs exist
|
||||
pre_results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
pre_results.append(tup)
|
||||
pre_run_ids = {t.metadata.get("run_id") for t in pre_results}
|
||||
assert run1 in pre_run_ids, "Pre-delete: run1 should exist"
|
||||
assert run2 in pre_run_ids, "Pre-delete: run2 should exist"
|
||||
|
||||
await saver.adelete_for_runs([run1])
|
||||
# run1's checkpoint should be gone; run2 should remain
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
run_ids = {t.metadata.get("run_id") for t in results}
|
||||
assert run1 not in run_ids
|
||||
assert run2 in run_ids
|
||||
|
||||
|
||||
async def test_delete_for_runs_multiple(saver: BaseCheckpointSaver) -> None:
|
||||
"""List of run_ids removed."""
|
||||
tid = str(uuid4())
|
||||
run1, run2, run3 = str(uuid4()), str(uuid4()), str(uuid4())
|
||||
|
||||
s1 = await _put_with_run_id(saver, tid, run1)
|
||||
s2 = await _put_with_run_id(saver, tid, run2, parent_config=s1)
|
||||
await _put_with_run_id(saver, tid, run3, parent_config=s2)
|
||||
|
||||
# Pre-delete: verify all 3 runs exist
|
||||
pre_results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
pre_results.append(tup)
|
||||
pre_run_ids = {t.metadata.get("run_id") for t in pre_results}
|
||||
assert run1 in pre_run_ids, "Pre-delete: run1 should exist"
|
||||
assert run2 in pre_run_ids, "Pre-delete: run2 should exist"
|
||||
assert run3 in pre_run_ids, "Pre-delete: run3 should exist"
|
||||
|
||||
await saver.adelete_for_runs([run1, run2])
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
run_ids = {t.metadata.get("run_id") for t in results}
|
||||
assert run1 not in run_ids
|
||||
assert run2 not in run_ids
|
||||
assert run3 in run_ids
|
||||
|
||||
|
||||
async def test_delete_for_runs_preserves_other_runs(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Unrelated runs untouched."""
|
||||
tid = str(uuid4())
|
||||
run_keep = str(uuid4())
|
||||
run_delete = str(uuid4())
|
||||
|
||||
await _put_with_run_id(saver, tid, run_keep)
|
||||
await _put_with_run_id(saver, tid, run_delete)
|
||||
|
||||
# Pre-delete: verify both runs exist
|
||||
pre_results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
pre_results.append(tup)
|
||||
pre_run_ids = {t.metadata.get("run_id") for t in pre_results}
|
||||
assert run_keep in pre_run_ids, "Pre-delete: run_keep should exist"
|
||||
assert run_delete in pre_run_ids, "Pre-delete: run_delete should exist"
|
||||
|
||||
await saver.adelete_for_runs([run_delete])
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
run_ids = {t.metadata.get("run_id") for t in results}
|
||||
assert run_keep in run_ids
|
||||
|
||||
|
||||
async def test_delete_for_runs_removes_writes(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Associated writes cleaned up."""
|
||||
tid = str(uuid4())
|
||||
run1 = str(uuid4())
|
||||
|
||||
stored = await _put_with_run_id(saver, tid, run1)
|
||||
await saver.aput_writes(stored, [("ch", "val")], str(uuid4()))
|
||||
|
||||
# Pre-delete: verify writes exist
|
||||
pre_tup = await saver.aget_tuple(stored)
|
||||
assert pre_tup is not None, "Pre-delete: checkpoint should exist"
|
||||
assert pre_tup.pending_writes is not None and len(pre_tup.pending_writes) == 1, (
|
||||
f"Pre-delete: expected 1 write, got {len(pre_tup.pending_writes) if pre_tup.pending_writes else 0}"
|
||||
)
|
||||
|
||||
await saver.adelete_for_runs([run1])
|
||||
# The checkpoint (and its writes) should be gone
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is None
|
||||
|
||||
|
||||
async def test_delete_for_runs_empty_list_noop(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Empty list no error."""
|
||||
await saver.adelete_for_runs([])
|
||||
|
||||
|
||||
async def test_delete_for_runs_nonexistent_noop(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Missing run_ids no error."""
|
||||
await saver.adelete_for_runs([str(uuid4())])
|
||||
|
||||
|
||||
async def test_delete_for_runs_across_namespaces(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""All namespaces cleaned."""
|
||||
tid = str(uuid4())
|
||||
run1 = str(uuid4())
|
||||
|
||||
await _put_with_run_id(saver, tid, run1, checkpoint_ns="")
|
||||
await _put_with_run_id(saver, tid, run1, checkpoint_ns="child:1")
|
||||
|
||||
# Pre-delete: verify run1 present in both namespaces
|
||||
for ns in ["", "child:1"]:
|
||||
pre_results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns=ns)):
|
||||
pre_results.append(tup)
|
||||
pre_run_ids = {t.metadata.get("run_id") for t in pre_results}
|
||||
assert run1 in pre_run_ids, f"Pre-delete: run1 should exist in ns='{ns}'"
|
||||
|
||||
await saver.adelete_for_runs([run1])
|
||||
for ns in ["", "child:1"]:
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns=ns)):
|
||||
results.append(tup)
|
||||
run_ids = {t.metadata.get("run_id") for t in results}
|
||||
assert run1 not in run_ids
|
||||
|
||||
|
||||
ALL_DELETE_FOR_RUNS_TESTS = [
|
||||
test_delete_for_runs_single,
|
||||
test_delete_for_runs_multiple,
|
||||
test_delete_for_runs_preserves_other_runs,
|
||||
test_delete_for_runs_removes_writes,
|
||||
test_delete_for_runs_empty_list_noop,
|
||||
test_delete_for_runs_nonexistent_noop,
|
||||
test_delete_for_runs_across_namespaces,
|
||||
]
|
||||
|
||||
|
||||
async def run_delete_for_runs_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all delete_for_runs tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_DELETE_FOR_RUNS_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("delete_for_runs", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"delete_for_runs", test_fn.__name__, False, traceback.format_exc()
|
||||
)
|
||||
return passed, failed, failures
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"""DELETE_THREAD capability tests — adelete_thread."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def test_delete_thread_removes_checkpoints(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""All checkpoints gone after delete."""
|
||||
tid = str(uuid4())
|
||||
parent_cfg = None
|
||||
for i in range(3):
|
||||
config = generate_config(tid)
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
parent_cfg = await saver.aput(config, cp, generate_metadata(step=i), {})
|
||||
|
||||
# Pre-delete: verify data exists
|
||||
assert await saver.aget_tuple(generate_config(tid)) is not None, (
|
||||
"Pre-delete: checkpoint should exist"
|
||||
)
|
||||
|
||||
await saver.adelete_thread(tid)
|
||||
|
||||
tup = await saver.aget_tuple(generate_config(tid))
|
||||
assert tup is None
|
||||
|
||||
results = []
|
||||
async for t in saver.alist(generate_config(tid)):
|
||||
results.append(t)
|
||||
assert len(results) == 0
|
||||
|
||||
|
||||
async def test_delete_thread_removes_writes(saver: BaseCheckpointSaver) -> None:
|
||||
"""Pending writes gone after delete."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
await saver.aput_writes(stored, [("ch", "val")], str(uuid4()))
|
||||
|
||||
# Pre-delete: verify writes exist
|
||||
pre_tup = await saver.aget_tuple(generate_config(tid))
|
||||
assert pre_tup is not None, "Pre-delete: checkpoint should exist"
|
||||
assert pre_tup.pending_writes is not None and len(pre_tup.pending_writes) == 1, (
|
||||
f"Pre-delete: expected 1 write, got {len(pre_tup.pending_writes) if pre_tup.pending_writes else 0}"
|
||||
)
|
||||
|
||||
await saver.adelete_thread(tid)
|
||||
|
||||
tup = await saver.aget_tuple(generate_config(tid))
|
||||
assert tup is None
|
||||
|
||||
|
||||
async def test_delete_thread_removes_all_namespaces(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Root + child namespaces both removed."""
|
||||
tid = str(uuid4())
|
||||
|
||||
for ns in ["", "child:1"]:
|
||||
cfg = generate_config(tid, checkpoint_ns=ns)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(cfg, cp, generate_metadata(), {})
|
||||
|
||||
# Pre-delete: verify each namespace has data
|
||||
for ns in ["", "child:1"]:
|
||||
pre = await saver.aget_tuple(generate_config(tid, checkpoint_ns=ns))
|
||||
assert pre is not None, f"Pre-delete: namespace '{ns}' should have data"
|
||||
|
||||
await saver.adelete_thread(tid)
|
||||
|
||||
for ns in ["", "child:1"]:
|
||||
tup = await saver.aget_tuple(generate_config(tid, checkpoint_ns=ns))
|
||||
assert tup is None
|
||||
|
||||
|
||||
async def test_delete_thread_preserves_other_threads(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Other threads untouched."""
|
||||
tid1, tid2 = str(uuid4()), str(uuid4())
|
||||
|
||||
for tid in (tid1, tid2):
|
||||
cfg = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(cfg, cp, generate_metadata(), {})
|
||||
|
||||
await saver.adelete_thread(tid1)
|
||||
|
||||
assert await saver.aget_tuple(generate_config(tid1)) is None
|
||||
assert await saver.aget_tuple(generate_config(tid2)) is not None
|
||||
|
||||
|
||||
async def test_delete_thread_nonexistent_noop(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""No error for missing thread."""
|
||||
# Should not raise
|
||||
await saver.adelete_thread(str(uuid4()))
|
||||
|
||||
|
||||
ALL_DELETE_THREAD_TESTS = [
|
||||
test_delete_thread_removes_checkpoints,
|
||||
test_delete_thread_removes_writes,
|
||||
test_delete_thread_removes_all_namespaces,
|
||||
test_delete_thread_preserves_other_threads,
|
||||
test_delete_thread_nonexistent_noop,
|
||||
]
|
||||
|
||||
|
||||
async def run_delete_thread_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all delete_thread tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_DELETE_THREAD_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("delete_thread", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"delete_thread", test_fn.__name__, False, traceback.format_exc()
|
||||
)
|
||||
return passed, failed, failures
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
"""DELTA_CHANNEL_HISTORY capability tests — aget_delta_channel_history contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.spec._delta_fixtures import build_delta_chain
|
||||
|
||||
|
||||
async def test_history_returns_writes_oldest_first(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Writes are returned oldest-to-newest."""
|
||||
tid = str(uuid4())
|
||||
# 5 steps: snapshot at 0, writes at 1,2,3,4.
|
||||
# Head is step 4. Walk starts at step 3 (parent of head).
|
||||
# Collects writes from steps 1,2,3 (between snapshot at 0 and head's parent).
|
||||
configs = await build_delta_chain(
|
||||
saver, thread_id=tid, channel="ch", snapshots_at_steps=[0], total_steps=5
|
||||
)
|
||||
head = configs[-1]
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["ch"])
|
||||
writes = result["ch"]["writes"]
|
||||
values = [w[2] for w in writes]
|
||||
assert values == [1, 2, 3], f"Expected [1,2,3], got {values}"
|
||||
|
||||
|
||||
async def test_history_seed_is_nearest_snapshot(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Seed is the value from the nearest ancestor with channel_values populated."""
|
||||
tid = str(uuid4())
|
||||
# 6 steps: snapshots at 0 and 3, writes at 1,2,4,5.
|
||||
# Head is step 5. Walk from step 4 backward stops at step 3 (snapshot).
|
||||
# Collects writes from step 4 only (between step 3 and head's parent step 4).
|
||||
configs = await build_delta_chain(
|
||||
saver,
|
||||
thread_id=tid,
|
||||
channel="ch",
|
||||
snapshots_at_steps=[0, 3],
|
||||
total_steps=6,
|
||||
)
|
||||
head = configs[-1]
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["ch"])
|
||||
assert "seed" in result["ch"], "Expected seed from snapshot at step 3"
|
||||
seed = result["ch"]["seed"]
|
||||
from langgraph.checkpoint.serde.types import _DeltaSnapshot
|
||||
|
||||
actual_value = seed.value if isinstance(seed, _DeltaSnapshot) else seed
|
||||
assert actual_value == 3, f"Expected seed value 3 (step 3), got {actual_value}"
|
||||
writes = result["ch"]["writes"]
|
||||
values = [w[2] for w in writes]
|
||||
assert values == [4], f"Expected [4], got {values}"
|
||||
|
||||
|
||||
async def test_history_excludes_target_pending_writes(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Target's own pending_writes are NOT included in the history."""
|
||||
tid = str(uuid4())
|
||||
configs = await build_delta_chain(
|
||||
saver, thread_id=tid, channel="ch", snapshots_at_steps=[0], total_steps=3
|
||||
)
|
||||
head = configs[-1]
|
||||
# Add writes directly to the head checkpoint
|
||||
await saver.aput_writes(head, [("ch", "extra")], str(uuid4()))
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["ch"])
|
||||
writes = result["ch"]["writes"]
|
||||
values = [w[2] for w in writes]
|
||||
assert "extra" not in values, f"Target's writes should be excluded, got {values}"
|
||||
|
||||
|
||||
async def test_history_multi_channel(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Multiple channels have independent walk termination."""
|
||||
tid = str(uuid4())
|
||||
configs: list = []
|
||||
parent_cfg = None
|
||||
from langgraph.checkpoint.base import Checkpoint
|
||||
from langgraph.checkpoint.base.id import uuid6
|
||||
from langgraph.checkpoint.serde.types import _DeltaSnapshot
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import generate_metadata
|
||||
|
||||
for step in range(5):
|
||||
config = {"configurable": {"thread_id": tid, "checkpoint_ns": ""}}
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cv: dict = {}
|
||||
cvs: dict = {}
|
||||
if step == 1:
|
||||
cv["a"] = _DeltaSnapshot("snap_a")
|
||||
cvs["a"] = step + 1
|
||||
if step == 3:
|
||||
cv["b"] = _DeltaSnapshot("snap_b")
|
||||
cvs["b"] = step + 1
|
||||
cp = Checkpoint(
|
||||
v=1,
|
||||
id=str(uuid6(clock_seq=-1)),
|
||||
ts="",
|
||||
channel_values=cv,
|
||||
channel_versions=cvs,
|
||||
versions_seen={},
|
||||
updated_channels=None,
|
||||
)
|
||||
parent_cfg = await saver.aput(config, cp, generate_metadata(step=step), cvs)
|
||||
configs.append(parent_cfg)
|
||||
await saver.aput_writes(parent_cfg, [("a", step), ("b", step)], str(uuid4()))
|
||||
|
||||
head = configs[-1]
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["a", "b"])
|
||||
a_writes = [w[2] for w in result["a"]["writes"]]
|
||||
b_writes = [w[2] for w in result["b"]["writes"]]
|
||||
assert a_writes == [1, 2, 3], f"Expected a writes [1,2,3], got {a_writes}"
|
||||
assert b_writes == [3], f"Expected b writes [3], got {b_writes}"
|
||||
|
||||
|
||||
async def test_history_empty_channels_returns_empty(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Empty channels list returns empty mapping."""
|
||||
tid = str(uuid4())
|
||||
configs = await build_delta_chain(
|
||||
saver, thread_id=tid, channel="ch", snapshots_at_steps=[0], total_steps=3
|
||||
)
|
||||
result = await saver.aget_delta_channel_history(config=configs[-1], channels=[])
|
||||
assert result == {}
|
||||
|
||||
|
||||
async def test_history_walk_to_root_no_seed(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Walk reaches root without finding seed — no 'seed' key in result."""
|
||||
tid = str(uuid4())
|
||||
configs = await build_delta_chain(
|
||||
saver,
|
||||
thread_id=tid,
|
||||
channel="ch",
|
||||
snapshots_at_steps=[],
|
||||
total_steps=4,
|
||||
)
|
||||
head = configs[-1]
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["ch"])
|
||||
assert "seed" not in result["ch"], f"Expected no seed, got {result['ch']}"
|
||||
|
||||
|
||||
async def test_history_migration_plain_value_as_seed(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Pre-delta plain value in channel_values acts as seed (migration case).
|
||||
|
||||
When a thread was originally using a regular channel (BinaryOperatorAggregate)
|
||||
and later switches to DeltaChannel, the old checkpoint has a plain value in
|
||||
channel_values[ch] (not a _DeltaSnapshot). The walk should treat it as the
|
||||
seed and terminate there.
|
||||
"""
|
||||
from langgraph.checkpoint.base import Checkpoint
|
||||
from langgraph.checkpoint.base.id import uuid6
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import generate_metadata
|
||||
|
||||
tid = str(uuid4())
|
||||
configs: list = []
|
||||
parent_cfg = None
|
||||
|
||||
for step in range(4):
|
||||
config = {"configurable": {"thread_id": tid, "checkpoint_ns": ""}}
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cv: dict = {}
|
||||
cvs: dict = {}
|
||||
# Step 1: plain value (migration case — old checkpoint before delta)
|
||||
if step == 1:
|
||||
cv["ch"] = [10, 20, 30]
|
||||
cvs["ch"] = step + 1
|
||||
cp = Checkpoint(
|
||||
v=1,
|
||||
id=str(uuid6(clock_seq=-1)),
|
||||
ts="",
|
||||
channel_values=cv,
|
||||
channel_versions=cvs,
|
||||
versions_seen={},
|
||||
updated_channels=None,
|
||||
)
|
||||
parent_cfg = await saver.aput(config, cp, generate_metadata(step=step), cvs)
|
||||
configs.append(parent_cfg)
|
||||
if step != 1:
|
||||
await saver.aput_writes(parent_cfg, [("ch", step)], str(uuid4()))
|
||||
|
||||
head = configs[-1]
|
||||
result = await saver.aget_delta_channel_history(config=head, channels=["ch"])
|
||||
# Seed should be the plain value from step 1
|
||||
assert "seed" in result["ch"], "Expected seed from migration plain value at step 1"
|
||||
seed = result["ch"]["seed"]
|
||||
assert seed == [10, 20, 30], f"Expected plain value [10,20,30], got {seed}"
|
||||
# Writes should be from step 2 only (between seed at step 1 and head's parent step 2)
|
||||
writes = result["ch"]["writes"]
|
||||
values = [w[2] for w in writes]
|
||||
assert values == [2], f"Expected [2], got {values}"
|
||||
|
||||
|
||||
ALL_DELTA_CHANNEL_HISTORY_TESTS = [
|
||||
test_history_returns_writes_oldest_first,
|
||||
test_history_seed_is_nearest_snapshot,
|
||||
test_history_excludes_target_pending_writes,
|
||||
test_history_multi_channel,
|
||||
test_history_empty_channels_returns_empty,
|
||||
test_history_walk_to_root_no_seed,
|
||||
test_history_migration_plain_value_as_seed,
|
||||
]
|
||||
|
||||
|
||||
async def run_delta_channel_history_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all delta_channel_history tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_DELTA_CHANNEL_HISTORY_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("delta_channel_history", test_fn.__name__, True, None)
|
||||
except Exception:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {traceback.format_exc()}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"delta_channel_history",
|
||||
test_fn.__name__,
|
||||
False,
|
||||
traceback.format_exc(),
|
||||
)
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,253 @@
|
||||
"""GET_TUPLE capability tests — aget_tuple retrieval."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def test_get_tuple_nonexistent_returns_none(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Missing thread returns None."""
|
||||
config = generate_config(str(uuid4()))
|
||||
tup = await saver.aget_tuple(config)
|
||||
assert tup is None
|
||||
|
||||
|
||||
async def test_get_tuple_latest_when_no_checkpoint_id(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Returns newest checkpoint when no checkpoint_id in config."""
|
||||
tid = str(uuid4())
|
||||
ids = []
|
||||
parent_cfg = None
|
||||
for i in range(3):
|
||||
config = generate_config(tid)
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
parent_cfg = await saver.aput(config, cp, generate_metadata(step=i), {})
|
||||
ids.append(cp["id"])
|
||||
|
||||
# Get without checkpoint_id — should return the latest
|
||||
tup = await saver.aget_tuple(generate_config(tid))
|
||||
assert tup is not None
|
||||
assert tup.checkpoint["id"] == ids[-1]
|
||||
assert tup.metadata["step"] == 2, (
|
||||
f"Expected latest step=2, got {tup.metadata['step']}"
|
||||
)
|
||||
|
||||
|
||||
async def test_get_tuple_specific_checkpoint_id(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Returns exact match when checkpoint_id specified."""
|
||||
tid = str(uuid4())
|
||||
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint()
|
||||
stored1 = await saver.aput(config1, cp1, generate_metadata(step=0), {})
|
||||
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint()
|
||||
await saver.aput(config2, cp2, generate_metadata(step=1), {})
|
||||
|
||||
# Fetch the first one specifically
|
||||
tup = await saver.aget_tuple(stored1)
|
||||
assert tup is not None
|
||||
assert tup.checkpoint["id"] == cp1["id"]
|
||||
|
||||
|
||||
async def test_get_tuple_config_structure(saver: BaseCheckpointSaver) -> None:
|
||||
"""tuple.config has thread_id, checkpoint_ns, checkpoint_id."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
conf = tup.config["configurable"]
|
||||
assert conf["thread_id"] == tid
|
||||
assert conf.get("checkpoint_ns", "") == "", (
|
||||
f"Expected checkpoint_ns='', got {conf.get('checkpoint_ns')!r}"
|
||||
)
|
||||
assert conf["checkpoint_id"] == cp["id"]
|
||||
|
||||
|
||||
async def test_get_tuple_checkpoint_fields(saver: BaseCheckpointSaver) -> None:
|
||||
"""All Checkpoint fields present."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint(channel_values={"k": "v"})
|
||||
cp["channel_versions"] = {"k": 1}
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {"k": 1})
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
c = tup.checkpoint
|
||||
assert c["id"] == cp["id"], f"id mismatch: {c['id']!r} != {cp['id']!r}"
|
||||
assert c["v"] == 1, f"Expected v=1, got {c['v']!r}"
|
||||
assert "ts" in c and c["ts"], "ts should be non-empty"
|
||||
assert c["channel_values"] == {"k": "v"}, f"channel_values: {c['channel_values']!r}"
|
||||
assert "channel_versions" in c
|
||||
assert "versions_seen" in c
|
||||
|
||||
|
||||
async def test_get_tuple_metadata(saver: BaseCheckpointSaver) -> None:
|
||||
"""metadata populated correctly."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata(source="input", step=-1)
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.metadata["source"] == "input"
|
||||
assert tup.metadata["step"] == -1
|
||||
|
||||
|
||||
async def test_get_tuple_parent_config(saver: BaseCheckpointSaver) -> None:
|
||||
"""parent_config when parent exists, None otherwise."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# First checkpoint — no parent
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint()
|
||||
stored1 = await saver.aput(config1, cp1, generate_metadata(step=0), {})
|
||||
|
||||
tup1 = await saver.aget_tuple(stored1)
|
||||
assert tup1 is not None
|
||||
assert tup1.parent_config is None
|
||||
|
||||
# Second checkpoint — has parent
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint()
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {})
|
||||
|
||||
tup2 = await saver.aget_tuple(stored2)
|
||||
assert tup2 is not None
|
||||
assert tup2.parent_config is not None
|
||||
assert (
|
||||
tup2.parent_config["configurable"]["checkpoint_id"]
|
||||
== stored1["configurable"]["checkpoint_id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_get_tuple_pending_writes(saver: BaseCheckpointSaver) -> None:
|
||||
"""pending_writes from put_writes visible."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(stored, [("ch", "val")], task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 1, (
|
||||
f"Expected 1 write, got {len(tup.pending_writes)}"
|
||||
)
|
||||
assert tup.pending_writes[0][0] == task_id, (
|
||||
f"task_id mismatch: {tup.pending_writes[0][0]!r}"
|
||||
)
|
||||
assert tup.pending_writes[0][1] == "ch", (
|
||||
f"channel mismatch: {tup.pending_writes[0][1]!r}"
|
||||
)
|
||||
assert tup.pending_writes[0][2] == "val", (
|
||||
f"value mismatch: {tup.pending_writes[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_get_tuple_respects_namespace(saver: BaseCheckpointSaver) -> None:
|
||||
"""checkpoint_ns filtering."""
|
||||
tid = str(uuid4())
|
||||
|
||||
cfg_root = generate_config(tid, checkpoint_ns="")
|
||||
cp_root = generate_checkpoint()
|
||||
stored_root = await saver.aput(cfg_root, cp_root, generate_metadata(), {})
|
||||
|
||||
cfg_child = generate_config(tid, checkpoint_ns="child:1")
|
||||
cp_child = generate_checkpoint()
|
||||
stored_child = await saver.aput(cfg_child, cp_child, generate_metadata(), {})
|
||||
|
||||
tup_root = await saver.aget_tuple(stored_root)
|
||||
assert tup_root is not None
|
||||
assert tup_root.checkpoint["id"] == cp_root["id"]
|
||||
|
||||
tup_child = await saver.aget_tuple(stored_child)
|
||||
assert tup_child is not None
|
||||
assert tup_child.checkpoint["id"] == cp_child["id"]
|
||||
|
||||
|
||||
async def test_get_tuple_nonexistent_checkpoint_id(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Specific but missing checkpoint_id returns None."""
|
||||
tid = str(uuid4())
|
||||
nonexistent_id = str(uuid4())
|
||||
# Put one checkpoint so the thread exists
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
# Ask for a non-existent checkpoint_id
|
||||
bad_cfg = generate_config(tid, checkpoint_id=nonexistent_id)
|
||||
tup = await saver.aget_tuple(bad_cfg)
|
||||
assert tup is None
|
||||
|
||||
|
||||
ALL_GET_TUPLE_TESTS = [
|
||||
test_get_tuple_nonexistent_returns_none,
|
||||
test_get_tuple_latest_when_no_checkpoint_id,
|
||||
test_get_tuple_specific_checkpoint_id,
|
||||
test_get_tuple_config_structure,
|
||||
test_get_tuple_checkpoint_fields,
|
||||
test_get_tuple_metadata,
|
||||
test_get_tuple_parent_config,
|
||||
test_get_tuple_pending_writes,
|
||||
test_get_tuple_respects_namespace,
|
||||
test_get_tuple_nonexistent_checkpoint_id,
|
||||
]
|
||||
|
||||
|
||||
async def run_get_tuple_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all get_tuple tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_GET_TUPLE_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("get_tuple", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"get_tuple", test_fn.__name__, False, traceback.format_exc()
|
||||
)
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,384 @@
|
||||
"""LIST capability tests — alist with various filters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from typing import cast
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def _setup_list_data(saver: BaseCheckpointSaver) -> dict:
|
||||
"""Populate saver with test data for list tests. Returns lookup info."""
|
||||
tid = str(uuid4())
|
||||
ids = []
|
||||
parent_cfg = None
|
||||
for i in range(4):
|
||||
config = generate_config(tid)
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
source = "input" if i % 2 == 0 else "loop"
|
||||
md = generate_metadata(source=source, step=i)
|
||||
parent_cfg = await saver.aput(config, cp, md, {})
|
||||
ids.append(cp["id"])
|
||||
|
||||
return {
|
||||
"thread_id": tid,
|
||||
"checkpoint_ids": ids,
|
||||
"latest_config": parent_cfg,
|
||||
}
|
||||
|
||||
|
||||
async def test_list_all(saver: BaseCheckpointSaver) -> None:
|
||||
"""No filters returns all checkpoints for the thread."""
|
||||
data = await _setup_list_data(saver)
|
||||
tid = data["thread_id"]
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 4
|
||||
|
||||
|
||||
async def test_list_by_thread(saver: BaseCheckpointSaver) -> None:
|
||||
"""Filter by thread_id — other threads not returned."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
# List for a non-existent thread
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(str(uuid4()))):
|
||||
results.append(tup)
|
||||
assert len(results) == 0
|
||||
|
||||
# List for actual thread
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(data["thread_id"])):
|
||||
results.append(tup)
|
||||
assert len(results) == 4
|
||||
|
||||
|
||||
async def test_list_by_namespace(saver: BaseCheckpointSaver) -> None:
|
||||
"""Filter by checkpoint_ns."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# Root namespace
|
||||
cfg1 = generate_config(tid, checkpoint_ns="")
|
||||
cp1 = generate_checkpoint()
|
||||
await saver.aput(cfg1, cp1, generate_metadata(), {})
|
||||
|
||||
# Child namespace
|
||||
cfg2 = generate_config(tid, checkpoint_ns="child:1")
|
||||
cp2 = generate_checkpoint()
|
||||
await saver.aput(cfg2, cp2, generate_metadata(), {})
|
||||
|
||||
root_results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns="")):
|
||||
root_results.append(tup)
|
||||
assert len(root_results) == 1
|
||||
|
||||
child_results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns="child:1")):
|
||||
child_results.append(tup)
|
||||
assert len(child_results) == 1
|
||||
|
||||
|
||||
async def test_list_ordering(saver: BaseCheckpointSaver) -> None:
|
||||
"""Newest first (descending checkpoint_id)."""
|
||||
data = await _setup_list_data(saver)
|
||||
ids = data["checkpoint_ids"]
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(data["thread_id"])):
|
||||
results.append(tup.checkpoint["id"])
|
||||
|
||||
# Should be in reverse order (newest first)
|
||||
assert results == list(reversed(ids))
|
||||
|
||||
|
||||
async def test_list_metadata_filter_single_key(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""filter={'source': 'input'} returns only input checkpoints."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
filter={"source": "input"},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 2, (
|
||||
f"Expected 2 'input' checkpoints (steps 0,2), got {len(results)}"
|
||||
)
|
||||
for tup in results:
|
||||
assert tup.metadata["source"] == "input"
|
||||
|
||||
|
||||
async def test_list_metadata_filter_step(saver: BaseCheckpointSaver) -> None:
|
||||
"""filter={'step': 1} returns matching checkpoints."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
filter={"step": 1},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].metadata["step"] == 1
|
||||
|
||||
|
||||
async def test_list_before(saver: BaseCheckpointSaver) -> None:
|
||||
"""Pagination cursor — only checkpoints before the given one."""
|
||||
data = await _setup_list_data(saver)
|
||||
ids = data["checkpoint_ids"]
|
||||
|
||||
# Use the 3rd checkpoint as the 'before' cursor (index 2)
|
||||
before_cfg = generate_config(data["thread_id"], checkpoint_id=ids[2])
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
before=before_cfg,
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
# Should only include checkpoints before ids[2]
|
||||
result_ids = [t.checkpoint["id"] for t in results]
|
||||
assert ids[2] not in result_ids
|
||||
assert ids[3] not in result_ids
|
||||
assert set(result_ids) == {ids[0], ids[1]}, (
|
||||
f"Expected {{ids[0], ids[1]}}, got {set(result_ids)}"
|
||||
)
|
||||
|
||||
|
||||
async def test_list_limit(saver: BaseCheckpointSaver) -> None:
|
||||
"""limit=1, limit=N."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(data["thread_id"]), limit=1):
|
||||
results.append(tup)
|
||||
assert len(results) == 1
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(data["thread_id"]), limit=2):
|
||||
results.append(tup)
|
||||
assert len(results) == 2
|
||||
|
||||
|
||||
async def test_list_limit_plus_before(saver: BaseCheckpointSaver) -> None:
|
||||
"""Pagination with limit."""
|
||||
data = await _setup_list_data(saver)
|
||||
ids = data["checkpoint_ids"]
|
||||
|
||||
before_cfg = generate_config(data["thread_id"], checkpoint_id=ids[3])
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
before=before_cfg,
|
||||
limit=1,
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].checkpoint["id"] == ids[2]
|
||||
|
||||
|
||||
async def test_list_combined_thread_and_filter(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""thread_id + metadata filter combined."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
filter={"source": "loop"},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 2, (
|
||||
f"Expected 2 'loop' checkpoints (steps 1,3), got {len(results)}"
|
||||
)
|
||||
for tup in results:
|
||||
assert tup.metadata["source"] == "loop"
|
||||
|
||||
|
||||
async def test_list_empty_result(saver: BaseCheckpointSaver) -> None:
|
||||
"""No matches returns empty."""
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(str(uuid4())),
|
||||
filter={"source": "nonexistent"},
|
||||
):
|
||||
results.append(tup)
|
||||
assert len(results) == 0
|
||||
|
||||
|
||||
async def test_list_includes_pending_writes(saver: BaseCheckpointSaver) -> None:
|
||||
"""pending_writes in listed tuples."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
await saver.aput_writes(stored, [("ch", "val")], str(uuid4()))
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].pending_writes is not None
|
||||
assert len(results[0].pending_writes) == 1, (
|
||||
f"Expected 1 write, got {len(results[0].pending_writes)}"
|
||||
)
|
||||
assert results[0].pending_writes[0][1] == "ch", (
|
||||
f"channel mismatch: {results[0].pending_writes[0][1]!r}"
|
||||
)
|
||||
assert results[0].pending_writes[0][2] == "val", (
|
||||
f"value mismatch: {results[0].pending_writes[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_list_multiple_namespaces(saver: BaseCheckpointSaver) -> None:
|
||||
"""Root namespace checkpoint listed correctly."""
|
||||
tid = str(uuid4())
|
||||
|
||||
for ns in ["", "child:1", "child:2"]:
|
||||
cfg = generate_config(tid, checkpoint_ns=ns)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(cfg, cp, generate_metadata(), {})
|
||||
|
||||
# List with root namespace filter — should return exactly the root checkpoint
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns="")):
|
||||
results.append(tup)
|
||||
assert len(results) == 1, f"Expected 1 root checkpoint, got {len(results)}"
|
||||
|
||||
|
||||
async def test_list_metadata_filter_multiple_keys(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""filter with multiple keys — all must match."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# Create checkpoints with different metadata combos
|
||||
for source, step in [("input", 1), ("loop", 1), ("input", 2)]:
|
||||
cfg = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(cfg, cp, generate_metadata(source=source, step=step), {})
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(tid),
|
||||
filter={"source": "input", "step": 2},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1, (
|
||||
f"Expected 1 match for source=input+step=2, got {len(results)}"
|
||||
)
|
||||
assert results[0].metadata["source"] == "input"
|
||||
assert results[0].metadata["step"] == 2
|
||||
|
||||
|
||||
async def test_list_metadata_filter_no_match(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Multi-key filter that matches nothing returns empty."""
|
||||
data = await _setup_list_data(saver)
|
||||
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(data["thread_id"]),
|
||||
filter={"source": "update", "step": 99},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 0
|
||||
|
||||
|
||||
async def test_list_metadata_custom_keys(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Custom (non-standard) metadata keys are filterable."""
|
||||
tid = str(uuid4())
|
||||
|
||||
cfg = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
await saver.aput(cfg, cp, generate_metadata(score=42, run_id="run-abc"), {})
|
||||
|
||||
cfg2 = generate_config(tid)
|
||||
cp2 = generate_checkpoint()
|
||||
await saver.aput(cfg2, cp2, generate_metadata(score=99, run_id="run-xyz"), {})
|
||||
|
||||
# Filter by custom key
|
||||
results = []
|
||||
async for tup in saver.alist(
|
||||
generate_config(tid),
|
||||
filter={"score": 42},
|
||||
):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1
|
||||
metadata = cast(dict[str, object], results[0].metadata)
|
||||
assert metadata["score"] == 42
|
||||
assert metadata["run_id"] == "run-abc"
|
||||
|
||||
|
||||
ALL_LIST_TESTS = [
|
||||
test_list_all,
|
||||
test_list_by_thread,
|
||||
test_list_by_namespace,
|
||||
test_list_ordering,
|
||||
test_list_metadata_filter_single_key,
|
||||
test_list_metadata_filter_step,
|
||||
test_list_metadata_filter_multiple_keys,
|
||||
test_list_metadata_filter_no_match,
|
||||
test_list_metadata_custom_keys,
|
||||
test_list_before,
|
||||
test_list_limit,
|
||||
test_list_limit_plus_before,
|
||||
test_list_combined_thread_and_filter,
|
||||
test_list_empty_result,
|
||||
test_list_includes_pending_writes,
|
||||
test_list_multiple_namespaces,
|
||||
]
|
||||
|
||||
|
||||
async def run_list_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all list tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_LIST_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("list", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result("list", test_fn.__name__, False, traceback.format_exc())
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,217 @@
|
||||
"""PRUNE capability tests — aprune(strategy)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def _setup_thread(saver: BaseCheckpointSaver, tid: str, n: int = 3) -> list[dict]:
|
||||
"""Create n checkpoints on tid. Returns stored configs."""
|
||||
stored = []
|
||||
parent_cfg = None
|
||||
for i in range(n):
|
||||
config = generate_config(tid)
|
||||
if parent_cfg:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
parent_cfg = await saver.aput(config, cp, generate_metadata(step=i), {})
|
||||
stored.append(parent_cfg)
|
||||
return stored
|
||||
|
||||
|
||||
async def test_prune_keep_latest_single_thread(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Only latest checkpoint survives."""
|
||||
tid = str(uuid4())
|
||||
configs = await _setup_thread(saver, tid, n=4)
|
||||
|
||||
await saver.aprune([tid], strategy="keep_latest")
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
|
||||
assert len(results) == 1
|
||||
assert (
|
||||
results[0].config["configurable"]["checkpoint_id"]
|
||||
== configs[-1]["configurable"]["checkpoint_id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_prune_keep_latest_multiple_threads(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Each thread keeps its latest."""
|
||||
tid1, tid2 = str(uuid4()), str(uuid4())
|
||||
c1 = await _setup_thread(saver, tid1, n=3)
|
||||
c2 = await _setup_thread(saver, tid2, n=2)
|
||||
|
||||
await saver.aprune([tid1, tid2], strategy="keep_latest")
|
||||
for tid, expected_last in [(tid1, c1[-1]), (tid2, c2[-1])]:
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
assert len(results) == 1
|
||||
assert (
|
||||
results[0].config["configurable"]["checkpoint_id"]
|
||||
== expected_last["configurable"]["checkpoint_id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_prune_keep_latest_across_namespaces(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Latest per namespace kept."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# Root namespace: 3 checkpoints
|
||||
parent = None
|
||||
for i in range(3):
|
||||
cfg = generate_config(tid, checkpoint_ns="")
|
||||
if parent:
|
||||
cfg["configurable"]["checkpoint_id"] = parent["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
parent = await saver.aput(cfg, cp, generate_metadata(step=i), {})
|
||||
root_latest = parent
|
||||
|
||||
# Child namespace: 2 checkpoints
|
||||
parent = None
|
||||
for i in range(2):
|
||||
cfg = generate_config(tid, checkpoint_ns="child:1")
|
||||
if parent:
|
||||
cfg["configurable"]["checkpoint_id"] = parent["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
parent = await saver.aput(cfg, cp, generate_metadata(step=i), {})
|
||||
child_latest = parent
|
||||
|
||||
assert root_latest is not None
|
||||
assert child_latest is not None
|
||||
await saver.aprune([tid], strategy="keep_latest")
|
||||
for ns, expected in [("", root_latest), ("child:1", child_latest)]:
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid, checkpoint_ns=ns)):
|
||||
results.append(tup)
|
||||
assert len(results) == 1
|
||||
assert (
|
||||
results[0].config["configurable"]["checkpoint_id"]
|
||||
== expected["configurable"]["checkpoint_id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_prune_keep_latest_preserves_writes(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Latest checkpoint's writes kept."""
|
||||
tid = str(uuid4())
|
||||
configs = await _setup_thread(saver, tid, n=3)
|
||||
|
||||
# Add writes to the latest
|
||||
await saver.aput_writes(configs[-1], [("ch", "val")], str(uuid4()))
|
||||
|
||||
await saver.aprune([tid], strategy="keep_latest")
|
||||
tup = await saver.aget_tuple(generate_config(tid))
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 1, (
|
||||
f"Expected 1 write, got {len(tup.pending_writes)}"
|
||||
)
|
||||
assert tup.pending_writes[0][1] == "ch", (
|
||||
f"channel mismatch: {tup.pending_writes[0][1]!r}"
|
||||
)
|
||||
assert tup.pending_writes[0][2] == "val", (
|
||||
f"value mismatch: {tup.pending_writes[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_prune_delete_all(saver: BaseCheckpointSaver) -> None:
|
||||
"""delete_all strategy removes everything."""
|
||||
tid = str(uuid4())
|
||||
await _setup_thread(saver, tid, n=3)
|
||||
|
||||
await saver.aprune([tid], strategy="delete")
|
||||
results = []
|
||||
async for tup in saver.alist(generate_config(tid)):
|
||||
results.append(tup)
|
||||
assert len(results) == 0
|
||||
|
||||
|
||||
async def test_prune_preserves_other_threads(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Unlisted threads untouched."""
|
||||
tid1, tid2 = str(uuid4()), str(uuid4())
|
||||
await _setup_thread(saver, tid1, n=3)
|
||||
await _setup_thread(saver, tid2, n=2)
|
||||
|
||||
# Snapshot tid2 before prune
|
||||
pre_ids = []
|
||||
async for tup in saver.alist(generate_config(tid2)):
|
||||
pre_ids.append(tup.checkpoint["id"])
|
||||
|
||||
await saver.aprune([tid1], strategy="keep_latest")
|
||||
# tid2 should be fully intact — same checkpoint IDs
|
||||
post_ids = []
|
||||
async for tup in saver.alist(generate_config(tid2)):
|
||||
post_ids.append(tup.checkpoint["id"])
|
||||
assert post_ids == pre_ids, f"tid2 changed: {pre_ids} -> {post_ids}"
|
||||
|
||||
|
||||
async def test_prune_empty_list_noop(saver: BaseCheckpointSaver) -> None:
|
||||
"""Empty thread_ids no error."""
|
||||
await saver.aprune([], strategy="keep_latest")
|
||||
|
||||
|
||||
async def test_prune_nonexistent_noop(saver: BaseCheckpointSaver) -> None:
|
||||
"""Missing threads no error."""
|
||||
await saver.aprune([str(uuid4())], strategy="keep_latest")
|
||||
|
||||
|
||||
ALL_PRUNE_TESTS = [
|
||||
test_prune_keep_latest_single_thread,
|
||||
test_prune_keep_latest_multiple_threads,
|
||||
test_prune_keep_latest_across_namespaces,
|
||||
test_prune_keep_latest_preserves_writes,
|
||||
test_prune_delete_all,
|
||||
test_prune_preserves_other_threads,
|
||||
test_prune_empty_list_noop,
|
||||
test_prune_nonexistent_noop,
|
||||
]
|
||||
|
||||
|
||||
async def run_prune_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all prune tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_PRUNE_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("prune", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result("prune", test_fn.__name__, False, traceback.format_exc())
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,411 @@
|
||||
"""PUT capability tests — aput + aget_tuple round-trip."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import (
|
||||
BaseCheckpointSaver,
|
||||
ChannelVersions,
|
||||
)
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def test_put_returns_config(saver: BaseCheckpointSaver) -> None:
|
||||
"""aput returns a RunnableConfig with thread_id, checkpoint_ns, checkpoint_id."""
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(channel_values={"k": "v"})
|
||||
cp["channel_versions"] = {"k": 1}
|
||||
md = generate_metadata()
|
||||
|
||||
result = await saver.aput(config, cp, md, {"k": 1})
|
||||
|
||||
assert "configurable" in result
|
||||
conf = result["configurable"]
|
||||
assert "thread_id" in conf
|
||||
assert "checkpoint_ns" in conf
|
||||
assert "checkpoint_id" in conf
|
||||
assert conf["checkpoint_id"] == cp["id"]
|
||||
|
||||
|
||||
async def test_put_roundtrip(saver: BaseCheckpointSaver) -> None:
|
||||
"""put then get_tuple returns identical checkpoint."""
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(channel_values={"msg": "hello"})
|
||||
cp["channel_versions"] = {"msg": 1}
|
||||
md = generate_metadata(source="input", step=-1)
|
||||
|
||||
stored_config = await saver.aput(config, cp, md, {"msg": 1})
|
||||
|
||||
tup = await saver.aget_tuple(stored_config)
|
||||
assert tup is not None
|
||||
assert tup.checkpoint["id"] == cp["id"]
|
||||
assert tup.checkpoint["channel_values"] == {"msg": "hello"}
|
||||
|
||||
|
||||
async def test_put_preserves_channel_values(saver: BaseCheckpointSaver) -> None:
|
||||
"""Various types (str, int, list, dict, bytes, None) round-trip correctly."""
|
||||
values: dict[str, Any] = {
|
||||
"str_val": "hello",
|
||||
"int_val": 42,
|
||||
"list_val": [1, 2, 3],
|
||||
"dict_val": {"nested": True},
|
||||
}
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(channel_values=values)
|
||||
versions: ChannelVersions = {k: 1 for k in values}
|
||||
cp["channel_versions"] = versions
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, versions)
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
for k, v in values.items():
|
||||
assert tup.checkpoint["channel_values"].get(k) == v, (
|
||||
f"channel_values[{k}]: expected {v!r}, got {tup.checkpoint['channel_values'].get(k)!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_preserves_channel_versions(saver: BaseCheckpointSaver) -> None:
|
||||
"""ChannelVersions round-trip correctly."""
|
||||
versions: ChannelVersions = {"a": 1, "b": 2}
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(
|
||||
channel_values={"a": "x", "b": "y"}, channel_versions=versions
|
||||
)
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, versions)
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
# Compare version values — checkpointers may convert int to str
|
||||
for k, expected in versions.items():
|
||||
actual = tup.checkpoint["channel_versions"].get(k)
|
||||
assert actual is not None, f"channel_versions[{k}] missing"
|
||||
assert str(actual).split(".")[0] == str(expected).split(".")[0], (
|
||||
f"channel_versions[{k}]: expected {expected!r}, got {actual!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_preserves_versions_seen(saver: BaseCheckpointSaver) -> None:
|
||||
"""versions_seen dict round-trips."""
|
||||
vs: dict[str, ChannelVersions] = {"node1": {"ch": 1}, "node2": {"ch": 2}}
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(versions_seen=vs)
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
for node in vs:
|
||||
assert node in tup.checkpoint["versions_seen"], f"versions_seen[{node}] missing"
|
||||
|
||||
|
||||
async def test_put_preserves_metadata(saver: BaseCheckpointSaver) -> None:
|
||||
"""Metadata source, step, parents, and custom keys round-trip."""
|
||||
md = generate_metadata(source="loop", step=3, custom_key="custom_value")
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.metadata["source"] == "loop"
|
||||
assert tup.metadata["step"] == 3
|
||||
assert tup.metadata.get("custom_key") == "custom_value"
|
||||
|
||||
|
||||
async def test_put_root_namespace(saver: BaseCheckpointSaver) -> None:
|
||||
"""checkpoint_ns='' works."""
|
||||
config = generate_config(checkpoint_ns="")
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.config["configurable"].get("checkpoint_ns", "") == ""
|
||||
|
||||
|
||||
async def test_put_child_namespace(saver: BaseCheckpointSaver) -> None:
|
||||
"""checkpoint_ns='child:abc' works."""
|
||||
config = generate_config(checkpoint_ns="child:abc")
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.config["configurable"]["checkpoint_ns"] == "child:abc"
|
||||
|
||||
|
||||
async def test_put_default_namespace(saver: BaseCheckpointSaver) -> None:
|
||||
"""Config without checkpoint_ns defaults to ''."""
|
||||
tid = str(uuid4())
|
||||
config = {"configurable": {"thread_id": tid, "checkpoint_ns": ""}}
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
|
||||
|
||||
async def test_put_multiple_checkpoints_same_thread(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Sequential puts on same thread, all retrievable."""
|
||||
tid = str(uuid4())
|
||||
ids = []
|
||||
parent_cfg = None
|
||||
for i in range(3):
|
||||
config = generate_config(tid)
|
||||
if parent_cfg is not None:
|
||||
config["configurable"]["checkpoint_id"] = parent_cfg["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata(step=i)
|
||||
parent_cfg = await saver.aput(config, cp, md, {})
|
||||
ids.append(cp["id"])
|
||||
|
||||
# All three should be retrievable
|
||||
for cid in ids:
|
||||
cfg = generate_config(tid, checkpoint_id=cid)
|
||||
tup = await saver.aget_tuple(cfg)
|
||||
assert tup is not None, f"checkpoint {cid} not found"
|
||||
assert tup.checkpoint["id"] == cid
|
||||
|
||||
|
||||
async def test_put_multiple_threads_isolated(saver: BaseCheckpointSaver) -> None:
|
||||
"""Different thread_ids don't interfere."""
|
||||
tid1, tid2 = str(uuid4()), str(uuid4())
|
||||
|
||||
config1 = generate_config(tid1)
|
||||
cp1 = generate_checkpoint(channel_values={"x": "thread1"})
|
||||
cp1["channel_versions"] = {"x": 1}
|
||||
await saver.aput(config1, cp1, generate_metadata(), {"x": 1})
|
||||
|
||||
config2 = generate_config(tid2)
|
||||
cp2 = generate_checkpoint(channel_values={"x": "thread2"})
|
||||
cp2["channel_versions"] = {"x": 1}
|
||||
await saver.aput(config2, cp2, generate_metadata(), {"x": 1})
|
||||
|
||||
tup1 = await saver.aget_tuple(generate_config(tid1))
|
||||
tup2 = await saver.aget_tuple(generate_config(tid2))
|
||||
assert tup1 is not None and tup2 is not None
|
||||
assert tup1.checkpoint["channel_values"]["x"] == "thread1"
|
||||
assert tup2.checkpoint["channel_values"]["x"] == "thread2"
|
||||
|
||||
|
||||
async def test_put_parent_config(saver: BaseCheckpointSaver) -> None:
|
||||
"""parent checkpoint_id tracked correctly."""
|
||||
tid = str(uuid4())
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint()
|
||||
stored1 = await saver.aput(config1, cp1, generate_metadata(step=0), {})
|
||||
|
||||
# Second checkpoint — its config carries the parent checkpoint_id
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint()
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {})
|
||||
|
||||
tup = await saver.aget_tuple(stored2)
|
||||
assert tup is not None
|
||||
assert tup.parent_config is not None
|
||||
assert (
|
||||
tup.parent_config["configurable"]["checkpoint_id"]
|
||||
== stored1["configurable"]["checkpoint_id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_put_incremental_channel_update(saver: BaseCheckpointSaver) -> None:
|
||||
"""Only updated channels need new blobs; unchanged channels loaded from prior versions."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# Checkpoint 1: both channels are new
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint(
|
||||
channel_values={"a": "v1", "b": "v2"},
|
||||
channel_versions={"a": 1, "b": 1},
|
||||
)
|
||||
stored1 = await saver.aput(
|
||||
config1, cp1, generate_metadata(step=0), {"a": 1, "b": 1}
|
||||
)
|
||||
|
||||
# Checkpoint 2: only 'a' is updated
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint(
|
||||
channel_values={"a": "v1_updated", "b": "v2"},
|
||||
channel_versions={"a": 2, "b": 1},
|
||||
)
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {"a": 2})
|
||||
|
||||
# cp2 should reconstruct full channel_values from blobs at mixed versions
|
||||
tup2 = await saver.aget_tuple(stored2)
|
||||
assert tup2 is not None
|
||||
assert tup2.checkpoint["channel_values"].get("a") == "v1_updated", (
|
||||
f"a: expected 'v1_updated', got {tup2.checkpoint['channel_values'].get('a')!r}"
|
||||
)
|
||||
assert tup2.checkpoint["channel_values"].get("b") == "v2", (
|
||||
f"b: expected 'v2', got {tup2.checkpoint['channel_values'].get('b')!r}"
|
||||
)
|
||||
|
||||
# cp1 should still return original values
|
||||
tup1 = await saver.aget_tuple(stored1)
|
||||
assert tup1 is not None
|
||||
assert tup1.checkpoint["channel_values"].get("a") == "v1"
|
||||
assert tup1.checkpoint["channel_values"].get("b") == "v2"
|
||||
|
||||
|
||||
async def test_put_new_channel_added(saver: BaseCheckpointSaver) -> None:
|
||||
"""A channel that appears for the first time in a later checkpoint."""
|
||||
tid = str(uuid4())
|
||||
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint(
|
||||
channel_values={"a": "v1"},
|
||||
channel_versions={"a": 1},
|
||||
)
|
||||
stored1 = await saver.aput(config1, cp1, generate_metadata(step=0), {"a": 1})
|
||||
|
||||
# Checkpoint 2: 'b' is brand new, 'a' is unchanged
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint(
|
||||
channel_values={"a": "v1", "b": "new_channel"},
|
||||
channel_versions={"a": 1, "b": 1},
|
||||
)
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {"b": 1})
|
||||
|
||||
tup2 = await saver.aget_tuple(stored2)
|
||||
assert tup2 is not None
|
||||
assert tup2.checkpoint["channel_values"].get("a") == "v1", (
|
||||
f"a: expected 'v1', got {tup2.checkpoint['channel_values'].get('a')!r}"
|
||||
)
|
||||
assert tup2.checkpoint["channel_values"].get("b") == "new_channel", (
|
||||
f"b: expected 'new_channel', got {tup2.checkpoint['channel_values'].get('b')!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_channel_removed(saver: BaseCheckpointSaver) -> None:
|
||||
"""Channel no longer in channel_versions should not appear in loaded values."""
|
||||
tid = str(uuid4())
|
||||
|
||||
config1 = generate_config(tid)
|
||||
cp1 = generate_checkpoint(
|
||||
channel_values={"a": "v1", "b": "v2"},
|
||||
channel_versions={"a": 1, "b": 1},
|
||||
)
|
||||
stored1 = await saver.aput(
|
||||
config1, cp1, generate_metadata(step=0), {"a": 1, "b": 1}
|
||||
)
|
||||
|
||||
# Checkpoint 2: 'b' dropped from channel_versions
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint(
|
||||
channel_values={"a": "v1_updated"},
|
||||
channel_versions={"a": 2},
|
||||
)
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {"a": 2})
|
||||
|
||||
tup2 = await saver.aget_tuple(stored2)
|
||||
assert tup2 is not None
|
||||
assert tup2.checkpoint["channel_values"].get("a") == "v1_updated"
|
||||
assert "b" not in tup2.checkpoint["channel_values"], (
|
||||
f"'b' should not be present, got {tup2.checkpoint['channel_values']}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_preserves_run_id(saver: BaseCheckpointSaver) -> None:
|
||||
"""run_id in metadata round-trips correctly."""
|
||||
run_id = str(uuid4())
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint()
|
||||
md = generate_metadata(source="loop", step=0, run_id=run_id)
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.metadata.get("run_id") == run_id, (
|
||||
f"run_id: expected {run_id!r}, got {tup.metadata.get('run_id')!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_preserves_versions_seen_values(saver: BaseCheckpointSaver) -> None:
|
||||
"""versions_seen values (not just keys) round-trip correctly."""
|
||||
vs: dict[str, ChannelVersions] = {
|
||||
"node1": {"ch_a": 1, "ch_b": 2},
|
||||
"node2": {"ch_a": 3},
|
||||
}
|
||||
config = generate_config()
|
||||
cp = generate_checkpoint(versions_seen=vs)
|
||||
md = generate_metadata()
|
||||
|
||||
stored = await saver.aput(config, cp, md, {})
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
for node, expected_versions in vs.items():
|
||||
assert node in tup.checkpoint["versions_seen"], f"versions_seen[{node}] missing"
|
||||
actual_versions = tup.checkpoint["versions_seen"][node]
|
||||
for ch, expected_v in expected_versions.items():
|
||||
actual_v = actual_versions.get(ch)
|
||||
assert actual_v is not None, f"versions_seen[{node}][{ch}] missing"
|
||||
assert str(actual_v).split(".")[0] == str(expected_v).split(".")[0], (
|
||||
f"versions_seen[{node}][{ch}]: expected {expected_v!r}, got {actual_v!r}"
|
||||
)
|
||||
|
||||
|
||||
ALL_PUT_TESTS = [
|
||||
test_put_returns_config,
|
||||
test_put_roundtrip,
|
||||
test_put_preserves_channel_values,
|
||||
test_put_preserves_channel_versions,
|
||||
test_put_preserves_versions_seen,
|
||||
test_put_preserves_metadata,
|
||||
test_put_root_namespace,
|
||||
test_put_child_namespace,
|
||||
test_put_default_namespace,
|
||||
test_put_multiple_checkpoints_same_thread,
|
||||
test_put_multiple_threads_isolated,
|
||||
test_put_parent_config,
|
||||
test_put_incremental_channel_update,
|
||||
test_put_new_channel_added,
|
||||
test_put_channel_removed,
|
||||
test_put_preserves_run_id,
|
||||
test_put_preserves_versions_seen_values,
|
||||
]
|
||||
|
||||
|
||||
async def run_put_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all put tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_PUT_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("put", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result("put", test_fn.__name__, False, traceback.format_exc())
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,302 @@
|
||||
"""PUT_WRITES capability tests — aput_writes + pending_writes retrieval."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
|
||||
from langgraph.checkpoint.conformance.test_utils import (
|
||||
generate_checkpoint,
|
||||
generate_config,
|
||||
generate_metadata,
|
||||
)
|
||||
|
||||
|
||||
async def test_put_writes_basic(saver: BaseCheckpointSaver) -> None:
|
||||
"""Write stored, visible in aget_tuple pending_writes."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(stored, [("channel1", "value1")], task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
# Verify exact write tuple: (task_id, channel, value)
|
||||
matching = [w for w in tup.pending_writes if w[0] == task_id and w[1] == "channel1"]
|
||||
assert len(matching) == 1, f"Expected 1 write, got {len(matching)}"
|
||||
assert matching[0][2] == "value1", f"Value mismatch: {matching[0][2]!r}"
|
||||
|
||||
|
||||
async def test_put_writes_multiple_writes_same_task(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Multiple (channel, value) pairs in a single call."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
writes = [("ch1", "v1"), ("ch2", "v2"), ("ch3", "v3")]
|
||||
await saver.aput_writes(stored, writes, task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 3, (
|
||||
f"Expected 3 writes, got {len(tup.pending_writes)}"
|
||||
)
|
||||
channels = {w[1] for w in tup.pending_writes}
|
||||
assert channels == {"ch1", "ch2", "ch3"}, f"Expected exact channels, got {channels}"
|
||||
# Verify values per channel
|
||||
for expected_ch, expected_val in writes:
|
||||
match = [
|
||||
w for w in tup.pending_writes if w[0] == task_id and w[1] == expected_ch
|
||||
]
|
||||
assert len(match) == 1, f"Expected 1 write for {expected_ch}, got {len(match)}"
|
||||
assert match[0][2] == expected_val, (
|
||||
f"Value mismatch for {expected_ch}: {match[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_writes_multiple_tasks(saver: BaseCheckpointSaver) -> None:
|
||||
"""Different task_ids produce separate writes."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
t1, t2 = str(uuid4()), str(uuid4())
|
||||
await saver.aput_writes(stored, [("ch", "from_t1")], t1)
|
||||
await saver.aput_writes(stored, [("ch", "from_t2")], t2)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 2, (
|
||||
f"Expected 2 writes, got {len(tup.pending_writes)}"
|
||||
)
|
||||
# Verify values per task
|
||||
t1_writes = [w for w in tup.pending_writes if w[0] == t1 and w[1] == "ch"]
|
||||
t2_writes = [w for w in tup.pending_writes if w[0] == t2 and w[1] == "ch"]
|
||||
assert len(t1_writes) == 1, f"Expected 1 write from t1, got {len(t1_writes)}"
|
||||
assert len(t2_writes) == 1, f"Expected 1 write from t2, got {len(t2_writes)}"
|
||||
assert t1_writes[0][2] == "from_t1", f"t1 value: {t1_writes[0][2]!r}"
|
||||
assert t2_writes[0][2] == "from_t2", f"t2 value: {t2_writes[0][2]!r}"
|
||||
|
||||
|
||||
async def test_put_writes_preserves_task_id(saver: BaseCheckpointSaver) -> None:
|
||||
"""task_id in pending_writes matches what was passed to aput_writes."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(stored, [("ch", "val")], task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert any(w[0] == task_id for w in tup.pending_writes)
|
||||
|
||||
|
||||
async def test_put_writes_preserves_channel_and_value(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""Channel name + value round-trip."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(stored, [("my_channel", {"data": 123})], task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
match = [w for w in tup.pending_writes if w[0] == task_id and w[1] == "my_channel"]
|
||||
assert len(match) == 1, f"Expected 1 write, got {len(match)}"
|
||||
assert match[0][2] == {"data": 123}, f"Value mismatch: {match[0][2]!r}"
|
||||
|
||||
|
||||
async def test_put_writes_task_path(saver: BaseCheckpointSaver) -> None:
|
||||
"""task_path parameter accepted without error."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
# Should not raise
|
||||
await saver.aput_writes(stored, [("ch", "v")], task_id, task_path="a:b:c")
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 1
|
||||
|
||||
|
||||
async def test_put_writes_idempotent(saver: BaseCheckpointSaver) -> None:
|
||||
"""Duplicate (task_id, idx) doesn't duplicate writes."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(stored, [("ch", "val")], task_id)
|
||||
await saver.aput_writes(stored, [("ch", "val")], task_id)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
assert len(tup.pending_writes) == 1, (
|
||||
f"Expected exactly 1 write total, got {len(tup.pending_writes)}"
|
||||
)
|
||||
# Should not have duplicated
|
||||
matching = [w for w in tup.pending_writes if w[0] == task_id and w[1] == "ch"]
|
||||
assert len(matching) == 1
|
||||
|
||||
|
||||
async def test_put_writes_special_channels(saver: BaseCheckpointSaver) -> None:
|
||||
"""ERROR and INTERRUPT channels handled correctly."""
|
||||
from langgraph.checkpoint.serde.types import ERROR, INTERRUPT
|
||||
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp = generate_checkpoint()
|
||||
stored = await saver.aput(config, cp, generate_metadata(), {})
|
||||
|
||||
task_id = str(uuid4())
|
||||
await saver.aput_writes(
|
||||
stored,
|
||||
[(ERROR, "something went wrong"), (INTERRUPT, {"reason": "human_input"})],
|
||||
task_id,
|
||||
)
|
||||
|
||||
tup = await saver.aget_tuple(stored)
|
||||
assert tup is not None
|
||||
assert tup.pending_writes is not None
|
||||
channels = {w[1] for w in tup.pending_writes}
|
||||
assert ERROR in channels
|
||||
assert INTERRUPT in channels
|
||||
# Verify values
|
||||
err_writes = [w for w in tup.pending_writes if w[0] == task_id and w[1] == ERROR]
|
||||
assert len(err_writes) == 1, f"Expected 1 ERROR write, got {len(err_writes)}"
|
||||
assert err_writes[0][2] == "something went wrong", (
|
||||
f"ERROR value: {err_writes[0][2]!r}"
|
||||
)
|
||||
int_writes = [
|
||||
w for w in tup.pending_writes if w[0] == task_id and w[1] == INTERRUPT
|
||||
]
|
||||
assert len(int_writes) == 1, f"Expected 1 INTERRUPT write, got {len(int_writes)}"
|
||||
assert int_writes[0][2] == {"reason": "human_input"}, (
|
||||
f"INTERRUPT value: {int_writes[0][2]!r}"
|
||||
)
|
||||
|
||||
|
||||
async def test_put_writes_across_namespaces(saver: BaseCheckpointSaver) -> None:
|
||||
"""Writes isolated by checkpoint_ns."""
|
||||
tid = str(uuid4())
|
||||
|
||||
# Root namespace checkpoint + write
|
||||
cfg_root = generate_config(tid, checkpoint_ns="")
|
||||
cp_root = generate_checkpoint()
|
||||
stored_root = await saver.aput(cfg_root, cp_root, generate_metadata(), {})
|
||||
root_task = str(uuid4())
|
||||
await saver.aput_writes(stored_root, [("ch", "root_val")], root_task)
|
||||
|
||||
# Child namespace checkpoint + write
|
||||
cfg_child = generate_config(tid, checkpoint_ns="child:1")
|
||||
cp_child = generate_checkpoint()
|
||||
stored_child = await saver.aput(cfg_child, cp_child, generate_metadata(), {})
|
||||
child_task = str(uuid4())
|
||||
await saver.aput_writes(stored_child, [("ch", "child_val")], child_task)
|
||||
|
||||
# Verify isolation — root should have exactly 1 write with root_val
|
||||
tup_root = await saver.aget_tuple(stored_root)
|
||||
assert tup_root is not None
|
||||
assert tup_root.pending_writes is not None
|
||||
root_ch = [w for w in tup_root.pending_writes if w[1] == "ch"]
|
||||
assert len(root_ch) == 1, f"Expected 1 root write, got {len(root_ch)}"
|
||||
assert root_ch[0][2] == "root_val", f"Root value: {root_ch[0][2]!r}"
|
||||
|
||||
# Child should have exactly 1 write with child_val
|
||||
tup_child = await saver.aget_tuple(stored_child)
|
||||
assert tup_child is not None
|
||||
assert tup_child.pending_writes is not None
|
||||
child_ch = [w for w in tup_child.pending_writes if w[1] == "ch"]
|
||||
assert len(child_ch) == 1, f"Expected 1 child write, got {len(child_ch)}"
|
||||
assert child_ch[0][2] == "child_val", f"Child value: {child_ch[0][2]!r}"
|
||||
|
||||
|
||||
async def test_put_writes_cleared_on_next_checkpoint(
|
||||
saver: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
"""New checkpoint starts with fresh pending_writes."""
|
||||
tid = str(uuid4())
|
||||
config = generate_config(tid)
|
||||
cp1 = generate_checkpoint()
|
||||
stored1 = await saver.aput(config, cp1, generate_metadata(step=0), {})
|
||||
|
||||
await saver.aput_writes(stored1, [("ch", "old_write")], str(uuid4()))
|
||||
|
||||
# New checkpoint
|
||||
config2 = generate_config(tid)
|
||||
config2["configurable"]["checkpoint_id"] = stored1["configurable"]["checkpoint_id"]
|
||||
cp2 = generate_checkpoint()
|
||||
stored2 = await saver.aput(config2, cp2, generate_metadata(step=1), {})
|
||||
|
||||
tup = await saver.aget_tuple(stored2)
|
||||
assert tup is not None
|
||||
# New checkpoint should have no pending writes
|
||||
writes = tup.pending_writes or []
|
||||
assert len(writes) == 0
|
||||
|
||||
|
||||
ALL_PUT_WRITES_TESTS = [
|
||||
test_put_writes_basic,
|
||||
test_put_writes_multiple_writes_same_task,
|
||||
test_put_writes_multiple_tasks,
|
||||
test_put_writes_preserves_task_id,
|
||||
test_put_writes_preserves_channel_and_value,
|
||||
test_put_writes_task_path,
|
||||
test_put_writes_idempotent,
|
||||
test_put_writes_special_channels,
|
||||
test_put_writes_across_namespaces,
|
||||
test_put_writes_cleared_on_next_checkpoint,
|
||||
]
|
||||
|
||||
|
||||
async def run_put_writes_tests(
|
||||
saver: BaseCheckpointSaver,
|
||||
on_test_result: Callable[[str, str, bool, str | None], None] | None = None,
|
||||
) -> tuple[int, int, list[str]]:
|
||||
"""Run all put_writes tests. Returns (passed, failed, failure_names)."""
|
||||
passed = 0
|
||||
failed = 0
|
||||
failures: list[str] = []
|
||||
for test_fn in ALL_PUT_WRITES_TESTS:
|
||||
try:
|
||||
await test_fn(saver)
|
||||
passed += 1
|
||||
if on_test_result:
|
||||
on_test_result("put_writes", test_fn.__name__, True, None)
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
msg = f"{test_fn.__name__}: {e}"
|
||||
failures.append(msg)
|
||||
if on_test_result:
|
||||
on_test_result(
|
||||
"put_writes", test_fn.__name__, False, traceback.format_exc()
|
||||
)
|
||||
return passed, failed, failures
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Test utilities: checkpoint generators, assertion helpers, bulk operations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.checkpoint.base import (
|
||||
ChannelVersions,
|
||||
Checkpoint,
|
||||
CheckpointMetadata,
|
||||
CheckpointTuple,
|
||||
)
|
||||
from langgraph.checkpoint.base.id import uuid6
|
||||
|
||||
|
||||
def generate_checkpoint(
|
||||
*,
|
||||
checkpoint_id: str | None = None,
|
||||
channel_values: dict[str, Any] | None = None,
|
||||
channel_versions: ChannelVersions | None = None,
|
||||
versions_seen: dict[str, ChannelVersions] | None = None,
|
||||
) -> Checkpoint:
|
||||
"""Create a well-formed Checkpoint with sensible defaults."""
|
||||
return Checkpoint(
|
||||
v=1,
|
||||
id=checkpoint_id or str(uuid6(clock_seq=-1)),
|
||||
ts=datetime.now(timezone.utc).isoformat(),
|
||||
channel_values=channel_values if channel_values is not None else {},
|
||||
channel_versions=channel_versions if channel_versions is not None else {},
|
||||
versions_seen=versions_seen if versions_seen is not None else {},
|
||||
pending_sends=[], # ty: ignore[invalid-key]
|
||||
updated_channels=None,
|
||||
)
|
||||
|
||||
|
||||
def generate_config(
|
||||
thread_id: str | None = None,
|
||||
*,
|
||||
checkpoint_ns: str = "",
|
||||
checkpoint_id: str | None = None,
|
||||
) -> RunnableConfig:
|
||||
"""Create a RunnableConfig targeting a specific thread / namespace / checkpoint."""
|
||||
configurable: dict[str, Any] = {
|
||||
"thread_id": thread_id or str(uuid4()),
|
||||
"checkpoint_ns": checkpoint_ns,
|
||||
}
|
||||
if checkpoint_id is not None:
|
||||
configurable["checkpoint_id"] = checkpoint_id
|
||||
return {"configurable": configurable}
|
||||
|
||||
|
||||
def generate_metadata(
|
||||
source: str = "loop",
|
||||
step: int = 0,
|
||||
**extra: Any,
|
||||
) -> CheckpointMetadata:
|
||||
"""Create CheckpointMetadata with defaults."""
|
||||
md: dict[str, Any] = {"source": source, "step": step, "parents": {}}
|
||||
md.update(extra)
|
||||
return md
|
||||
|
||||
|
||||
async def put_test_checkpoint(
|
||||
saver: Any,
|
||||
*,
|
||||
thread_id: str | None = None,
|
||||
checkpoint_ns: str = "",
|
||||
parent_config: RunnableConfig | None = None,
|
||||
channel_values: dict[str, Any] | None = None,
|
||||
channel_versions: ChannelVersions | None = None,
|
||||
metadata: CheckpointMetadata | None = None,
|
||||
new_versions: ChannelVersions | None = None,
|
||||
) -> RunnableConfig:
|
||||
"""Put a single test checkpoint and return the stored config.
|
||||
|
||||
Handles wiring up parent_config, channel_values -> new_versions, etc.
|
||||
"""
|
||||
tid = thread_id or str(uuid4())
|
||||
cp = generate_checkpoint(
|
||||
channel_values=channel_values,
|
||||
channel_versions=channel_versions,
|
||||
)
|
||||
|
||||
# When channel_values are provided, ensure channel_versions + new_versions
|
||||
# are consistent so the checkpointer stores the blobs correctly.
|
||||
vals = channel_values or {}
|
||||
cv = channel_versions
|
||||
if cv is None and vals:
|
||||
cv: ChannelVersions = {k: 1 for k in vals}
|
||||
cp["channel_versions"] = cv
|
||||
nv = new_versions
|
||||
if nv is None:
|
||||
nv = cv or {}
|
||||
|
||||
md = metadata or generate_metadata()
|
||||
|
||||
config = generate_config(tid, checkpoint_ns=checkpoint_ns)
|
||||
if parent_config is not None:
|
||||
config["configurable"]["checkpoint_id"] = parent_config["configurable"][
|
||||
"checkpoint_id"
|
||||
]
|
||||
|
||||
return await saver.aput(config, cp, md, nv)
|
||||
|
||||
|
||||
async def put_test_checkpoints(
|
||||
saver: Any,
|
||||
*,
|
||||
n_threads: int = 1,
|
||||
n_checkpoints: int = 1,
|
||||
namespaces: list[str] | None = None,
|
||||
channel_values: dict[str, Any] | None = None,
|
||||
) -> list[RunnableConfig]:
|
||||
"""Convenience: put multiple checkpoints across threads/namespaces.
|
||||
|
||||
Returns the stored configs in insertion order.
|
||||
"""
|
||||
nss = namespaces or [""]
|
||||
stored: list[RunnableConfig] = []
|
||||
for t in range(n_threads):
|
||||
tid = f"thread-{t}"
|
||||
for ns in nss:
|
||||
parent: RunnableConfig | None = None
|
||||
for _c in range(n_checkpoints):
|
||||
cfg = await put_test_checkpoint(
|
||||
saver,
|
||||
thread_id=tid,
|
||||
checkpoint_ns=ns,
|
||||
parent_config=parent,
|
||||
channel_values=channel_values,
|
||||
)
|
||||
parent = cfg
|
||||
stored.append(cfg)
|
||||
return stored
|
||||
|
||||
|
||||
def assert_checkpoint_equal(
|
||||
actual: Checkpoint,
|
||||
expected: Checkpoint,
|
||||
*,
|
||||
check_channel_values: bool = True,
|
||||
) -> None:
|
||||
"""Assert two checkpoints are semantically equal."""
|
||||
assert actual["v"] == expected["v"], f"v mismatch: {actual['v']} != {expected['v']}"
|
||||
assert actual["id"] == expected["id"], (
|
||||
f"id mismatch: {actual['id']} != {expected['id']}"
|
||||
)
|
||||
assert actual["channel_versions"] == expected["channel_versions"], (
|
||||
"channel_versions mismatch"
|
||||
)
|
||||
assert actual["versions_seen"] == expected["versions_seen"], (
|
||||
"versions_seen mismatch"
|
||||
)
|
||||
if check_channel_values:
|
||||
assert actual["channel_values"] == expected["channel_values"], (
|
||||
"channel_values mismatch"
|
||||
)
|
||||
|
||||
|
||||
def assert_tuple_equal(
|
||||
actual: CheckpointTuple,
|
||||
expected: CheckpointTuple,
|
||||
*,
|
||||
check_writes: bool = True,
|
||||
check_channel_values: bool = True,
|
||||
) -> None:
|
||||
"""Assert two CheckpointTuples are semantically equal."""
|
||||
# Config
|
||||
a_conf = actual.config["configurable"]
|
||||
e_conf = expected.config["configurable"]
|
||||
assert a_conf["thread_id"] == e_conf["thread_id"], (
|
||||
f"thread_id mismatch: {a_conf['thread_id']} != {e_conf['thread_id']}"
|
||||
)
|
||||
assert a_conf.get("checkpoint_ns", "") == e_conf.get("checkpoint_ns", ""), (
|
||||
"checkpoint_ns mismatch"
|
||||
)
|
||||
assert a_conf["checkpoint_id"] == e_conf["checkpoint_id"], "checkpoint_id mismatch"
|
||||
|
||||
# Checkpoint
|
||||
assert_checkpoint_equal(
|
||||
actual.checkpoint,
|
||||
expected.checkpoint,
|
||||
check_channel_values=check_channel_values,
|
||||
)
|
||||
|
||||
# Metadata
|
||||
for k, v in expected.metadata.items():
|
||||
assert actual.metadata.get(k) == v, (
|
||||
f"metadata[{k}] mismatch: {actual.metadata.get(k)} != {v}"
|
||||
)
|
||||
|
||||
# Parent config
|
||||
if expected.parent_config is not None:
|
||||
assert actual.parent_config is not None, "expected parent_config, got None"
|
||||
assert (
|
||||
actual.parent_config["configurable"]["checkpoint_id"]
|
||||
== expected.parent_config["configurable"]["checkpoint_id"]
|
||||
), "parent checkpoint_id mismatch"
|
||||
else:
|
||||
assert actual.parent_config is None, (
|
||||
f"expected no parent_config, got {actual.parent_config}"
|
||||
)
|
||||
|
||||
# Pending writes
|
||||
if check_writes and expected.pending_writes is not None:
|
||||
assert actual.pending_writes is not None
|
||||
assert len(actual.pending_writes) == len(expected.pending_writes), (
|
||||
f"pending_writes length mismatch: {len(actual.pending_writes)} != {len(expected.pending_writes)}"
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Core conformance runner — detects capabilities, runs test suites, builds report."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from langgraph.checkpoint.conformance.capabilities import (
|
||||
Capability,
|
||||
DetectedCapabilities,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.initializer import RegisteredCheckpointer
|
||||
from langgraph.checkpoint.conformance.report import (
|
||||
CapabilityReport,
|
||||
CapabilityResult,
|
||||
ProgressCallbacks,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_copy_thread import run_copy_thread_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_delete_for_runs import (
|
||||
run_delete_for_runs_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_delete_thread import (
|
||||
run_delete_thread_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_delta_channel_history import (
|
||||
run_delta_channel_history_tests,
|
||||
)
|
||||
from langgraph.checkpoint.conformance.spec.test_get_tuple import run_get_tuple_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_list import run_list_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_prune import run_prune_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_put import run_put_tests
|
||||
from langgraph.checkpoint.conformance.spec.test_put_writes import run_put_writes_tests
|
||||
|
||||
# Maps capability to its runner function.
|
||||
_RUNNERS = {
|
||||
Capability.PUT: run_put_tests,
|
||||
Capability.PUT_WRITES: run_put_writes_tests,
|
||||
Capability.GET_TUPLE: run_get_tuple_tests,
|
||||
Capability.LIST: run_list_tests,
|
||||
Capability.DELETE_THREAD: run_delete_thread_tests,
|
||||
Capability.DELETE_FOR_RUNS: run_delete_for_runs_tests,
|
||||
Capability.COPY_THREAD: run_copy_thread_tests,
|
||||
Capability.PRUNE: run_prune_tests,
|
||||
Capability.DELTA_CHANNEL_HISTORY: run_delta_channel_history_tests,
|
||||
}
|
||||
|
||||
|
||||
async def validate(
|
||||
registered: RegisteredCheckpointer,
|
||||
*,
|
||||
capabilities: set[str] | None = None,
|
||||
progress: ProgressCallbacks | None = None,
|
||||
) -> CapabilityReport:
|
||||
"""Run the validation suite against a registered checkpointer.
|
||||
|
||||
Args:
|
||||
registered: A RegisteredCheckpointer (from @checkpointer_test decorator).
|
||||
capabilities: If given, only run tests for these capability names.
|
||||
Otherwise, auto-detect and run all applicable tests.
|
||||
progress: Optional progress callbacks for incremental output.
|
||||
Use ``ProgressCallbacks.default()`` for dot-style,
|
||||
``ProgressCallbacks.verbose()`` for per-test output, or
|
||||
``None`` / ``ProgressCallbacks.quiet()`` for silent mode.
|
||||
|
||||
Returns:
|
||||
A CapabilityReport with per-capability results.
|
||||
"""
|
||||
report = CapabilityReport(checkpointer_name=registered.name)
|
||||
|
||||
# Determine which capabilities to test.
|
||||
caps_to_test: set[Capability]
|
||||
if capabilities is not None:
|
||||
caps_to_test = {Capability(c) for c in capabilities}
|
||||
else:
|
||||
caps_to_test = set(Capability)
|
||||
|
||||
async with registered.enter_lifespan():
|
||||
for cap in Capability:
|
||||
if cap in caps_to_test and cap.value not in registered.skip_capabilities:
|
||||
# Create a fresh checkpointer for each capability suite.
|
||||
async with registered.create() as saver:
|
||||
detected = DetectedCapabilities.from_instance(saver)
|
||||
is_detected = cap in detected.detected
|
||||
|
||||
if not is_detected:
|
||||
if progress and progress.on_capability_start:
|
||||
progress.on_capability_start(cap.value, False)
|
||||
report.results[cap.value] = CapabilityResult(
|
||||
detected=False,
|
||||
passed=None,
|
||||
tests_skipped=1,
|
||||
)
|
||||
continue
|
||||
|
||||
runner = _RUNNERS.get(cap)
|
||||
if runner is None:
|
||||
report.results[cap.value] = CapabilityResult(
|
||||
detected=True,
|
||||
passed=None,
|
||||
tests_skipped=1,
|
||||
)
|
||||
continue
|
||||
|
||||
if progress and progress.on_capability_start:
|
||||
progress.on_capability_start(cap.value, True)
|
||||
|
||||
passed, failed, failures = await runner(
|
||||
saver,
|
||||
on_test_result=progress.on_test_result if progress else None,
|
||||
)
|
||||
|
||||
if progress and progress.on_capability_end:
|
||||
progress.on_capability_end(cap.value)
|
||||
|
||||
report.results[cap.value] = CapabilityResult(
|
||||
detected=True,
|
||||
passed=failed == 0,
|
||||
tests_passed=passed,
|
||||
tests_failed=failed,
|
||||
failures=failures,
|
||||
)
|
||||
else:
|
||||
if progress and progress.on_capability_start:
|
||||
progress.on_capability_start(cap.value, False)
|
||||
report.results[cap.value] = CapabilityResult(
|
||||
detected=False,
|
||||
passed=None,
|
||||
tests_skipped=1,
|
||||
)
|
||||
|
||||
return report
|
||||
@@ -0,0 +1,72 @@
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langgraph-checkpoint-conformance"
|
||||
version = "0.0.2"
|
||||
description = "Conformance test suite for LangGraph checkpointer implementations."
|
||||
authors = [{name = "William FH", email = "13333726+hinthornw@users.noreply.github.com"}]
|
||||
requires-python = ">=3.10"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
dependencies = [
|
||||
"langgraph-checkpoint>=2.0.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Source = "https://github.com/langchain-ai/langgraph/tree/main/libs/checkpoint-conformance"
|
||||
|
||||
[dependency-groups]
|
||||
test = [
|
||||
"pytest",
|
||||
"pytest-asyncio",
|
||||
]
|
||||
lint = [
|
||||
"ruff",
|
||||
"ty",
|
||||
]
|
||||
dev = [
|
||||
{include-group = "test"},
|
||||
{include-group = "lint"},
|
||||
]
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
include = ["langgraph"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--strict-markers --strict-config --durations=5 -vv"
|
||||
testpaths = ["tests"]
|
||||
asyncio_mode = "auto"
|
||||
|
||||
[tool.ty.rules]
|
||||
# The extended methods (acopy_thread, adelete_for_runs, aprune) are checked
|
||||
# at runtime via capability detection and may not exist on the installed
|
||||
# base class. Dict literal inference is also overly strict for RunnableConfig.
|
||||
# Delta-channel tests import from `langgraph` (not a declared dep of this
|
||||
# package — at test time it is installed alongside); private `_DeltaSnapshot`
|
||||
# imports are intentional (beta surface).
|
||||
unresolved-attribute = "ignore"
|
||||
unresolved-import = "ignore"
|
||||
invalid-argument-type = "ignore"
|
||||
invalid-return-type = "ignore"
|
||||
|
||||
[tool.ruff]
|
||||
lint.select = [
|
||||
"E", # pycodestyle
|
||||
"F", # Pyflakes
|
||||
"UP", # pyupgrade
|
||||
"B", # flake8-bugbear
|
||||
"I", # isort
|
||||
]
|
||||
lint.ignore = ["E501", "B008"]
|
||||
target-version = "py310"
|
||||
|
||||
[tool.uv.sources]
|
||||
langgraph-checkpoint = {path = "../checkpoint", editable = true}
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "testpypi"
|
||||
url = "https://test.pypi.org/simple/"
|
||||
publish-url = "https://test.pypi.org/legacy/"
|
||||
explicit = true
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Self-tests: run the conformance suite against InMemorySaver."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from langgraph.checkpoint.conformance import checkpointer_test, validate
|
||||
|
||||
|
||||
@checkpointer_test(name="InMemorySaver")
|
||||
async def memory_checkpointer():
|
||||
yield InMemorySaver()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_memory_base():
|
||||
"""InMemorySaver passes all base capability tests."""
|
||||
report = await validate(memory_checkpointer)
|
||||
report.print_report()
|
||||
assert report.passed_all_base(), f"Base tests failed: {report.to_dict()}"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user