Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(checkpoint-validation): add custom checkpointer validation tool #600

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ index.js
index.d.ts
node_modules
dist
coverage/
.yarn/*
!.yarn/patches
!.yarn/plugins
Expand All @@ -18,4 +19,4 @@ dist
.ipynb_checkpoints
dist-cjs
**/dist-cjs
tmp/
tmp/
6 changes: 6 additions & 0 deletions libs/checkpoint-validation/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# ------------------LangSmith tracing------------------
LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
LANGCHAIN_API_KEY=
LANGCHAIN_PROJECT=
# -----------------------------------------------------
69 changes: 69 additions & 0 deletions libs/checkpoint-validation/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof", "eslint-plugin-jest"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
"arrow-body-style": 0,
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
'jest/no-focused-tests': 'error',
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-empty-function": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
};
7 changes: 7 additions & 0 deletions libs/checkpoint-validation/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
index.cjs
index.js
index.d.ts
index.d.cts
node_modules
dist
.yarn
19 changes: 19 additions & 0 deletions libs/checkpoint-validation/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
13 changes: 13 additions & 0 deletions libs/checkpoint-validation/.release-it.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"publish": true,
"versionArgs": [
"--workspaces-update=false"
]
}
}
21 changes: 21 additions & 0 deletions libs/checkpoint-validation/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2024 LangChain

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.
96 changes: 96 additions & 0 deletions libs/checkpoint-validation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# @langchain/langgraph-checkpoint-validation
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add a section to the LangGraph docs around contributing! I can do that in a separate PR after we merge this.


The checkpointer validation tool is used to validate that custom checkpointer implementations conform to LangGraph's requirements. LangGraph uses [checkpointers](https://langchain-ai.github.io/langgraphjs/concepts/persistence/#checkpointer-libraries) for persisting workflow state, providing the ability to "rewind" your workflow to some earlier point in time, and continue execution from there.

The overall process for using this tool is as follows:

1. Write your custom checkpointer implementation.
2. Add a file to your project that defines a [`CheckpointerTestInitializer`](./src/types.ts) as its default export.
3. Run the checkpointer validation tool to test your checkpointer and determine whether it meets LangGraph's requirements.
4. Iterate on your custom checkpointer as required, until tests pass.

The tool can be executed from the terminal as a CLI, or you can use it as a library to integrate it into your test suite.

## Writing a CheckpointerTestInitializer

The `CheckpointerTestInitializer` interface ([example](./src/tests/postgres_initializer.ts)) is used by the test harness to create instances of your custom checkpointer, and any infrastructure that it requires for testing purposes.

If you intend to execute the tool via the CLI, your `CheckpointerTestInitializer` **must** be the default export of the module in which it is defined.

**Synchronous vs Asynchronous initializer functions**: You may return promises from any functions defined in your `CheckpointerTestInitializer` according to your needs and the test harness will behave accordingly.

**IMPORTANT**: You must take care to write your `CheckpointerTestInitializer` such that instances of your custom checkpointer are isolated from one another with respect to persisted state, or else some tests (particularly the ones that exercise the `list` method) will fail. That is, state written by one instance of your checkpointer MUST NOT be readable by another instance of your checkpointer. That said, there will only ever be one instance of your checkpointer live at any given time, so **you may use shared storage, provided it is cleared when your checkpointer is created or destroyed.** The structure of the `CheckpointerTestInitializer` interface should make this relatively easy to achieve, per the sections below.


### (Required) `checkpointerName`: Define a name for your checkpointer

`CheckpointerTestInitializer` requires you to define a `checkpointerName` field (of type `string`) for use in the test output.

### `beforeAll`: Set up required infrastructure

If your checkpointer requires some external infrastructure to be provisioned, you may wish to provision this via the **optional** `beforeAll` function. This function executes exactly once, at the very start of the testing lifecycle. If defined, it is the first function that will be called from your `CheckpointerTestInitializer`.

**Timeout duration**: If your `beforeAll` function may take longer than 10 seconds to execute, you can assign a custom timeout duration (as milliseconds) to the optional `beforeAllTimeout` field of your `CheckpointerTestInitializer`.

**State isolation note**: Depending on the cost/performance/requirements of your checkpointer infrastructure, it **may** make more sense for you to provision it during the `createCheckpointer` step, so you can provide each checkpointer instance with its own isolated storage backend. However as mentioned above, you may also provision a single shared storage backend, provided you clear any stored data during the `createCheckpointer` or `destroyCheckpointer` step.

### `afterAll`: Tear down required infrastructure

If you set up infrastructure during the `beforeAll` step, you may need to tear it down once the tests complete their execution. You can define this teardown logic in the optional `afterAll` function. Much like `beforeAll` this function will execute exactly one time, after all tests have finished executing.

