LangGraph Checkpointer on pgdorm — 1-RTT Agent State & Zero-N+1 History#
← Proving Grounds · LangGraph on GitHub ↗ · Tests: tests/cases/langgraph/
Why Replace langgraph-checkpoint-postgres?#
Production LangGraph agents persist state on every graph step: channel blobs, checkpoint metadata, pending writes, parent lineage, and thread isolation. Upstream langgraph-checkpoint-postgres spans hundreds of lines of hand-assembled psycopg SQL strings, hardcoded MIGRATIONS: list[str] DDL arrays, multi-RTT aput writes, and correlated ARRAY_AGG tuple unpacking (row[0]..row[8]).
PgdormCheckpointSaver implements LangGraph's BaseCheckpointSaver protocol in a single typed file—zero raw SQL, composite-PK slot-backed models matching upstream's 3-table schema, 1-RTT fused step saves, 1-RTT checkpoint resume, and <= 2-RTT zero-N+1 history walks.
1. 1-RTT Fused Step Save (aput)#
Before (langgraph-checkpoint-postgres — Multi-RTT + Raw SQL Strings)#
# Upstream issues separate statements per step inside a transaction (3–4 RTTs)
# and hand-assembles raw SQL strings with manual Jsonb / bytea plumbing:
async with self._cursor(pipeline=True) as cur:
await cur.executemany(
"""INSERT INTO checkpoint_blobs (thread_id, checkpoint_ns, channel, version, type, blob)
VALUES (%s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING""",
self._dump_blobs(thread_id, checkpoint_ns, values, new_versions),
)
await cur.execute(
"""INSERT INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, checkpoint, metadata)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id) DO UPDATE SET ...""",
(thread_id, checkpoint_ns, cp_id, parent_id, Jsonb(cp), Jsonb(meta)),
)
After (pgdorm — Composite PKs, UNNEST Batch, 1-RTT Fused Pipeline)#
class LgCheckpoint(pg.Table, strict_pk=False):
thread_id: pg.Col[str] = pg.pk()
checkpoint_ns: pg.Col[str] = pg.pk()
checkpoint_id: pg.Col[str] = pg.pk()
parent_checkpoint_id: pg.Col[str | None] = pg.col(default=None)
checkpoint_type: pg.Col[str]
checkpoint_blob: pg.Col[bytes]
metadata_type: pg.Col[str]
metadata_blob: pg.Col[bytes]
class LgCheckpointBlob(pg.Table, strict_pk=False):
thread_id: pg.Col[str] = pg.pk()
checkpoint_ns: pg.Col[str] = pg.pk()
channel: pg.Col[str] = pg.pk()
version: pg.Col[str] = pg.pk()
blob_type: pg.Col[str]
blob_data: pg.Col[bytes]
class LgCheckpointWrite(pg.Table, strict_pk=False):
thread_id: pg.Col[str] = pg.pk()
checkpoint_ns: pg.Col[str] = pg.pk()
checkpoint_id: pg.Col[str] = pg.pk()
task_id: pg.Col[str] = pg.pk()
idx: pg.Col[int] = pg.pk()
channel: pg.Col[str]
value_type: pg.Col[str]
value_blob: pg.Col[bytes]
Inside aput, tx.pipeline(commit=True) fuses lazy BEGIN, the UNNEST bulk blob insert, the composite-PK checkpoint upsert, and COMMIT into one PostgreSQL wire round-trip (aput_rtts == 1):
async with self._pool.transaction() as tx, tx.pipeline(commit=True) as pipe:
if blob_rows:
pipe.add(pg.insert_many(LgCheckpointBlob, blob_rows).on_conflict_do_nothing())
pipe.add(
pg.insert(LgCheckpoint)
.values(row)
.on_conflict_do_update(
LgCheckpoint.thread_id,
LgCheckpoint.checkpoint_ns,
LgCheckpoint.checkpoint_id,
checkpoint_type=cp_type,
checkpoint_blob=cp_blob,
metadata_type=meta_type,
metadata_blob=meta_blob,
)
)
What Crosses the Wire (4 Frames, 1 Sync, 1 RTT)#
-- Frame 1: BEGIN (lazy, fused into pipeline)
BEGIN;
-- Frame 2: UNNEST bulk channel-blob batch (constant prepared-statement shape for any N channels)
INSERT INTO "lg_checkpoint_blob" (
"thread_id", "checkpoint_ns", "channel", "version", "blob_type", "blob_data"
)
SELECT u."thread_id", u."checkpoint_ns", u."channel", u."version", u."blob_type", u."blob_data"
FROM UNNEST($1::text[], $2::text[], $3::text[], $4::text[], $5::text[], $6::bytea[])
WITH ORDINALITY AS u("thread_id", "checkpoint_ns", "channel", "version", "blob_type", "blob_data", ord)
ORDER BY u.ord
ON CONFLICT DO NOTHING;
-- Frame 3: Composite-PK checkpoint upsert
INSERT INTO "lg_checkpoint" (
"thread_id", "checkpoint_ns", "checkpoint_id", "parent_checkpoint_id",
"checkpoint_type", "checkpoint_blob", "metadata_type", "metadata_blob"
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT ("thread_id", "checkpoint_ns", "checkpoint_id") DO UPDATE
SET
"checkpoint_type" = $9,
"checkpoint_blob" = $10,
"metadata_type" = $11,
"metadata_blob" = $12;
-- Frame 4: COMMIT + single Sync ==> 1 RTT total
COMMIT;
2. 1-RTT Resume & Zero-N+1 History (aget_tuple / alist)#
Before (langgraph-checkpoint-postgres — Correlated ARRAY_AGG Raw SQL & Tuple Indexing)#
Upstream embeds correlated ARRAY_AGG subqueries across checkpoints, checkpoint_blobs, and checkpoint_writes as raw SQL strings and unpacks positional row[0]..row[8] tuples—or, in naive ORM ports, falls into an N+1 loop firing 1 query per checkpoint in alist().
After (pgdorm — pool.pipeline() + = ANY($1) Constant Shapes)#
- 1-RTT
aget_tuple: Whencheckpoint_idis inconfig,LgCheckpoint,LgCheckpointBlob, andLgCheckpointWriteare fetched in a singleself._pool.pipeline()wave (aget_tuple_rtts == 1). - Zero-N+1
alist(<= 2 RTTstotal): Fetch the page of checkpoints, then bulk-load all matching channel blobs and pending writes in one pipelined wave using.in_any(...)(= ANY($1)):
rows = await self._pool.all(q)
if not rows:
return
# Zero-N+1: bulk-fetch all channel blobs and pending writes in 1 pipelined wave.
thread_ids = list({r.thread_id for r in rows})
cp_ids = [r.checkpoint_id for r in rows]
async with self._pool.pipeline() as pipe:
blobs_h = pipe.add(
pg.select(LgCheckpointBlob).where(LgCheckpointBlob.thread_id.in_any(thread_ids))
)
writes_h = pipe.add(
pg.select(LgCheckpointWrite)
.where(LgCheckpointWrite.checkpoint_id.in_any(cp_ids))
.order_by(LgCheckpointWrite.idx.asc())
)
Verified live in test_their_code.py via TelemetryHook: walking 12 persisted StateGraph checkpoints via graph.aget_state_history(cfg) executes in 2 RTTs total regardless of history depth.
3. Assimilated Schema & Online Migrations#
Instead of maintaining a hardcoded MIGRATIONS: list[str] array and a manual checkpoint_migrations version table, pgdorm migrate introspects LangGraph's upstream SQL schema, plans the adoption (scaffold_from_db(mode="assimilate") + plan_adoption), and applies 17 assimilation ops with 0 blockers and 0 residual ops.
The Adoption Ladder#
| Status | Rung | Today | Blocked by |
|---|---|---|---|
| ✅ | Audit the live schema | 4 tables; left untouched: nothing | — |
| ✅ | Bind models to the live schema, zero DDL | 0 planned DDL operations | — |
| ✅ | Build a fresh database from the models alone | 4 DDL ops applied cleanly | — |
| ✅ | Assimilate the upstream schema into idiomatic pgdorm | 17 assimilation ops applied cleanly, 0 blockers, 0 residual ops | — |
| ✅ | Run core BaseCheckpointSaver operations (put, lineage, get_latest) | 3 of 3 named queries, each graded upstream | — |
| ✅ | Run real LangGraph StateGraph workflows on pgdorm | 3 live StateGraph flows verified (1-RTT aput, <=2-RTT zero-N+1 history) | — |