Metadata-Version: 2.5
Name: open-postgres-checkpointer
Version: 1.0.0rc2
Summary: A LangGraph Postgres checkpointer that stores changed values as small patches on upstream's own tables.
Project-URL: Homepage, https://github.com/davidallada/open-postgres-checkpointer
Project-URL: Documentation, https://davidallada.github.io/open-postgres-checkpointer/
Project-URL: Source, https://github.com/davidallada/open-postgres-checkpointer
Project-URL: Issues, https://github.com/davidallada/open-postgres-checkpointer/issues
Project-URL: Changelog, https://github.com/davidallada/open-postgres-checkpointer/blob/main/CHANGELOG.md
Author-email: David Allada <davidanilallada@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
License-File: THIRD_PARTY_NOTICES.md
Keywords: checkpoint,checkpointer,langchain,langgraph,postgres,postgresql,zstd
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: backports-zstd>=1.8.0; python_version < '3.14'
Requires-Dist: langgraph-checkpoint<5,>=4.3.1
Requires-Dist: psycopg-pool>=3.2
Requires-Dist: psycopg>=3.3.6
Provides-Extra: binary
Requires-Dist: psycopg[binary]>=3.3.6; extra == 'binary'
Provides-Extra: c
Requires-Dist: psycopg[c]>=3.3.6; extra == 'c'
Description-Content-Type: text/markdown

# Open Postgres Checkpointer