**IMPORTANT**: If you kill the test runner early this function may not be called. To avoid manual clean-up, give preference to test infrastructure management tools like [TestContainers](https://testcontainers.com/guides/getting-started-with-testcontainers-for-nodejs/), as these tools are designed to detect when this happens and clean up after themselves once the controlling process dies.

### (Required) `createCheckpointer`: Construct your checkpointer

`CheckpointerTestInitializer` requires you to define a `createCheckpointer()` function that returns an instance of your custom checkpointer.

**State isolation note:** If you're provisioning storage during this step, make sure that it is "fresh" storage for each instance of your checkpointer. Otherwise if you are using a shared storage setup, be sure to clear it either in this function, or in the `destroyCheckpointer` function (described in the section below).

### `destroyCheckpointer`: Destroy your checkpointer

If your custom checkpointer requires an explicit teardown step (for example, to clean up database connections), you can define this in the **optional** `destroyCheckpointer(checkpointer: CheckpointerT)` function.

**State isolation note:** If you are using a shared storage setup, be sure to clear it either in this function, or in the `createCheckpointer` function (described in the section above).

## CLI usage

You may use this tool's CLI either via `npx`, `yarn dlx`, or by installing globally and executing it via the `validate-checkpointer` command.

The only required argument to the tool is the import path for your `CheckpointerTestInitializer`. Relative paths must begin with a leading `./` (or `.\`, for Windows), otherwise the path will be interpreted as a module name rather than a relative path.

You may optionally pass one or more test filters as positional arguments after the import path argument (separated by spaces). Valid values are `getTuple`, `list`, `put`, and `putWrites`. If present, only the test suites specified in the filter list will be executed. This is useful for working through smaller sets of test failures as you're validating your checkpointer.

TypeScript imports **are** supported, so you may pass a path directly to your TypeScript source file.

### NPX & Yarn execution

NPX:

```bash
npx @langchain/langgraph-checkpoint-validation ./src/my_initializer.ts
```

Yarn:

```bash
yarn dlx @langchain/langgraph-checkpoint-validation ./src/my_initializer.ts
```

### Global install

NPM:

```bash
npm install -g @langchain/langgraph-checkpoint-validation
validate-checkpointer ./src/my_initializer.ts
```

## Usage in existing Jest test suite

If you wish to integrate this tooling into your existing Jest test suite, you import it as a library, as shown below.

```ts
import { validate } from "@langchain/langgraph-validation";

validate(MyCheckpointerInitializer);
```
5 changes: 5 additions & 0 deletions libs/checkpoint-validation/bin/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env node

import { main } from "../dist/cli.js";

await main();
22 changes: 22 additions & 0 deletions libs/checkpoint-validation/bin/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// This is the Jest config used by the test harness when being executed via the CLI.
// For the Jest config for the tests in this project, see the `jest.config.cjs` in the root of the package workspace.
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "../dist/parse_args.js";

const args = await parseArgs(process.argv.slice(2));

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
preset: "ts-jest/presets/default-esm",
rootDir: path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "dist"),
testEnvironment: "node",
testMatch: ["<rootDir>/runner.js"],
transform: {
"^.+\\.[jt]sx?$": ["@swc/jest"],
},
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.[jt]sx?$": "$1",
},
globals: args,
};
38 changes: 38 additions & 0 deletions libs/checkpoint-validation/jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
rootDir: "../../",
testEnvironment: "./libs/checkpoint-validation/jest.env.cjs",
testMatch: ["<rootDir>/libs/checkpoint-validation/src/**/*.spec.ts"],
modulePathIgnorePatterns: ["dist/"],

collectCoverageFrom: [
"<rootDir>/libs/checkpoint/src/memory.ts",
"<rootDir>/libs/checkpoint-mongodb/src/index.ts",
"<rootDir>/libs/checkpoint-postgres/src/index.ts",
"<rootDir>/libs/checkpoint-sqlite/src/index.ts",
],

coveragePathIgnorePatterns: [
".+\\.(test|spec)\\.ts",
],

coverageDirectory: "<rootDir>/libs/checkpoint-validation/coverage",

moduleNameMapper: {
"^@langchain/langgraph-(checkpoint(-[^/]+)?)$": "<rootDir>/libs/$1/src/index.ts",
"^@langchain/langgraph-(checkpoint(-[^/]+)?)/(.+)\\.js$": "<rootDir>/libs/$1/src/$2.ts",
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/(?!@langchain/langgraph-checkpoint-[^/]+)",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
};
12 changes: 12 additions & 0 deletions libs/checkpoint-validation/jest.env.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { TestEnvironment } = require("jest-environment-node");

class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}

module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
21 changes: 21 additions & 0 deletions libs/checkpoint-validation/langchain.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";

/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}

export const config = {
internals: [/node\:/, /@langchain\/core\//, /async_hooks/],
entrypoints: {
index: "index"
},
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
};
Loading
Loading