[![CI](https://github.com/davidallada/open-postgres-checkpointer/actions/workflows/ci.yml/badge.svg)](https://github.com/davidallada/open-postgres-checkpointer/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/open-postgres-checkpointer?include_prereleases)](https://pypi.org/project/open-postgres-checkpointer/)
[![Python 3.11–3.14](https://img.shields.io/pypi/pyversions/open-postgres-checkpointer)](https://pypi.org/project/open-postgres-checkpointer/)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/davidallada/open-postgres-checkpointer/blob/main/LICENSE)
[![Typed](https://img.shields.io/badge/typing-typed-blue.svg)](https://packaging.python.org/en/latest/specifications/py-typed-data/)
[![Docs](https://img.shields.io/badge/docs-mkdocs-blue.svg)](https://davidallada.github.io/open-postgres-checkpointer/)

**A drop-in LangGraph PostgreSQL checkpointer that cuts disk usage 4×–12.5× using flat zstd patches, lock-free pooled concurrency, optimistic thread fencing, and production lifecycle primitives — on upstream's own tables.**

[Documentation](https://davidallada.github.io/open-postgres-checkpointer/) · [Why & How It Works](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/how-it-works.md) · [Quickstart](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/quickstart.md) · [Benchmarks](#benchmarks) · [Changelog](https://github.com/davidallada/open-postgres-checkpointer/blob/main/CHANGELOG.md)

> **Status:** `1.0.0rc1` is a release candidate. Tested against upstream's `langgraph-checkpoint-conformance` suite. Please report bugs or edge cases in [GitHub Issues](https://github.com/davidallada/open-postgres-checkpointer/issues).

---

## Why Open Postgres Checkpointer?

Upstream's `langgraph-checkpoint-postgres` rewrites every changed channel value in full at every step (causing O(N²) disk and WAL growth on growing chat/agent state), serializes all traffic behind a single saver-wide `asyncio.Lock`, lets concurrent runs on one thread silently fork history, refuses to prune `DeltaChannel` threads, and omits operational primitives like thread listing and idle-thread expiry.

Open Postgres Checkpointer implements LangGraph's `BaseCheckpointSaver` directly on upstream's existing four tables — adopting existing databases in place with no data migration:

| Capability | `langgraph-checkpoint-postgres` | `open-postgres-checkpointer` |
|---|---|---|
| **Disk on plain graphs** | O(N²) full rewrites every step | **4.0×–12.5× smaller** via flat zstd-prefix patches (no graph changes) |
| **Concurrency** | Single saver-wide `asyncio.Lock` | **Lock-free connection pool** + single-statement atomic `put` / `put_writes` (**1.5×–1.7×** turns/s) |
| **Racing writers on one thread** | Silently forks history | **Optimistic fence** raises `ThreadConflictError` |
| **Retention & pruning** | Refuses `DeltaChannel` threads | `aprune` / `prune` works on `DeltaChannel`, plus `keep_last=N` thinning and `adelete_for_runs` |
| **Thread operations** | Manual SQL | Indexed `alist_threads` / `list_threads`, `acopy_thread`, and idle-thread `asweep_expired` |
| **Adoption & rollback** | — | Reads all upstream rows in place; `full_copies_only=True` rollout; online rollback via `opc-rehydrate` |

For turn-by-turn diagrams of how upstream stores checkpoints and how each optimization works, see **[Why & How It Works](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/how-it-works.md)**.

---

## Installation

```bash
pip install --pre "open-postgres-checkpointer[binary]"
```

Or with [uv](https://docs.astral.sh/uv/):

```bash
uv add "open-postgres-checkpointer[binary]>=1.0.0rc1"
```

- `[binary]` installs psycopg's bundled `libpq`. If your environment already provides PostgreSQL's `libpq`, you can install bare `open-postgres-checkpointer` (or `[c]` for psycopg's C extension). Importing without a `libpq` backend raises `ImportError: no pq wrapper available`.
- `--pre` is required while only release candidates are published.

---

## Quickstart

### Async (recommended)

```python
from open_postgres_checkpointer import AsyncOpenPostgresCheckpointer

async with AsyncOpenPostgresCheckpointer.from_conn_string(DB_URI) as saver:
    await saver.setup()  # once, from one process
    graph = builder.compile(checkpointer=saver)
    result = await graph.ainvoke(inputs, {"configurable": {"thread_id": "t1"}})
```

You can also pass an existing `psycopg_pool.AsyncConnectionPool` configured with `kwargs={"autocommit": True}` directly to `async with AsyncOpenPostgresCheckpointer(pool) as saver:`.

### Sync

For code without an event loop of its own, `OpenPostgresCheckpointer` provides the same behavior over a private background loop thread:

```python
from open_postgres_checkpointer import OpenPostgresCheckpointer

with OpenPostgresCheckpointer.from_conn_string(DB_URI) as saver:
    saver.setup()  # once, from one process
    graph = builder.compile(checkpointer=saver)
    result = graph.invoke(inputs, {"configurable": {"thread_id": "t1"}})
```

---

## Production Primitives

### List threads (indexed, metadata-filtered, cursor-paged)

```python
from open_postgres_checkpointer import alist_threads

page = [t async for t in alist_threads(saver, filter={"user_id": "u1"}, limit=20)]
next_page = [
    t
    async for t in alist_threads(
        saver, filter={"user_id": "u1"}, before=page[-1].config, limit=20
    )
]
```

*(Sync callers use `list_threads(saver, ...)`.)*

### Retention, thinning, and idle-thread expiry

```python
from datetime import timedelta

# Thin history: keep the last 10 checkpoints per namespace + each run's final checkpoint
await saver.aprune(["t1", "t2"], keep_last=10)

# Delete threads idle for more than 30 days (safe alongside live runs)
report = await saver.asweep_expired(timedelta(days=30), max_threads=100)

# Remove checkpoints belonging to specific runs, or clone a thread for branching/replay
await saver.adelete_for_runs(["run-123"])
await saver.acopy_thread("t1", "t1-fork")
```

### Optimistic concurrency fence

Every read mints a lightweight generation token carried through LangGraph's `configurable` dict. If two runs race on the same thread, the stale writer is refused with `ThreadConflictError` instead of silently overwriting or forking history:

```python
from open_postgres_checkpointer import ThreadConflictError

try:
    await graph.ainvoke(inputs, config)
except ThreadConflictError:
    # Reload latest state or surface a conflict to the caller
    ...
```

---

## How Patch Storage Works

Changed channel values ≥ 1 KiB are compressed as a **flat zstd-prefix patch** against an earlier full copy (the *base*) stored in upstream's `checkpoint_blobs` table. Every base is a full copy — never a patch — so reads apply **at most one patch** regardless of thread length:

```text
checkpoint_blobs
  v1 (base)   ──► opc:zstd:msgpack         (compressed full copy + zstd checksum)
  v2 (patch)  ──► opc:zstd-patch:msgpack   (small delta against v1; 1 hop to decode)
  v3 (patch)  ──► opc:zstd-patch:msgpack   (small delta against v1; still 1 hop)
  vN (new)    ──► opc:zstd:msgpack         (new base once patch > 25% of base size)
```

- **Wire-skip warm reads:** An in-memory LRU `BaseCache` (64 MiB default) caches base bytes and `ZstdDict` prefixes so warm reads skip re-fetching the base blob over the wire.
- **Database-enforced integrity:** A `DEFERRABLE INITIALLY DEFERRED` foreign key in `opc_blob_patch` prevents orphaned patches, and zstd content checksums verify every decoded frame.
- **Off the event loop:** All serialization, compression, and decoding run on a dedicated single codec thread per saver.

---

## Benchmarks

Measured before the first release on an uncontended benchmark host with PostgreSQL 16 and 8 pool connections per arm. Disk is bytes above each arm's empty schema after `VACUUM`, including our side tables and indexes. Ratios are against upstream's `AsyncPostgresSaver`:

| Workload | Disk vs. upstream | `put` p50 vs. upstream |
|---|---|---|
| 400-step chat, plain graph | **6.9× smaller** | **0.41×** |
| 400-step chat, `DeltaChannel` graph | **0.95×** | **0.65×** |
| Agent thread growing to 1 / 3 / 10 MB, plain graph | **4.0× / 5.7× / 12.5× smaller** | **0.43× / 0.34× / 0.15×** |
| Agent thread growing to 1 / 3 / 10 MB, `DeltaChannel` graph | **1.06×** / 0.93× / 0.84× | **1.39× / 1.81× / 1.76×** *(cold pool)* |
| 8 / 32 concurrent threads, plain graph | — | **0.53× / 0.47×** (**1.7× / 1.6×** turns/s) |
| 8 / 32 concurrent threads, `DeltaChannel` graph | — | **0.21× / 0.21×** (**1.5× / 1.5×** turns/s) |

> **Note on the cold-pool `DeltaChannel` cells:** Bold cells exceed the [acceptance bars](https://github.com/davidallada/open-postgres-checkpointer/blob/main/benchmarks/README.md#acceptance-bars) (`DeltaChannel` disk ≤ 1.05×, `put` p50 ≤ 1.25×) on a brand-new connection pool because the larger `put` statement (which also maintains `opc_thread_head` and the listing index) costs more to plan on first execution ([analysis](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/design/put-planning-cold-pools.md)). On a warm long-lived pool, the same `DeltaChannel` puts measure **0.72×–1.16×** upstream ([ADR-0030](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/adr/0030-large-thread-put-bar-pool.md)).

Reproduce locally with [benchmarks/README.md](https://github.com/davidallada/open-postgres-checkpointer/blob/main/benchmarks/README.md):

```bash
just bench-case smoke     # quick setup check
just bench-case four-arm  # 400-step chat + concurrent arms
just bench-case large     # 1 / 3 / 10 MB agent threads
```

---

## Safe Rollout & Rollback

1. **Adopt in place:** Open Postgres Checkpointer reads every row upstream wrote. Once a patch is stored on a thread, upstream's saver cannot read that thread and raises loudly rather than returning partial state.
2. **Zero-downtime rollout:** Deploy initially with `full_copies_only=True` while upstream replicas are still running, then enable patching once all replicas run this saver ([Adopting the saver](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/adoption.md)).
3. **Online rollback:** `opc-rehydrate` rewrites every patch and compressed row back to plain upstream format in resumable, memory-bounded batches while savers keep running:

```bash
opc-rehydrate "$DB_URI" --dry-run   # estimate row counts and disk needed
opc-rehydrate "$DB_URI"             # or: python -m open_postgres_checkpointer.rehydrate
```

See [Rolling back](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/rollback.md) for the full procedure and dropping our side tables.

---

## Supported Versions

| Component | Supported |
|---|---|
| **Python** | `3.11`, `3.12`, `3.13`, `3.14` (`compression.zstd` stdlib on 3.14+; `backports.zstd` before) |
| **PostgreSQL** | `15`, `16` (required weekly matrix); `17`, `18` tested weekly |
| **`langgraph-checkpoint`** | `>=4.3.1, <5` |
| **`langgraph-checkpoint-postgres` schema** | `3.2.0` (vendored migrations; not a runtime dependency) |
| **`psycopg` / `psycopg-pool`** | `>=3.3.6` / `>=3.2` |

---

## Documentation

- **[Why & How It Works](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/how-it-works.md)** — turn-by-turn diagrams, patch design, and optimization breakdown
- **[Quickstart](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/quickstart.md)** — installation, async/sync usage, and thread listing
- **[Adopting the Saver](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/adoption.md)** — rolling deploys, storage format, advisory locks, and known limits
- **[Rolling Back](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/rollback.md)** — `opc-rehydrate` and removing side tables
- **[Architecture](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/architecture.md)**, **[Compatibility Promise](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/compatibility.md)**, **[ADRs](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/adr/README.md)**, and **[Design Notes](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/design/README.md)**

---

## Development

This project uses [uv](https://docs.astral.sh/uv/) and [just](https://just.systems/) (plus a [Dev Container](https://github.com/davidallada/open-postgres-checkpointer/blob/main/docs/devcontainer.md)):

```bash
just install     # sync all dependency groups + install pre-commit hooks
just check       # lint, fmt-check, typecheck, and unit tests
just test-int    # integration + upstream conformance suite (needs Docker)
just docs        # strict MkDocs build
```

See [CONTRIBUTING.md](https://github.com/davidallada/open-postgres-checkpointer/blob/main/CONTRIBUTING.md), [CODE_OF_CONDUCT.md](https://github.com/davidallada/open-postgres-checkpointer/blob/main/CODE_OF_CONDUCT.md), and [SECURITY.md](https://github.com/davidallada/open-postgres-checkpointer/blob/main/SECURITY.md).

## License & Attribution

Licensed under the [Apache License, Version 2.0](https://github.com/davidallada/open-postgres-checkpointer/blob/main/LICENSE) — see [NOTICE](https://github.com/davidallada/open-postgres-checkpointer/blob/main/NOTICE) and [THIRD_PARTY_NOTICES.md](https://github.com/davidallada/open-postgres-checkpointer/blob/main/THIRD_PARTY_NOTICES.md) for attribution and vendored upstream schema migrations.

*PostgreSQL and Postgres are registered trademarks of the PostgreSQL Community Association of Canada (PGCAC). LangGraph and LangChain are trademarks of LangChain, Inc. Open Postgres Checkpointer is an independent open-source project and is not affiliated with, endorsed by, or sponsored by the PostgreSQL Global Development Group, PGCAC, or LangChain, Inc.*
