Skip to content

API Reference

open_postgres_checkpointer

A LangGraph Postgres checkpointer that stores changed values as small patches on langgraph-checkpoint-postgres tables.

AsyncOpenPostgresCheckpointer

AsyncOpenPostgresCheckpointer(pool: AsyncConnectionPool[AsyncConnection[Any]], *, serde: SerializerProtocol | None = None, full_copies_only: bool = False, base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES)

Bases: BaseCheckpointSaver[str]

A LangGraph checkpointer on upstream langgraph-checkpoint-postgres's tables.

Each operation takes its own connection from pool; nothing serialises the saver. Every pooled connection must be in autocommit mode (kwargs={"autocommit": True}), or the first operation raises PoolConfigError. The first operation also checks upstream's migration ledger and the saver's own (opc_migrations), and raises MigrationError unless both are at the heads this saver knows; setup() brings a database there.

Async only: the synchronous methods are the base class's, which raise NotImplementedError; OpenPostgresCheckpointer is the sync saver.

Patches are on by default. full_copies_only=True writes only rows upstream's saver can read, and still reads patches: a fleet deploys with it everywhere, then turns patches on. base_cache_bytes bounds the full copies held in memory to patch against.

Serializing stored values and writes, compressing, patching and decoding them run on one thread per saver, never on the event loop, so zstd's large, short-lived buffers come from one allocator arena instead of one per worker thread. The checkpoint's inline JSON (primitive channel values of any size stay there) and its metadata are encoded and decoded by psycopg on the event loop, as upstream's are. glibc may still keep freed buffers in the process; an operator who needs the resident size close to the cache bound can set MALLOC_MMAP_THRESHOLD_=131072 in the environment (the saver never changes allocator settings itself).

Lifecycle: use async with (or from_conn_string) or call await saver.aclose() on shutdown so the codec worker thread is drained and closed. Closing the saver does not close a caller-owned pool.

Parameters:

Name Type Description Default
pool AsyncConnectionPool[AsyncConnection[Any]]

psycopg_pool.AsyncConnectionPool handing out autocommit connections. A single AsyncConnection, which upstream's saver takes, raises TypeError (ADR-0042).

required
serde SerializerProtocol | None

Optional checkpoint serializer (defaults to LangGraph's JsonPlusSerializer).

None
full_copies_only bool

When True, write only plain langgraph-checkpoint-postgres rows (useful during rolling deploys) while still reading patches.

False
base_cache_bytes int

Byte bound on the in-memory LRU cache of full-copy bases (default 64 MiB; 0 disables caching).

DEFAULT_BASE_CACHE_BYTES
Source code in src/open_postgres_checkpointer/aio.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def __init__(
    self,
    pool: AsyncConnectionPool[AsyncConnection[Any]],
    *,
    serde: SerializerProtocol | None = None,
    full_copies_only: bool = False,
    base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES,
) -> None:
    # Upstream's saver also takes one connection or a sync pool, so a swapped class
    # name reaches here.
    if isinstance(pool, (AsyncConnection, Connection, ConnectionPool)):
        msg = (
            "pool must be a psycopg_pool.AsyncConnectionPool, not "
            f"{type(pool).__name__}: each operation takes its own connection from it. "
            "For a single connection, use from_conn_string(conn_string, max_size=1); "
            "for synchronous code, use OpenPostgresCheckpointer.from_conn_string(conn_string)."
        )
        raise TypeError(msg)
    super().__init__(serde=serde)
    self.pool = pool
    self.full_copies_only = full_copies_only

    # The latest full copy per channel, to patch new values against; LRU, byte-bounded.
    # A per-process speed-up only: every patch names its base row, which the database
    # must hold.
    self._base_cache = _patch.BaseCache(base_cache_bytes)

    # Shared mutable state across this saver and with_allowlist() clones: the single
    # codec thread (keeps zstd off the event loop and in one malloc arena), closed
    # flag, patching-off switch, and whether migration ledgers were confirmed current.
    self._codec_state = _CodecState(
        ThreadPoolExecutor(max_workers=1, thread_name_prefix="opc-codec")
    )
    self._owns_codec = True

aclose async

aclose() -> None

Shut down this saver's codec thread and release its cached bases.

Idempotent: calling it more than once is a no-op. Leaves self.pool open, since callers who passed a pool own its lifecycle. Calling it on a clone returned by with_allowlist is a no-op so the owning saver stays usable.

Source code in src/open_postgres_checkpointer/aio.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
async def aclose(self) -> None:
    """Shut down this saver's codec thread and release its cached bases.

    Idempotent: calling it more than once is a no-op. Leaves ``self.pool`` open,
    since callers who passed a pool own its lifecycle. Calling it on a clone returned
    by ``with_allowlist`` is a no-op so the owning saver stays usable.
    """
    if not self._owns_codec or self._codec_state.closed:
        return
    self._codec_state.closed = True
    self._base_cache.clear()
    executor = self._codec_state.executor
    try:
        # Drain queued jobs instead of cancelling them: cancelling a future turns it
        # into a bare CancelledError on callers (e.g. a TaskGroup or LangGraph).
        await asyncio.get_running_loop().run_in_executor(
            None, lambda: executor.shutdown(wait=True)
        )
    except BaseException:
        executor.shutdown(wait=False)
        raise

acopy_thread async

acopy_thread(source_thread_id: str, target_thread_id: str) -> None

Copy every checkpoint, write and stored value of a thread to another thread.

The copy keeps checkpoint ids, parents, namespaces and pending writes, and copies patches as patches, so each copied checkpoint reads back as its source does, DeltaChannel history included (the whole parent chain comes along). It reads one snapshot of the source: a run writing to it meanwhile is copied entirely or not at all. A source with no rows copies nothing. The target gets a head row of its own, at the source's newest root checkpoint under a new generation, so no token read from an earlier thread of the target's id admits a put to it.

Raises:

Type Description
ValueError

the target thread already has rows, including when a concurrent copy to the same target won (copies to one target run one at a time) or a put to it committed while the copy ran.

CheckpointerError

rehydrate has turned patching off but the source still holds rows of this saver's; finish rehydrate, then copy.

Source code in src/open_postgres_checkpointer/aio.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
async def acopy_thread(self, source_thread_id: str, target_thread_id: str) -> None:
    """Copy every checkpoint, write and stored value of a thread to another thread.

    The copy keeps checkpoint ids, parents, namespaces and pending writes, and copies
    patches as patches, so each copied checkpoint reads back as its source does,
    ``DeltaChannel`` history included (the whole parent chain comes along). It reads
    one snapshot of the source: a run writing to it meanwhile is copied entirely or
    not at all. A source with no rows copies nothing. The target gets a head row of
    its own, at the source's newest root checkpoint under a new generation, so no
    token read from an earlier thread of the target's id admits a put to it.

    Raises:
        ValueError: the target thread already has rows, including when a concurrent
            copy to the same target won (copies to one target run one at a time) or a
            put to it committed while the copy ran.
        CheckpointerError: ``rehydrate`` has turned patching off but the source still
            holds rows of this saver's; finish ``rehydrate``, then copy.
    """
    params = {"source": str(source_thread_id), "target": str(target_thread_id)}
    target_exists_msg = (
        f"thread {target_thread_id!r} already exists; copy_thread wrote nothing"
    )
    async with self._connection() as conn:
        try:
            # tuple rows whatever the pool's row factory (upstream's pools use dict_row)
            async with (
                conn.transaction(),
                conn.cursor(row_factory=tuple_row) as cur,
            ):
                # 1. Wait for any other copy to the same target.
                await cur.execute(_sql.COPY_LOCK_SQL, params)
                # 2. Copy in one statement. It copies nothing when the target has
                # rows (occupied), or when rehydrate has turned patching off and
                # the source holds rows of ours (refused).
                await cur.execute(_sql.COPY_THREAD_SQL, params)
                occupied, refused, copied = cast(
                    "tuple[bool, bool, int]", await cur.fetchone()
                )
                if not (occupied or refused):
                    # 3. Count the target's rows in a newer snapshot. A put to the
                    # target that the copy waited on (its head row) shows here but
                    # not in the copy's snapshot. Refuse, as if the put came first;
                    # raising here rolls the copy back.
                    await cur.execute(_sql.COPY_TARGET_ROWS_SQL, params)
                    (target_rows,) = cast("tuple[int]", await cur.fetchone())
                    if target_rows != copied:
                        raise ValueError(target_exists_msg)
        except UniqueViolation as e:  # a run's put to the target won the race
            raise ValueError(target_exists_msg) from e
    if occupied:
        raise ValueError(target_exists_msg)
    if refused:
        self._turn_patching_off()
        msg = (
            f"thread {source_thread_id!r} still holds rows in this saver's format "
            "(patches, compressed values or compressed pending writes), but "
            "rehydrate has turned patching off; copy_thread wrote nothing. Run "
            "rehydrate to the end first."
        )
        raise CheckpointerError(msg)

adelete_for_runs async

adelete_for_runs(run_ids: Sequence[str]) -> None

Delete the checkpoints of the given runs, in every thread and namespace, with their writes.

Matching: a checkpoint belongs to a run when its metadata's run_id is one of run_ids; LangGraph puts it there only when the caller passed run_id in config metadata (or configurable), so a plain invoke has none. Each affected thread then goes as aprune's keep_latest does, with every checkpoint of another run kept: a subgraph call goes with its root checkpoint, and a kept checkpoint whose parent is deleted is left with no parent.

Not an erasure guarantee:

  • What a kept checkpoint reads stays: a deleted checkpoint's full copy while a kept patch rests on it, and on a DeltaChannel thread every checkpoint, deleted run or not, that a kept checkpoint's history walks through back to its snapshot.
  • A copied thread (acopy_thread) carries its source's run ids, so its checkpoints match too.
  • The stored values each namespace's newest checkpoint names stay even when that checkpoint goes: a run still writing, or one that starts from that checkpoint, may commit a checkpoint after the thread's snapshot that names them without writing them again. They stay until a later prune or delete deletes a checkpoint of the thread, or the thread is deleted; a thread left with no checkpoint keeps them until adelete_thread, and acopy_thread refuses it as a target until then.
  • A fork from an older deleted checkpoint during the delete is unsafe, as for aprune.
  • Once the delete commits, a run holding its read's token that goes on from a checkpoint the delete removed is refused at its next put with ThreadConflictError.

The count matched and deleted is logged at INFO.

Raises:

Type Description
TypeError

run_ids is a single string.

Source code in src/open_postgres_checkpointer/aio.py
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
async def adelete_for_runs(self, run_ids: Sequence[str]) -> None:
    """Delete the checkpoints of the given runs, in every thread and namespace, with
    their writes.

    Matching: a checkpoint belongs to a run when its metadata's ``run_id`` is one of
    ``run_ids``; LangGraph puts it there only when the caller passed ``run_id`` in
    config ``metadata`` (or ``configurable``), so a plain ``invoke`` has none. Each
    affected thread then goes as ``aprune``'s keep_latest does, with every checkpoint
    of another run kept: a subgraph call goes with its root checkpoint, and a kept
    checkpoint whose parent is deleted is left with no parent.

    Not an erasure guarantee:

    - What a kept checkpoint reads stays: a deleted checkpoint's full copy while a kept
      patch rests on it, and on a ``DeltaChannel`` thread every checkpoint, deleted run
      or not, that a kept checkpoint's history walks through back to its snapshot.
    - A copied thread (``acopy_thread``) carries its source's run ids, so its
      checkpoints match too.
    - The stored values each namespace's newest checkpoint names stay even when that
      checkpoint goes: a run still writing, or one that starts from that checkpoint, may
      commit a checkpoint after the thread's snapshot that names them without writing
      them again. They stay until a later prune or delete deletes a checkpoint of the
      thread, or the thread is deleted; a thread left with no checkpoint keeps them
      until ``adelete_thread``, and ``acopy_thread`` refuses it as a target until then.
    - A fork from an older deleted checkpoint during the delete is unsafe, as for
      ``aprune``.
    - Once the delete commits, a run holding its read's token that goes on from a
      checkpoint the delete removed is refused at its next put with
      ``ThreadConflictError``.

    The count matched and deleted is logged at INFO.

    Raises:
        TypeError: ``run_ids`` is a single string.
    """
    if isinstance(run_ids, str):
        msg = "run_ids must be a sequence of run IDs, not a str"
        raise TypeError(msg)
    runs = {str(r) for r in run_ids}
    if not runs:
        return
    thread_rows = await self._fetch(_sql.RUN_THREADS_SQL, {"run_ids": list(runs)})
    # The policy appends each thread's count of matched checkpoints, for the log line.
    matched_per_thread: list[int] = []

    def policy(rows: Sequence[DictRow]) -> set[tuple[str, str]]:
        matched_rows = [r for r in rows if r["run_id"] in runs]
        matched_per_thread.append(len(matched_rows))
        return {
            (r["checkpoint_ns"], r["checkpoint_id"])
            for r in rows
            if r["run_id"] not in runs
        }

    self._base_cache.drop_threads({row["thread_id"] for row in thread_rows})
    deleted = 0
    for row in thread_rows:
        deleted += await self._retain(row["thread_id"], policy)
    _log.info(
        "delete_for_runs: %d checkpoints of %d runs matched in %d threads; %d checkpoints "
        "deleted (a matched checkpoint a kept one reads stays; a subgraph call goes with "
        "its root)",
        sum(matched_per_thread),
        len(runs),
        len(thread_rows),
        deleted,
    )

adelete_thread async

adelete_thread(thread_id: str) -> None

Delete every checkpoint, stored value and write of thread_id, and its head row, so a run that read the thread before is refused at its next put.

One transaction: it first waits for any put or write holding the thread's head row, so the delete includes what they commit.

Source code in src/open_postgres_checkpointer/aio.py
947
948
949
950
951
952
953
954
async def adelete_thread(self, thread_id: str) -> None:
    """Delete every checkpoint, stored value and write of ``thread_id``, and its head
    row, so a run that read the thread before is refused at its next put.

    One transaction: it first waits for any put or write holding the thread's head row,
    so the delete includes what they commit.
    """
    await self.aprune([thread_id], strategy="delete")

aget_delta_channel_history async

aget_delta_channel_history(*, config: RunnableConfig, channels: Sequence[str]) -> Mapping[str, DeltaChannelHistory]

Return each DeltaChannel's ordered pending writes and nearest snapshot seed.

Walks ancestor checkpoints along the parent chain starting at config's configurable.checkpoint_id (or the latest checkpoint in configurable.thread_id / configurable.checkpoint_ns when omitted) back to each channel's nearest snapshot seed, in a single query. Returns {} when channels is empty.

Source code in src/open_postgres_checkpointer/aio.py
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
async def aget_delta_channel_history(
    self, *, config: RunnableConfig, channels: Sequence[str]
) -> Mapping[str, DeltaChannelHistory]:
    """Return each `DeltaChannel`'s ordered pending writes and nearest snapshot seed.

    Walks ancestor checkpoints along the parent chain starting at `config`'s
    `configurable.checkpoint_id` (or the latest checkpoint in `configurable.thread_id`
    / `configurable.checkpoint_ns` when omitted) back to each channel's nearest
    snapshot seed, in a single query. Returns `{}` when `channels` is empty.
    """
    if not channels:
        return {}
    configurable = config.get("configurable", {})
    thread_id = configurable["thread_id"]
    checkpoint_ns = configurable.get("checkpoint_ns", "")
    checkpoint_id = get_checkpoint_id(config)
    rows = await self._fetch(
        _sql.DELTA_HISTORY_BY_ID_SQL
        if checkpoint_id
        else _sql.DELTA_HISTORY_LATEST_SQL,
        {
            "thread_id": thread_id,
            "checkpoint_ns": checkpoint_ns,
            "checkpoint_id": checkpoint_id,
            "channels": list(channels),
        },
    )
    return await self._on_codec_thread(
        lambda: self._load_delta_history(thread_id, checkpoint_ns, channels, rows)
    )

aget_tuple async

aget_tuple(config: RunnableConfig) -> CheckpointTuple | None

The checkpoint config names, or the latest of its thread and namespace.

A root-namespace tuple's config and parent_config carry the fence's token (see aput).

Source code in src/open_postgres_checkpointer/aio.py
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
    """The checkpoint ``config`` names, or the latest of its thread and namespace.

    A root-namespace tuple's ``config`` and ``parent_config`` carry the fence's token
    (see [`aput`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aput]).
    """
    configurable = config.get("configurable", {})
    thread_id: str = configurable["thread_id"]
    checkpoint_ns: str = configurable.get("checkpoint_ns", "")
    checkpoint_id = get_checkpoint_id(config)
    # Snapshot cached Base objects on the event loop so warm patched reads can skip
    # transferring base blobs over the wire, reuse their pre-built ZstdDicts, and
    # skip priming channels whose base is already held.
    prime_bound = (
        None
        if self._full_copies or self._base_cache.bound < _patch.MIN_COMPRESS_BYTES
        else self._base_cache.bound
    )
    cached_bases = (
        self._base_cache.scope_bases(thread_id, checkpoint_ns)
        if prime_bound is not None
        else {}
    )
    base_params: dict[str, Any] = {
        "thread_id": thread_id,
        "checkpoint_ns": checkpoint_ns,
        "checkpoint_id": checkpoint_id,
        "limit": 1,
    }
    if cached_bases:
        rows = await self._fetch_tuples(
            _sql.GET_BY_ID_SKIP_SQL if checkpoint_id else _sql.GET_LATEST_SKIP_SQL,
            {
                **base_params,
                "skip_channels": list(cached_bases),
                "skip_versions": [b.version for b in cached_bases.values()],
            },
        )
    else:
        rows = await self._fetch_tuples(
            _sql.GET_BY_ID_SQL if checkpoint_id else _sql.GET_LATEST_SQL,
            base_params,
        )
    if not rows:
        return None
    if cached_bases:
        for row in rows:
            if row[0] is not None:
                for channel, _ in row[8] or ():
                    if channel in cached_bases:
                        self._base_cache.get((thread_id, checkpoint_ns, channel))
                break
    try:
        tuples, primed = await self._on_codec_thread(
            lambda: self._load_page(
                rows, prime_bound=prime_bound, cached_bases=cached_bases
            )
        )
    except _patch.StaleCachedBaseError:
        # A wire-skipped cached base failed zstd's checksum (stale cache entry);
        # drop this scope's cached bases and re-fetch full blobs from Postgres.
        for ch in cached_bases:
            self._base_cache.drop((thread_id, checkpoint_ns, ch))
        rows = await self._fetch_tuples(
            _sql.GET_BY_ID_SQL if checkpoint_id else _sql.GET_LATEST_SQL,
            base_params,
        )
        if not rows:
            return None
        tuples, primed = await self._on_codec_thread(
            lambda: self._load_page(rows, prime_bound=prime_bound)
        )
    if not tuples:
        return None
    # checked again: another task may have turned patching off or closed the saver
    if self._can_cache:
        # The run's own read primes its next put: each
        # value's full copy, or a patch's base, is what that put patches against.
        for channel_key, base in primed:
            cached = self._base_cache.get(channel_key)
            if cached is None or cached.version != base.version:
                self._base_cache.put(channel_key, base)
    return tuples[0]

alist async

alist(config: RunnableConfig | None, *, filter: dict[str, Any] | None = None, before: RunnableConfig | None = None, limit: int | None = None) -> AsyncIterator[CheckpointTuple]

Checkpoints newest first, in pages; each page reads each stored value once.

Root-namespace tuples carry the fence's token, as aget_tuple's do.

Without a checkpoint_ns in config (or with no config) the matching checkpoints' keys are read first, in one statement, and held while the caller iterates: pass limit when listing a whole database this way.

Source code in src/open_postgres_checkpointer/aio.py
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
async def alist(
    self,
    config: RunnableConfig | None,
    *,
    filter: dict[str, Any] | None = None,  # noqa: A002 -- the base class's name
    before: RunnableConfig | None = None,
    limit: int | None = None,
) -> AsyncIterator[CheckpointTuple]:
    """Checkpoints newest first, in pages; each page reads each stored value once.

    Root-namespace tuples carry the fence's token, as
    [`aget_tuple`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aget_tuple]'s do.

    Without a ``checkpoint_ns`` in ``config`` (or with no ``config``) the matching
    checkpoints' keys are read first, in one statement, and held while the caller
    iterates: pass ``limit`` when listing a whole database this way.
    """
    # 1. The filter: one SQL predicate per argument given, ANDed.
    wheres: list[LiteralString] = []
    params: dict[str, Any] = {}
    if config:
        configurable = config.get("configurable", {})
        wheres.append("thread_id = %(thread_id)s")
        params["thread_id"] = configurable["thread_id"]
        if (checkpoint_ns := configurable.get("checkpoint_ns")) is not None:
            wheres.append("checkpoint_ns = %(checkpoint_ns)s")
            params["checkpoint_ns"] = checkpoint_ns
        if checkpoint_id := get_checkpoint_id(config):
            wheres.append("checkpoint_id = %(checkpoint_id)s")
            params["checkpoint_id"] = checkpoint_id
    if filter:
        wheres.append("metadata @> %(filter)s")
        params["filter"] = Jsonb(filter)
    if before is not None:
        wheres.append("checkpoint_id < %(before)s")
        params["before"] = get_checkpoint_id(before)
    where: LiteralString = " AND ".join(wheres) or "TRUE"
    if limit == 0:
        return

    # 2. How a page of rows becomes tuples, and where the next page starts.
    async def load(rows: list[tuple[Any, ...]]) -> list[CheckpointTuple]:
        if not rows:
            return []
        tuples, _ = await self._on_codec_thread(lambda: self._load_page(rows))
        return tuples

    def cursor(last_tuple: CheckpointTuple) -> dict[str, Any]:
        """The params of `_sql.AFTER`: the key of the last tuple yielded."""
        last = last_tuple.config.get("configurable", {})
        return {
            "after_id": last["checkpoint_id"],
            "after_thread": last["thread_id"],
            "after_ns": last["checkpoint_ns"],
        }

    # 3a. Across namespaces: no index orders checkpoints across namespaces, so a
    #     keyset page would read every row below its cursor. Read the keys once, then
    #     load a page at a time.
    if "checkpoint_ns" not in params:
        keys = await self._fetch_tuples(
            _sql.list_keys_sql(where), {**params, "limit": limit}
        )
        for start in range(0, len(keys), _LIST_PAGE_SIZE):
            page_keys = keys[start : start + _LIST_PAGE_SIZE]
            rows = await self._fetch_tuples(
                _sql.SELECT_BY_KEYS_SQL,
                {
                    "threads": [key[0] for key in page_keys],
                    "nss": [key[1] for key in page_keys],
                    "ids": [key[2] for key in page_keys],
                },
            )
            for checkpoint_tuple in await load(rows):
                yield checkpoint_tuple
        return

    # 3b. In one thread and namespace: keyset pages, each starting after the last tuple yielded.
    async for checkpoint_tuple in self._paged(
        _sql.select_sql(where),
        _sql.select_sql(" AND ".join([*wheres, _sql.AFTER])),
        params,
        limit,
        load,
        cursor,
        fetch=self._fetch_tuples,
    ):
        yield checkpoint_tuple

aprune async

aprune(thread_ids: Sequence[str], *, strategy: str = 'keep_latest', keep_last: int | None = None) -> None

Delete checkpoints of thread_ids that a retention strategy does not keep.

Strategies:

  • "delete" removes every row of the threads, in one transaction, as adelete_thread does. The other strategies never touch a thread's head row.
  • "keep_latest" keeps, per namespace, the latest checkpoint, as upstream's prune does.
  • "keep_latest" with keep_last=N thins instead: per namespace, the latest N plus the latest checkpoint of each run, by the run_id in checkpoint metadata (it is there only when the caller passed it in config metadata or configurable).

Always kept ("keep_latest", either way):

  • As upstream does, a pre-v4 kept checkpoint's parent that holds its pending sends.
  • A subgraph call's namespace is deleted together with the root checkpoint the call started from.
  • What a kept checkpoint reads: every stored value it names with each patch's full copy.
  • On a DeltaChannel thread, the ancestors its history walks back to each channel's snapshot, with their writes, so a DeltaChannel thread is pruned, not refused. A checkpoint kept only as such an ancestor reads back its own stored values, but not necessarily its own DeltaChannel history.
  • A kept checkpoint whose parent is deleted is left with no parent.

Concurrency:

  • Each thread is pruned in its own transaction on one snapshot of it, so a run appending to the thread meanwhile is safe; forking or replaying from a checkpoint being deleted is not, as upstream's.
  • A thread another transaction changes meanwhile fails whole, leaving the threads before it pruned, and retrying is safe.
  • It fails with psycopg.errors.SerializationFailure when the transaction changed a row this one changes (a second prune, say).
  • It fails with psycopg.errors.ForeignKeyViolation when a writer committed a patch against a full copy this one deletes (the foreign key's check reads the latest snapshot).

Raises:

Type Description
TypeError

thread_ids is a single string.

ValueError

an unknown strategy, keep_last with a strategy other than "keep_latest", or keep_last below 1.

Source code in src/open_postgres_checkpointer/aio.py
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
async def aprune(
    self,
    thread_ids: Sequence[str],
    *,
    strategy: str = "keep_latest",
    keep_last: int | None = None,
) -> None:
    """Delete checkpoints of ``thread_ids`` that a retention strategy does not keep.

    Strategies:

    - ``"delete"`` removes every row of the threads, in one transaction, as
      ``adelete_thread`` does. The other strategies never touch a thread's head row.
    - ``"keep_latest"`` keeps, per namespace, the latest checkpoint, as upstream's
      ``prune`` does.
    - ``"keep_latest"`` with ``keep_last=N`` thins instead: per namespace, the latest
      ``N`` plus the latest checkpoint of each run, by the ``run_id`` in checkpoint
      metadata (it is there only when the caller passed it in config ``metadata`` or
      ``configurable``).

    Always kept (``"keep_latest"``, either way):

    - As upstream does, a pre-v4 kept checkpoint's parent that holds its pending sends.
    - A subgraph call's namespace is deleted together with the root checkpoint the call
      started from.
    - What a kept checkpoint reads: every stored value it names with each patch's full
      copy.
    - On a ``DeltaChannel`` thread, the ancestors its history walks back to each
      channel's snapshot, with their writes, so a ``DeltaChannel`` thread is pruned, not
      refused. A checkpoint kept only as such an ancestor reads back its own stored
      values, but not necessarily its own ``DeltaChannel`` history.
    - A kept checkpoint whose parent is deleted is left with no parent.

    Concurrency:

    - Each thread is pruned in its own transaction on one snapshot of it, so a run
      appending to the thread meanwhile is safe; forking or replaying from a checkpoint
      being deleted is not, as upstream's.
    - A thread another transaction changes meanwhile fails whole, leaving the threads
      before it pruned, and retrying is safe.
    - It fails with ``psycopg.errors.SerializationFailure`` when the transaction changed
      a row this one changes (a second prune, say).
    - It fails with ``psycopg.errors.ForeignKeyViolation`` when a writer committed a
      patch against a full copy this one deletes (the foreign key's check reads the
      latest snapshot).

    Raises:
        TypeError: ``thread_ids`` is a single string.
        ValueError: an unknown ``strategy``, ``keep_last`` with a strategy other than
            ``"keep_latest"``, or ``keep_last`` below 1.
    """
    if isinstance(thread_ids, str):
        msg = "thread_ids must be a sequence of thread IDs, not a str"
        raise TypeError(msg)
    if strategy not in ("keep_latest", "delete"):
        msg = f"Unknown prune strategy: {strategy!r}"
        raise ValueError(msg)
    if keep_last is not None and strategy != "keep_latest":
        msg = f"keep_last applies only to strategy='keep_latest', not {strategy!r}"
        raise ValueError(msg)
    if keep_last is not None and keep_last < 1:
        msg = f"keep_last must be at least 1; got {keep_last!r}"
        raise ValueError(msg)
    threads = list(dict.fromkeys(str(t) for t in thread_ids))
    if not threads:
        return
    self._base_cache.drop_threads(set(threads))
    if strategy == "delete":
        params = {"thread_ids": threads}
        async with self._connection() as conn, conn.transaction():
            await conn.execute(_sql.DELETE_LOCK_SQL, params)
            await conn.execute(_sql.DELETE_THREADS_SQL, params)
        return
    keep_per_ns = keep_last or 1

    def policy(rows: Sequence[DictRow]) -> set[tuple[str, str]]:
        kept: set[tuple[str, str]] = set()
        rank_in_ns: dict[str, int] = {}
        runs_seen: set[tuple[str, str]] = set()  # (checkpoint_ns, run_id)
        for r in rows:  # newest first per namespace
            ns = r["checkpoint_ns"]
            key = (ns, r["checkpoint_id"])
            rank_in_ns[ns] = rank_in_ns.get(ns, 0) + 1
            if rank_in_ns[ns] <= keep_per_ns:
                kept.add(key)
            # Thinning also keeps each run's first row in the namespace: its newest.
            run_id = r["run_id"]
            if keep_last is not None and run_id is not None:
                if (ns, run_id) not in runs_seen:
                    kept.add(key)
                runs_seen.add((ns, run_id))
        return kept

    for thread_id in threads:
        await self._retain(thread_id, policy)

aput async

aput(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: ChannelVersions) -> RunnableConfig

Store a checkpoint and its changed values in one statement.

The fence: a read of this saver hands out a token, and LangGraph passes it on to every put of the run. A put in the root namespace that carries a token is admitted only when one of these holds:

  • it continues from the thread's head (its parent is the head);
  • no writer of ours has moved the head since the read, and the put starts from the checkpoint that read returned (time travel, or a deliberate fork);
  • it retries a put that already committed (the head is already this checkpoint);
  • the thread has no head row, the read found none either, and the put starts from the checkpoint that read returned.

All but the retry also need the parent checkpoint to still exist. A put without a token, or in a subgraph's namespace, is admitted, as upstream's is.

Raises:

Type Description
ThreadConflictError

the fence refused the put; nothing was written and the saver does not retry it.

Source code in src/open_postgres_checkpointer/aio.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
async def aput(
    self,
    config: RunnableConfig,
    checkpoint: Checkpoint,
    metadata: CheckpointMetadata,
    new_versions: ChannelVersions,
) -> RunnableConfig:
    """Store a checkpoint and its changed values in one statement.

    The fence: a read of this saver hands out a token, and LangGraph passes it on to
    every put of the run. A put in the root namespace that carries a token is admitted
    only when one of these holds:

    - it continues from the thread's head (its parent is the head);
    - no writer of ours has moved the head since the read, and the put starts from
      the checkpoint that read returned (time travel, or a deliberate fork);
    - it retries a put that already committed (the head is already this checkpoint);
    - the thread has no head row, the read found none either, and the put starts
      from the checkpoint that read returned.

    All but the retry also need the parent checkpoint to still exist. A put without a
    token, or in a subgraph's namespace, is admitted, as upstream's is.

    Raises:
        ThreadConflictError: the fence refused the put; nothing was written and the
            saver does not retry it.
    """
    configurable = config.get("configurable", {})
    thread_id = configurable["thread_id"]
    checkpoint_ns = configurable["checkpoint_ns"]

    # 1. Split the values. As upstream: primitives stay inline in the checkpoint
    # row, everything else goes to checkpoint_blobs, and a _DeltaSnapshot leaves a
    # `true` marker inline. Copies, so the caller's checkpoint is never changed.
    inline_values: dict[str, Any] = {}
    blob_values: dict[str, Any] = {}
    for k, v in checkpoint["channel_values"].items():
        if isinstance(v, _DeltaSnapshot):
            inline_values[k] = True
            if k in new_versions:
                blob_values[k] = v
        elif v is None or isinstance(v, (str, int, float, bool)):
            inline_values[k] = v
        elif k in new_versions:
            blob_values[k] = v
    row_checkpoint = checkpoint.copy()
    row_checkpoint["channel_values"] = inline_values

    # 2 & 3. Serialize and encode the blob values this put changed in one codec-thread
    # hop whenever their bases are already held in memory (the common warm-cache path).
    # Unchanged channels are already stored under their current version.
    changed = [k for k in new_versions if k in blob_values]
    parent_id: str | None = configurable.get("checkpoint_id")
    values: list[_Value] = []
    pre_encoded: list[tuple[_Value, _patch.Encoded]] = []
    ready_bases: dict[str, _patch.Base] = {}

    if changed:
        # Snapshot held bases on the event loop before entering the codec thread
        # (BaseCache is event-loop-only).
        full_copies = self._full_copies
        bound = self._base_cache.bound
        cached_bases: dict[str, _patch.Base] = {}
        if not full_copies:
            for k in changed:
                if (
                    base := self._base_cache.get((thread_id, checkpoint_ns, k))
                ) is not None:
                    cached_bases[k] = base

        def dump_and_encode() -> tuple[
            list[_Value],
            dict[str, _patch.Encoded],
            dict[str, int],
            dict[str, _patch.Base],
        ]:
            vals: list[_Value] = []
            done: dict[str, _patch.Encoded] = {}
            missing_limits: dict[str, int] = {}
            built_bases: dict[str, _patch.Base] = {}
            for k in changed:
                typ, raw = self.serde.dumps_typed(blob_values[k])
                v = _Value(k, str(new_versions[k]), typ, raw)
                vals.append(v)
                if full_copies:
                    done[k] = _patch.Encoded(typ, raw, None)
                    continue
                base = cached_bases.get(k)
                if (
                    base is None
                    and _is_cacheable_channel(k)
                    and parent_id is not None
                    and len(raw) >= _patch.MIN_PATCH_BYTES
                    and (limit := min(bound, _patch.max_base_len(len(raw))))
                    >= _patch.MIN_COMPRESS_BYTES
                ):
                    missing_limits[k] = limit
                    continue
                done[k], built = _encode_with_base(v, base, bound)
                if built is not None:
                    built_bases[k] = built
            return vals, done, missing_limits, built_bases

        values, done, missing_limits, ready_bases = await self._on_codec_thread(
            dump_and_encode
        )

        # Cold-cache miss: fetch missing parent bases, then decode them and encode the
        # waiting channels together in one second codec hop (two hops total, not three).
        if missing_limits and not self._full_copies and parent_id is not None:
            missing_done, missing_bases = await self._fetch_and_encode_missing(
                thread_id,
                checkpoint_ns,
                parent_id,
                [v for v in values if v.channel in missing_limits],
                missing_limits,
                bound,
            )
            done |= missing_done
            ready_bases |= missing_bases
        elif missing_limits:
            # Patching turned off concurrently during hop #1: write plain rows.
            for v in values:
                if v.channel not in done:
                    done[v.channel] = _patch.Encoded(v.typ, v.raw, None)

        pre_encoded = [(v, done[v.channel]) for v in values]

    # 4. Write the checkpoint and its values in one statement, behind the fence.
    token = _head_token(configurable, thread_id)
    params: dict[str, Any] = {
        # str(token.seq) keeps OID 0 (TEXT) for both None and ints so psycopg prepares
        # PUT_SQL once instead of splitting across int2/int4/int8/NULL variants.
        "token_seq": None if token is None else str(token.seq),
        "token_at": None if token is None else token.checkpoint_id,
        "thread_id": thread_id,
        "checkpoint_ns": checkpoint_ns,
        "channels": [v.channel for v in values],
        "versions": [v.version for v in values],
        "checkpoint_id": checkpoint["id"],
        "parent_checkpoint_id": parent_id,
        "checkpoint": Jsonb(row_checkpoint),
        "metadata": Jsonb(get_serializable_checkpoint_metadata(config, metadata)),
    }
    # No per-(thread, ns) gate: LangGraph chains a run's puts itself; concurrent runs meet
    # the fence in PUT_SQL.
    try:
        stored = await self._store(params, pre_encoded)
    except ForeignKeyViolation:
        # A base was deleted (a prune, another process) after this writer last saw
        # it; the deferred key refused the patch at commit and nothing was written,
        # the head move included, so the retry meets the fence afresh as full copies.
        for v in values:
            self._base_cache.drop((thread_id, checkpoint_ns, v.channel))
        if values and not self._full_copies:
            retry_bound = self._base_cache.bound
            retry_done, ready_bases = await self._on_codec_thread(
                lambda: _encode_values(values, {}, retry_bound)
            )
            retry_encoded = [(v, retry_done[v.channel]) for v in values]
        else:
            retry_encoded = [
                (v, _patch.Encoded(v.typ, v.raw, None)) for v in values
            ]
            ready_bases = {}
        stored = await self._store(params, retry_encoded)

    # 5. Only now, after the commit, do new full copies become bases (the base cache holds
    # only bases the database has): a base the database never stored would make every
    # later patch against it fail.
    # - Internal channels (`__start__`, `__pregel_tasks`) are never cached or patched.
    # - Checked again, not repeated from step 2: _store turns patching off when
    #   `rehydrate` refused the put, and then no later put patches at all.
    if self._can_cache:
        for v, e in stored:
            if e.typ.startswith(_patch.PATCH_PREFIX) or not _is_cacheable_channel(
                v.channel
            ):
                continue
            if (new_base := ready_bases.get(v.channel)) is not None:
                self._base_cache.put(
                    (thread_id, checkpoint_ns, v.channel), new_base
                )
            else:
                # Value shrank below MIN_COMPRESS_BYTES or grew past cache bound.
                self._base_cache.drop((thread_id, checkpoint_ns, v.channel))
    return {
        "configurable": {
            "thread_id": thread_id,
            "checkpoint_ns": checkpoint_ns,
            "checkpoint_id": checkpoint["id"],
        }
    }

aput_writes async

aput_writes(config: RunnableConfig, writes: Sequence[tuple[str, Any]], task_id: str, task_path: str = '') -> None

Save the outputs one task produced during a step (its pending writes).

LangGraph calls this as each task of a step finishes, before the step's next checkpoint exists. If the step fails or is interrupted, a resumed run replays these saved writes instead of running the finished tasks again.

Each write is a (channel, value) pair. All of them go into checkpoint_writes in one SQL statement (upstream sends one per write), keyed by the checkpoint the step started from (config's checkpoint_id), the task's id and the write's index, so either every write of the task is stored or none is.

A thread with no head row gets one, so a thread whose only rows are writes still expires (asweep_expired); an existing head row is left as it is.

Source code in src/open_postgres_checkpointer/aio.py
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
async def aput_writes(
    self,
    config: RunnableConfig,
    writes: Sequence[tuple[str, Any]],
    task_id: str,
    task_path: str = "",
) -> None:
    """Save the outputs one task produced during a step (its *pending writes*).

    LangGraph calls this as each task of a step finishes, before the step's next
    checkpoint exists. If the step fails or is interrupted, a resumed run replays these
    saved writes instead of running the finished tasks again.

    Each write is a ``(channel, value)`` pair. All of them go into ``checkpoint_writes``
    in one SQL statement (upstream sends one per write), keyed by the checkpoint the
    step started from (``config``'s ``checkpoint_id``), the task's id and the write's
    index, so either every write of the task is stored or none is.

    A thread with no head row gets one, so a thread whose only rows are writes still
    expires ([`asweep_expired`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.asweep_expired]);
    an existing head row is left as it is.
    """
    if not writes:
        return
    upsert = all(channel in WRITES_IDX_MAP for channel, _ in writes)
    # Upstream runs one statement per write, so a repeated index ends as the last
    # write when it overwrites and the first when it does not; one statement may
    # not touch a row twice, so the same choice is made here.
    by_idx: dict[int, tuple[str, Any]] = {}
    for position, (channel, value) in enumerate(writes):
        idx = WRITES_IDX_MAP.get(channel, position)
        if upsert or idx not in by_idx:
            by_idx[idx] = (channel, value)
    full_copies = self._full_copies

    def dump() -> tuple[list[tuple[str, bytes]], list[_patch.Encoded]]:
        """Each write in upstream's exact form, and in the form to write now."""
        dumped = [self.serde.dumps_typed(v) for _, v in by_idx.values()]
        if full_copies:
            return dumped, [_patch.Encoded(t, raw, None) for t, raw in dumped]
        # A write has no base, so it is never a patch: compressed as a full copy when
        # that is smaller. The version only matters against a base.
        return dumped, [
            _patch.encode(t, raw, None, version="") for t, raw in dumped
        ]

    dumped, encoded = await self._on_codec_thread(dump)
    configurable = config.get("configurable", {})
    params = {
        "thread_id": configurable["thread_id"],
        "checkpoint_ns": configurable["checkpoint_ns"],
        "checkpoint_id": configurable["checkpoint_id"],
        "task_id": task_id,
        "task_path": task_path,
        # Int4 pins idx to OID 1007 (int4[]) so writes statements stay one prepared plan.
        "idx": [Int4(i) for i in by_idx],
        "channels": [c for c, _ in by_idx.values()],
    }
    query = _sql.UPSERT_WRITES_SQL if upsert else _sql.INSERT_WRITES_SQL
    if self._full_copies and not full_copies:
        encoded = [_patch.Encoded(t, raw, None) for t, raw in dumped]
    # Loops at most twice: a call refused because `rehydrate` turned patching off
    # wrote nothing, and is written again as upstream's rows, which hold no tag of
    # ours, so the switch does not refuse them.
    while True:
        rows = await self._fetch(
            query,
            {
                **params,
                "types": [e.typ for e in encoded],
                "blobs": [e.blob for e in encoded],
                "ours": any(e.typ.startswith(_patch.OUR_PREFIX) for e in encoded),
            },
        )
        if not rows[0]["refused"]:
            break
        self._turn_patching_off()
        encoded = [_patch.Encoded(t, raw, None) for t, raw in dumped]

asweep_expired async

asweep_expired(idle_for: timedelta, *, max_threads: int = 100) -> SweepReport

Delete whole threads that no root-namespace put of this saver touched for idle_for, on the database's clock; at most max_threads per call.

The application calls it on a schedule of its choosing; the saver starts no task. Each thread goes in its own transaction, deleting what adelete_thread deletes, so a write that committed before the delete is deleted with it. It first locks the thread's head row and checks it again. It skips, without waiting, a thread that:

  • a put is writing;
  • was written, deleted or re-created since this call picked it;
  • holds a root checkpoint newer than its head (langgraph-checkpoint-postgres wrote it, or puts committed out of id order). The thread's head moves to that checkpoint, and the thread is counted idle from now.

Cancelling a call leaves every thread swept or untouched. A thread swept under a running run is gone; that run's next put raises ThreadConflictError, so idle_for should exceed the longest run. Threads only langgraph-checkpoint-postgres wrote get a head row at setup() (counted idle from then), or at this saver's first write to them.

Raises:

Type Description
ValueError

idle_for is negative or max_threads is below 1.

Source code in src/open_postgres_checkpointer/aio.py
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
async def asweep_expired(
    self, idle_for: timedelta, *, max_threads: int = 100
) -> SweepReport:
    """Delete whole threads that no root-namespace put of this saver touched for
    `idle_for`, on the database's clock; at most `max_threads` per call.

    The application calls it on a schedule of its choosing; the saver starts no task.
    Each thread goes in its own transaction, deleting what `adelete_thread` deletes,
    so a write that committed before the delete is deleted with it. It first locks the
    thread's head row and checks it again. It skips, without waiting, a thread that:

    - a put is writing;
    - was written, deleted or re-created since this call picked it;
    - holds a root checkpoint newer than its head (`langgraph-checkpoint-postgres`
      wrote it, or puts committed out of id order). The thread's head moves to that
      checkpoint, and the thread is counted idle from now.

    Cancelling a call leaves every thread swept or untouched. A thread swept under a
    running run is gone; that run's next put raises
    [`ThreadConflictError`][open_postgres_checkpointer.ThreadConflictError], so
    `idle_for` should exceed the longest run. Threads only
    `langgraph-checkpoint-postgres` wrote get a head row at `setup()` (counted idle
    from then), or at this saver's first write to them.

    Raises:
        ValueError: `idle_for` is negative or `max_threads` is below 1.
    """
    if idle_for < timedelta(0):
        msg = f"idle_for must be non-negative; got {idle_for!r}"
        raise ValueError(msg)
    if max_threads < 1:
        msg = f"max_threads must be at least 1; got {max_threads!r}"
        raise ValueError(msg)
    # 1. Pick the idle threads, oldest first. One extra tells whether more wait.
    candidates = await self._fetch(
        _sql.SWEEP_CANDIDATES_SQL,
        {"idle_for": idle_for, "limit": max_threads + 1},
    )
    # 2. Delete each in its own transaction.
    skipped = failed = 0
    swept: set[str] = set()
    for candidate in candidates[:max_threads]:
        # the candidate's thread_id and seq, which the lock re-checks
        params = {**candidate, "idle_for": idle_for}
        deleted = False
        try:
            async with (
                self._connection() as conn,
                conn.transaction(),
                conn.cursor(row_factory=tuple_row) as cur,
            ):
                await cur.execute(_sql.SWEEP_LOCK_SQL, params)
                # no row: a put holds the head row, or the thread changed since
                # it was picked
                if await cur.fetchone() is not None:
                    await cur.execute(_sql.SWEEP_DELETE_SQL, params)
                    (deleted,) = cast("tuple[bool]", await cur.fetchone())
        except (ForeignKeyViolation, SerializationFailure):
            failed += 1
            continue
        if deleted:
            swept.add(candidate["thread_id"])
        else:
            skipped += 1
    # 3. Drop the swept threads' cached bases, in one scan of the cache. A base of
    # a swept thread held meanwhile is safe, as aput retries a patch whose base is
    # gone.
    self._base_cache.drop_threads(swept)
    return SweepReport(
        swept=len(swept),
        skipped=skipped,
        failed=failed,
        more=len(candidates) > max_threads,
    )

from_conn_string async classmethod

from_conn_string(conn_string: str, *, serde: SerializerProtocol | None = None, full_copies_only: bool = False, base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES, min_size: int | None = None, max_size: int | None = None, pool_kwargs: Mapping[str, Any] | None = None, conn_kwargs: Mapping[str, Any] | None = None) -> AsyncGenerator[Self]

A saver on its own pool of autocommit connections to conn_string; the pool and the saver's codec thread close on exit.

min_size and max_size size the pool (defaulting to a fixed pool of 4, or min(4, max_size) when only max_size < 4 is given). pool_kwargs are forwarded to AsyncConnectionPool (refusing open, kwargs, min_size and max_size). Unless pool_kwargs specifies check, the pool installs a zero-RTT socket-readability check on checkout that falls back to AsyncConnectionPool.check_connection on EOF/RST/activity (and sweeps other dead pooled sockets on failure); pass pool_kwargs={"check": None} to disable it or pool_kwargs={"check": AsyncConnectionPool.check_connection} to ping on every checkout. conn_kwargs are forwarded to each connection (and the startup probe), keeping prepare_threshold=0, TCP keepalives (keepalives=1, keepalives_idle=30, keepalives_interval=10, keepalives_count=3), connect_timeout=10, and application_name="open-postgres-checkpointer" by default (respecting values already set in conn_string, conn_kwargs, or PGCONNECT_TIMEOUT / PGAPPNAME), and requiring autocommit=True.

Opens and closes one connection first, so a bad conn_string raises psycopg's OperationalError at once, not the pool's PoolTimeout on the first operation.

Source code in src/open_postgres_checkpointer/aio.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
@classmethod
@asynccontextmanager
async def from_conn_string(
    cls,
    conn_string: str,
    *,
    serde: SerializerProtocol | None = None,
    full_copies_only: bool = False,
    base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES,
    min_size: int | None = None,
    max_size: int | None = None,
    pool_kwargs: Mapping[str, Any] | None = None,
    conn_kwargs: Mapping[str, Any] | None = None,
) -> AsyncGenerator[Self]:
    """A saver on its own pool of autocommit connections to ``conn_string``; the pool
    and the saver's codec thread close on exit.

    ``min_size`` and ``max_size`` size the pool (defaulting to a fixed pool of 4, or
    ``min(4, max_size)`` when only ``max_size < 4`` is given). ``pool_kwargs`` are
    forwarded to ``AsyncConnectionPool`` (refusing ``open``, ``kwargs``, ``min_size``
    and ``max_size``). Unless ``pool_kwargs`` specifies ``check``, the pool installs
    a zero-RTT socket-readability check on checkout that falls back to
    ``AsyncConnectionPool.check_connection`` on EOF/RST/activity (and sweeps other
    dead pooled sockets on failure); pass ``pool_kwargs={"check": None}`` to disable
    it or ``pool_kwargs={"check": AsyncConnectionPool.check_connection}`` to ping on
    every checkout. ``conn_kwargs`` are forwarded to each connection (and the
    startup probe), keeping ``prepare_threshold=0``, TCP keepalives
    (``keepalives=1``, ``keepalives_idle=30``, ``keepalives_interval=10``,
    ``keepalives_count=3``), ``connect_timeout=10``, and
    ``application_name="open-postgres-checkpointer"`` by default (respecting values
    already set in ``conn_string``, ``conn_kwargs``, or ``PGCONNECT_TIMEOUT`` /
    ``PGAPPNAME``), and requiring ``autocommit=True``.

    Opens and closes one connection first, so a bad ``conn_string`` raises psycopg's
    ``OperationalError`` at once, not the pool's ``PoolTimeout`` on the first operation.
    """
    if base_cache_bytes < 0:
        msg = f"base_cache_bytes must be non-negative; got {base_cache_bytes!r}"
        raise ValueError(msg)
    async with (
        _connection.open_pool(
            conn_string,
            min_size=min_size,
            max_size=max_size,
            pool_kwargs=pool_kwargs,
            conn_kwargs=conn_kwargs,
        ) as pool,
        cls(
            pool,
            serde=serde,
            full_copies_only=full_copies_only,
            base_cache_bytes=base_cache_bytes,
        ) as saver,
    ):
        yield saver

get_next_version

get_next_version(current: str | None, channel: None) -> str

Return the next monotonic channel version string (zero-padded integer prefix with a random tie-breaker, matching langgraph-checkpoint-postgres so adopted threads preserve ordering).

Source code in src/open_postgres_checkpointer/aio.py
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
def get_next_version(self, current: str | None, channel: None) -> str:  # noqa: ARG002 -- the base signature
    """Return the next monotonic channel version string (zero-padded integer prefix
    with a random tie-breaker, matching `langgraph-checkpoint-postgres` so adopted
    threads preserve ordering)."""
    # Matches langgraph/checkpoint/postgres/base.py:826-835 (3.2.0).
    if current is None:
        current_v = 0
    elif isinstance(current, int):
        current_v = current
    else:
        current_v = int(current.split(".")[0])
    next_v = current_v + 1
    next_h = random.random()  # noqa: S311 -- a tie-breaker, not a secret
    return f"{next_v:032}.{next_h:016}"

setup async

setup() -> None

Run upstream's migrations, then ours, past their recorded heads.

When both are current it only reads the two ledgers, so a role without CREATE on the schema can call it at boot.

Raises:

Type Description
MigrationError

a ledger is ahead of the heads this saver knows, or setup() timed out waiting for the migration lock, colliding with upstream's setup(), or waiting for a table an open transaction holds.

Source code in src/open_postgres_checkpointer/aio.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
async def setup(self) -> None:
    """Run upstream's migrations, then ours, past their recorded heads.

    When both are current it only reads the two ledgers, so a role without ``CREATE``
    on the schema can call it at boot.

    Raises:
        MigrationError: a ledger is ahead of the heads this saver knows, or setup()
            timed out waiting for the migration lock, colliding with upstream's
            setup(), or waiting for a table an open transaction holds.
    """
    self._check_open()
    # Not _connection: its ledger check refuses a database that is behind, which is
    # the database this method is for.
    async with self.pool.connection() as conn:
        _connection.require_autocommit(conn)
        await migrate(conn)
    self._codec_state.migrations_checked = True

with_allowlist

with_allowlist(extra_allowlist: Collection[tuple[str, ...]]) -> BaseCheckpointSaver[str]

Clone with a stricter msgpack allowlist; the clone shares this saver's codec thread without owning its shutdown.

Source code in src/open_postgres_checkpointer/aio.py
372
373
374
375
376
377
378
379
380
def with_allowlist(
    self, extra_allowlist: Collection[tuple[str, ...]]
) -> BaseCheckpointSaver[str]:
    """Clone with a stricter msgpack allowlist; the clone shares this saver's codec
    thread without owning its shutdown."""
    clone = super().with_allowlist(extra_allowlist)
    if clone is not self:
        cast("AsyncOpenPostgresCheckpointer", clone)._owns_codec = False
    return clone

CheckpointerError

Bases: Exception

Base class for every error this package raises deliberately.

MigrationError

Bases: CheckpointerError

The schema is not at this saver's heads, or setup() could not bring it there.

Raised when either migration ledger (langgraph-checkpoint-postgres's checkpoint_migrations or this saver's opc_migrations) is missing, behind this saver's head, or ahead of it. Ahead means a newer langgraph-checkpoint-postgres or open-postgres-checkpointer migrated the database: its tables may no longer be the ones this saver writes, so it refuses instead of guessing.

setup() also raises it when its deadline runs out while waiting for the migration lock or while colliding with a concurrent setup() creating the same schema. Neither is a schema mismatch: call setup() again once the other session finishes.

OpenPostgresCheckpointer

OpenPostgresCheckpointer(saver: AsyncOpenPostgresCheckpointer, loop: AbstractEventLoop, gate: _LoopGate)

Bases: BaseCheckpointSaver[str]

The synchronous saver: AsyncOpenPostgresCheckpointer's behaviour, called from plain threads. Build it with from_conn_string. The constructor is internal: it needs a loop running in its own thread, which only from_conn_string provides.

Use it from code that has no running event loop of its own, as upstream's PostgresSaver. Its async methods are the base class's, which raise NotImplementedError; an async application uses the async saver. Use it inside its from_conn_string block and in the process that created it: a call after the block exits, or in a child forked after it was created, raises CheckpointerError.

Source code in src/open_postgres_checkpointer/sync.py
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    saver: AsyncOpenPostgresCheckpointer,
    loop: asyncio.AbstractEventLoop,
    gate: _LoopGate,
) -> None:
    super().__init__(serde=saver.serde)
    self._saver = saver
    self._loop = loop
    self._gate = gate
    self._pid = os.getpid()

copy_thread

copy_thread(source_thread_id: str, target_thread_id: str) -> None

AsyncOpenPostgresCheckpointer.acopy_thread.

Source code in src/open_postgres_checkpointer/sync.py
267
268
269
def copy_thread(self, source_thread_id: str, target_thread_id: str) -> None:
    """[`AsyncOpenPostgresCheckpointer.acopy_thread`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.acopy_thread]."""
    self._run(self._saver.acopy_thread(source_thread_id, target_thread_id))

delete_for_runs

delete_for_runs(run_ids: Sequence[str]) -> None

AsyncOpenPostgresCheckpointer.adelete_for_runs.

Source code in src/open_postgres_checkpointer/sync.py
263
264
265
def delete_for_runs(self, run_ids: Sequence[str]) -> None:
    """[`AsyncOpenPostgresCheckpointer.adelete_for_runs`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.adelete_for_runs]."""
    self._run(self._saver.adelete_for_runs(run_ids))

delete_thread

delete_thread(thread_id: str) -> None

AsyncOpenPostgresCheckpointer.adelete_thread.

Source code in src/open_postgres_checkpointer/sync.py
247
248
249
def delete_thread(self, thread_id: str) -> None:
    """[`AsyncOpenPostgresCheckpointer.adelete_thread`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.adelete_thread]."""
    self._run(self._saver.adelete_thread(thread_id))

from_conn_string classmethod

from_conn_string(conn_string: str, *, serde: SerializerProtocol | None = None, full_copies_only: bool = False, base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES, min_size: int | None = None, max_size: int | None = None, pool_kwargs: Mapping[str, Any] | None = None, conn_kwargs: Mapping[str, Any] | None = None) -> Generator[Self]

Open a sync saver backed by a pool of autocommit connections to conn_string; the pool and internal event-loop thread are closed on exit.

Arguments match AsyncOpenPostgresCheckpointer.from_conn_string. Any callback in pool_kwargs (such as check, configure, or reset) runs on the internal AsyncConnectionPool's event loop and must be an async callable.

Source code in src/open_postgres_checkpointer/sync.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@classmethod
@contextmanager
def from_conn_string(
    cls,
    conn_string: str,
    *,
    serde: SerializerProtocol | None = None,
    full_copies_only: bool = False,
    base_cache_bytes: int = DEFAULT_BASE_CACHE_BYTES,
    min_size: int | None = None,
    max_size: int | None = None,
    pool_kwargs: Mapping[str, Any] | None = None,
    conn_kwargs: Mapping[str, Any] | None = None,
) -> Generator[Self]:
    """Open a sync saver backed by a pool of autocommit connections to `conn_string`;
    the pool and internal event-loop thread are closed on exit.

    Arguments match
    [`AsyncOpenPostgresCheckpointer.from_conn_string`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.from_conn_string].
    Any callback in `pool_kwargs` (such as `check`, `configure`, or `reset`) runs on
    the internal `AsyncConnectionPool`'s event loop and must be an async callable.
    """
    creator_pid = os.getpid()
    loop = new_event_loop()
    gate = _LoopGate()
    thread = threading.Thread(
        target=loop.run_forever, name="opc-sync-loop", daemon=True
    )
    thread.start()
    try:
        async_block = AsyncOpenPostgresCheckpointer.from_conn_string(
            conn_string,
            serde=serde,
            full_copies_only=full_copies_only,
            base_cache_bytes=base_cache_bytes,
            min_size=min_size,
            max_size=max_size,
            pool_kwargs=pool_kwargs,
            conn_kwargs=conn_kwargs,
        )
        # The stack holds the async block open between two calls on the loop: one
        # enters it now, the other exits it when this block exits.
        stack = AsyncExitStack()
        saver = _run_on(loop, stack.enter_async_context(async_block), gate)
        try:
            yield cls(saver, loop, gate)
        finally:
            # Close the exit stack first so pool/codec teardown errors propagate
            # directly to the caller instead of being swallowed by shutdown_asyncgens.
            if os.getpid() == creator_pid:
                try:
                    _run_on(loop, stack.aclose(), gate)
                finally:
                    _run_on(loop, loop.shutdown_asyncgens(), gate)
    finally:
        # a forked child has neither the loop's thread nor the parent's pool to tear down
        if os.getpid() == creator_pid:
            with gate.lock:
                gate.closing = True
            loop.call_soon_threadsafe(loop.stop)
            thread.join()
            loop.close()

get_delta_channel_history

get_delta_channel_history(*, config: RunnableConfig, channels: Sequence[str]) -> Mapping[str, DeltaChannelHistory]

AsyncOpenPostgresCheckpointer.aget_delta_channel_history.

Source code in src/open_postgres_checkpointer/sync.py
271
272
273
274
275
276
277
def get_delta_channel_history(
    self, *, config: RunnableConfig, channels: Sequence[str]
) -> Mapping[str, DeltaChannelHistory]:
    """[`AsyncOpenPostgresCheckpointer.aget_delta_channel_history`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aget_delta_channel_history]."""
    return self._run(
        self._saver.aget_delta_channel_history(config=config, channels=channels)
    )

get_next_version

get_next_version(current: str | None, channel: None) -> str

AsyncOpenPostgresCheckpointer.get_next_version.

Source code in src/open_postgres_checkpointer/sync.py
285
286
287
def get_next_version(self, current: str | None, channel: None) -> str:
    """[`AsyncOpenPostgresCheckpointer.get_next_version`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.get_next_version]."""
    return self._saver.get_next_version(current, channel)

get_tuple

get_tuple(config: RunnableConfig) -> CheckpointTuple | None

AsyncOpenPostgresCheckpointer.aget_tuple.

Source code in src/open_postgres_checkpointer/sync.py
210
211
212
def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
    """[`AsyncOpenPostgresCheckpointer.aget_tuple`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aget_tuple]."""
    return self._run(self._saver.aget_tuple(config))

list

list(config: RunnableConfig | None, *, filter: dict[str, Any] | None = None, before: RunnableConfig | None = None, limit: int | None = None) -> Iterator[CheckpointTuple]

AsyncOpenPostgresCheckpointer.alist.

Source code in src/open_postgres_checkpointer/sync.py
214
215
216
217
218
219
220
221
222
223
224
225
def list(
    self,
    config: RunnableConfig | None,
    *,
    filter: dict[str, Any] | None = None,  # noqa: A002 -- the base class's name
    before: RunnableConfig | None = None,
    limit: int | None = None,
) -> Iterator[CheckpointTuple]:
    """[`AsyncOpenPostgresCheckpointer.alist`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.alist]."""
    return self._iterate(
        self._saver.alist(config, filter=filter, before=before, limit=limit)
    )

prune

prune(thread_ids: Sequence[str], *, strategy: str = 'keep_latest', keep_last: int | None = None) -> None

AsyncOpenPostgresCheckpointer.aprune.

Source code in src/open_postgres_checkpointer/sync.py
251
252
253
254
255
256
257
258
259
260
261
def prune(
    self,
    thread_ids: Sequence[str],
    *,
    strategy: str = "keep_latest",
    keep_last: int | None = None,
) -> None:
    """[`AsyncOpenPostgresCheckpointer.aprune`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aprune]."""
    self._run(
        self._saver.aprune(thread_ids, strategy=strategy, keep_last=keep_last)
    )

put

put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: ChannelVersions) -> RunnableConfig

AsyncOpenPostgresCheckpointer.aput.

Source code in src/open_postgres_checkpointer/sync.py
227
228
229
230
231
232
233
234
235
def put(
    self,
    config: RunnableConfig,
    checkpoint: Checkpoint,
    metadata: CheckpointMetadata,
    new_versions: ChannelVersions,
) -> RunnableConfig:
    """[`AsyncOpenPostgresCheckpointer.aput`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aput]."""
    return self._run(self._saver.aput(config, checkpoint, metadata, new_versions))

put_writes

put_writes(config: RunnableConfig, writes: Sequence[tuple[str, Any]], task_id: str, task_path: str = '') -> None

AsyncOpenPostgresCheckpointer.aput_writes.

Source code in src/open_postgres_checkpointer/sync.py
237
238
239
240
241
242
243
244
245
def put_writes(
    self,
    config: RunnableConfig,
    writes: Sequence[tuple[str, Any]],
    task_id: str,
    task_path: str = "",
) -> None:
    """[`AsyncOpenPostgresCheckpointer.aput_writes`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.aput_writes]."""
    self._run(self._saver.aput_writes(config, writes, task_id, task_path))

setup

setup() -> None

AsyncOpenPostgresCheckpointer.setup.

Source code in src/open_postgres_checkpointer/sync.py
206
207
208
def setup(self) -> None:
    """[`AsyncOpenPostgresCheckpointer.setup`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.setup]."""
    self._run(self._saver.setup())

sweep_expired

sweep_expired(idle_for: timedelta, *, max_threads: int = 100) -> SweepReport

AsyncOpenPostgresCheckpointer.asweep_expired.

Source code in src/open_postgres_checkpointer/sync.py
279
280
281
282
283
def sweep_expired(
    self, idle_for: timedelta, *, max_threads: int = 100
) -> SweepReport:
    """[`AsyncOpenPostgresCheckpointer.asweep_expired`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.asweep_expired]."""
    return self._run(self._saver.asweep_expired(idle_for, max_threads=max_threads))

with_allowlist

with_allowlist(extra_allowlist: Collection[tuple[str, ...]]) -> BaseCheckpointSaver[str]

AsyncOpenPostgresCheckpointer.with_allowlist.

Source code in src/open_postgres_checkpointer/sync.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def with_allowlist(
    self, extra_allowlist: Collection[tuple[str, ...]]
) -> BaseCheckpointSaver[str]:
    """[`AsyncOpenPostgresCheckpointer.with_allowlist`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer.with_allowlist]."""
    # The base class's clone sets only this wrapper's serde, which no call reads:
    # every call runs on the async saver, so clone the async saver instead.
    async_clone = self._saver.with_allowlist(extra_allowlist)
    if async_clone is self._saver:
        return self
    # typed as the base class, but the base class's clone is a copy.copy of the async saver
    clone = type(self)(
        cast("AsyncOpenPostgresCheckpointer", async_clone),
        self._loop,
        self._gate,
    )
    clone._pid = self._pid  # a clone made in a forked child must still refuse
    return clone

PatchError

Bases: CheckpointerError

A stored patch or saver-compressed full copy cannot be turned back into its value.

A patch's side row or base row is missing, its base is itself a patch, or the base holds bytes other than the ones the patch was made against (zstd's content checksum fails); or a full copy's zstd frame is damaged. The foreign key on opc_blob_patch makes a missing base impossible for rows this saver wrote; seeing this means the tables were changed outside the saver.

PoolConfigError

Bases: CheckpointerError

The connection pool hands out connections this saver cannot use.

Every pooled connection must be in autocommit mode, for two reasons:

  • setup() runs CREATE INDEX CONCURRENTLY (both langgraph-checkpoint-postgres migrations and ours), which cannot run inside a transaction block.
  • Every other operation either commits one statement on its own or opens its own transaction. That transaction must be a real one, not a savepoint inside an implicit one.

SweepReport dataclass

SweepReport(swept: int, skipped: int, failed: int, more: bool)

What one asweep_expired call did.

failed instance-attribute

failed: int

Candidates whose delete failed with ForeignKeyViolation (a patching writer committed against a value it deleted) or SerializationFailure; the next call tries them again.

more instance-attribute

more: bool

Whether more idle threads were found than the call's max_threads.

skipped instance-attribute

skipped: int

Candidates left alone: a put held the head row, or the thread was written, deleted or re-created since it was picked, or upstream wrote a newer checkpoint.

swept instance-attribute

swept: int

Threads deleted.

ThreadConflictError

Bases: CheckpointerError

Another writer moved the thread's head since this run read it; the put wrote nothing.

Raised from aput (put on the sync saver) when a run that read the thread through this saver tries to save a checkpoint that does not continue from the thread's current head (two runs racing on one thread, or a run continuing after the thread was deleted or expired). The saver does not retry it: the same put is refused again. Under LangGraph's default durability="async" the run's nodes have already run when this surfaces, so their side effects happened and are lost from the thread; durability="sync" stops the run at the refused put. The application decides whether to read the thread again and re-run on top of the winner.

ThreadInfo dataclass

ThreadInfo(config: RunnableConfig, metadata: CheckpointMetadata, created_at: str)

A thread as alist_threads lists it: its latest root checkpoint.

config instance-attribute

config: RunnableConfig

thread_id, checkpoint_ns ("") and checkpoint_id of that checkpoint; carries no optimistic-concurrency token, so passing it to a graph will not trigger ThreadConflictError.

created_at instance-attribute

created_at: str

That checkpoint's ts.

metadata instance-attribute

metadata: CheckpointMetadata

That checkpoint's metadata, as graph.aget_state(thread).metadata shows it.

alist_threads async

alist_threads(saver: AsyncOpenPostgresCheckpointer, *, filter: dict[str, Any] | None = None, before: RunnableConfig | None = None, limit: int | None = None) -> AsyncIterator[ThreadInfo]

Yield threads newest first by their latest root checkpoint, in one-statement pages.

A thread is listed when it has a root-namespace checkpoint; subgraph namespaces are never listed and never change a thread's place. Its entry is its latest root checkpoint (the highest checkpoint_id, as LangGraph reads "latest"), listed only when that checkpoint's metadata contains filter (@>, matching alist). Checkpoint metadata holds the keys a run passed in config metadata and configurable, so a key the application filters on must be passed on every run: a thread whose latest checkpoint lacks it is not listed. Threads written by langgraph-checkpoint-postgres list the same way. Ties on checkpoint_id (acopy_thread preserves ids, so a copy lists beside its source) are ordered by thread_id descending.

Each page is its own statement, so pages are not one snapshot: a thread written while the caller pages moves above the cursor and is not listed again in that pass (or, if not yet listed, is missed). A thread whose newest root checkpoint is deleted while the caller pages (adelete_for_runs, or a delete by other tooling) can be listed again under an older checkpoint; callers that need each thread once should dedupe by thread_id. A thread with many root checkpoints newer than the page's last entry costs one probe each, so an unfiltered page behind a busy thread reads more than its own rows.

Parameters:

Name Type Description Default
saver AsyncOpenPostgresCheckpointer

Checkpointer whose database to query.

required
filter dict[str, Any] | None

JSONB containment filter (@>) applied to each thread's latest root checkpoint metadata.

None
before RunnableConfig | None

A ThreadInfo.config from an earlier call; listing continues after it.

None
limit int | None

Maximum number of threads to yield.

None

Raises:

Type Description
ValueError

before lacks a valid configurable.thread_id or configurable.checkpoint_id.

Source code in src/open_postgres_checkpointer/listing.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
async def alist_threads(
    saver: AsyncOpenPostgresCheckpointer,
    *,
    filter: dict[str, Any] | None = None,  # noqa: A002 -- alist's name
    before: RunnableConfig | None = None,
    limit: int | None = None,
) -> AsyncIterator[ThreadInfo]:
    """Yield threads newest first by their latest root checkpoint, in one-statement pages.

    A thread is listed when it has a root-namespace checkpoint; subgraph namespaces are
    never listed and never change a thread's place. Its entry is its latest root
    checkpoint (the highest `checkpoint_id`, as LangGraph reads "latest"), listed only
    when that checkpoint's metadata contains `filter` (`@>`, matching `alist`).
    Checkpoint metadata holds the keys a run passed in config `metadata` and
    `configurable`, so a key the application filters on must be passed on every run: a
    thread whose latest checkpoint lacks it is not listed. Threads written by
    `langgraph-checkpoint-postgres` list the same way. Ties on `checkpoint_id`
    (`acopy_thread` preserves ids, so a copy lists beside its source) are ordered by
    `thread_id` descending.

    Each page is its own statement, so pages are not one snapshot: a thread written while
    the caller pages moves above the cursor and is not listed again in that pass (or, if
    not yet listed, is missed). A thread whose newest root checkpoint is deleted while
    the caller pages (`adelete_for_runs`, or a delete by other tooling) can be listed
    again under an older checkpoint; callers that need each thread once should dedupe by
    `thread_id`. A thread with many root checkpoints newer than the page's last entry
    costs one probe each, so an unfiltered page behind a busy thread reads more than its
    own rows.

    Args:
        saver: Checkpointer whose database to query.
        filter: JSONB containment filter (`@>`) applied to each thread's latest root
            checkpoint metadata.
        before: A [`ThreadInfo.config`][open_postgres_checkpointer.ThreadInfo.config]
            from an earlier call; listing continues after it.
        limit: Maximum number of threads to yield.

    Raises:
        ValueError: `before` lacks a valid `configurable.thread_id` or
            `configurable.checkpoint_id`.
    """
    # 1. Build the statements. Every page after the first starts after a cursor: the
    # last listed thread's (checkpoint_id, thread_id).
    wheres: list[LiteralString] = []
    params: dict[str, Any] = {}
    if filter:
        wheres.append("metadata @> %(filter)s")
        params["filter"] = Jsonb(filter)
    rest = _sql.list_threads_sql(" AND ".join([*wheres, _sql.LIST_THREADS_AFTER]))

    # 2. With ``before``, the first page also starts after a cursor: ``before``'s.
    if before is None:
        first = _sql.list_threads_sql(" AND ".join(wheres) or "TRUE")
    else:
        first = rest
        cursor = before.get("configurable")
        if (
            not isinstance(cursor, Mapping)
            or not isinstance(cursor.get("thread_id"), str)
            or not isinstance(cursor.get("checkpoint_id"), str)
            or not cursor["checkpoint_id"]
        ):
            keys = sorted(cursor.keys()) if isinstance(cursor, Mapping) else None
            msg = (
                "before must be a ThreadInfo.config with string configurable.thread_id "
                f"and non-empty configurable.checkpoint_id (configurable keys: {keys!r})"
            )
            raise ValueError(msg)
        params["after_id"] = cursor["checkpoint_id"]
        params["after_thread"] = cursor["thread_id"]

    # 3. Read page by page. ``load`` is async only because the pager awaits it: alist's
    # load decodes values on the codec thread, but a thread's entry holds no value.
    async def load(rows: list[DictRow]) -> list[ThreadInfo]:
        return [
            ThreadInfo(
                config={
                    "configurable": {
                        "thread_id": row["thread_id"],
                        "checkpoint_ns": "",
                        "checkpoint_id": row["checkpoint_id"],
                    }
                },
                metadata=row["metadata"],
                created_at=row["created_at"],
            )
            for row in rows
        ]

    def after(info: ThreadInfo) -> dict[str, Any]:
        """The next page's cursor: the page's last thread."""
        last = info.config.get("configurable", {})
        return {"after_id": last["checkpoint_id"], "after_thread": last["thread_id"]}

    async for info in saver._paged(  # pyright: ignore[reportPrivateUsage] -- alist's pager
        first,
        rest,
        params,
        limit,
        load,
        after,
        fetch=saver._fetch,  # pyright: ignore[reportPrivateUsage]
    ):
        yield info

list_threads

list_threads(saver: OpenPostgresCheckpointer, *, filter: dict[str, Any] | None = None, before: RunnableConfig | None = None, limit: int | None = None) -> Iterator[ThreadInfo]

alist_threads for the sync saver.

Source code in src/open_postgres_checkpointer/listing.py
148
149
150
151
152
153
154
155
156
157
158
def list_threads(
    saver: OpenPostgresCheckpointer,
    *,
    filter: dict[str, Any] | None = None,  # noqa: A002 -- alist's name
    before: RunnableConfig | None = None,
    limit: int | None = None,
) -> Iterator[ThreadInfo]:
    """[`alist_threads`][open_postgres_checkpointer.alist_threads] for the sync saver."""
    return saver._iterate(  # pyright: ignore[reportPrivateUsage] -- runs on the saver's loop
        alist_threads(saver._saver, filter=filter, before=before, limit=limit)  # pyright: ignore[reportPrivateUsage]
    )

open_pool async

open_pool(conn_string: str, *, min_size: int | None = None, max_size: int | None = None, pool_kwargs: Mapping[str, Any] | None = None, conn_kwargs: Mapping[str, Any] | None = None) -> AsyncGenerator[AsyncConnectionPool[AsyncConnection[Any]]]

Open a validated autocommit AsyncConnectionPool with a zero-RTT checkout check.

Validates pool_kwargs and conn_kwargs, opens and closes a startup probe connection so an unreachable conn_string raises OperationalError immediately rather than PoolTimeout, and installs a default checkout check (unless pool_kwargs specifies check) that sweeps remaining dead idle sockets in the background on failure.

This is the pool from_conn_string builds. An application that owns its checkpointer pool's lifecycle — for example in a web framework lifespan or across multiple savers — opens it here and passes it to AsyncOpenPostgresCheckpointer; the pool closes when this block exits, not when the saver does. Keep this pool dedicated to checkpointer traffic: its connections run with autocommit=True, prepare_threshold=0, and application_name="open-postgres-checkpointer".

Source code in src/open_postgres_checkpointer/_connection.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
@asynccontextmanager
async def open_pool(
    conn_string: str,
    *,
    min_size: int | None = None,
    max_size: int | None = None,
    pool_kwargs: Mapping[str, Any] | None = None,
    conn_kwargs: Mapping[str, Any] | None = None,
) -> AsyncGenerator[AsyncConnectionPool[AsyncConnection[Any]]]:
    """Open a validated autocommit ``AsyncConnectionPool`` with a zero-RTT checkout check.

    Validates ``pool_kwargs`` and ``conn_kwargs``, opens and closes a startup probe
    connection so an unreachable ``conn_string`` raises ``OperationalError`` immediately
    rather than ``PoolTimeout``, and installs a default checkout check (unless
    ``pool_kwargs`` specifies ``check``) that sweeps remaining dead idle sockets in the
    background on failure.

    This is the pool ``from_conn_string`` builds. An application that owns its
    checkpointer pool's lifecycle — for example in a web framework lifespan or across
    multiple savers — opens it here and passes it to
    [`AsyncOpenPostgresCheckpointer`][open_postgres_checkpointer.AsyncOpenPostgresCheckpointer];
    the pool closes when this block exits, not when the saver does. Keep this pool
    dedicated to checkpointer traffic: its connections run with ``autocommit=True``,
    ``prepare_threshold=0``, and ``application_name="open-postgres-checkpointer"``.
    """
    extra_pool: dict[str, Any] = dict(pool_kwargs or {})
    reserved = RESERVED_POOL_KWARGS.intersection(extra_pool)
    if reserved:
        names = ", ".join(sorted(reserved))
        msg = f"pool_kwargs cannot set reserved parameter(s): {names}"
        raise ValueError(msg)
    extra_conn: dict[str, Any] = dict(conn_kwargs or {})
    merged_conn_kwargs = merge_conn_kwargs(conn_string, extra_conn)
    resolved_min = (
        (4 if max_size is None else min(4, max_size)) if min_size is None else min_size
    )
    sweep_task: asyncio.Task[None] | None = None
    if "check" not in extra_pool:

        async def _sweep() -> None:
            with suppress(Exception):
                await pool.check()

        async def _default_check(conn: AsyncConnection[Any]) -> None:
            nonlocal sweep_task
            try:
                await check_connection_fast(conn)
            except Exception:
                # A Postgres restart kills every idle connection in the pool at once.
                # Without sweeping the remaining idle slots, psycopg_pool's backoff loop
                # pops and sleeps on each dead connection sequentially (1+2+4+8s, or
                # PoolTimeout on larger pools). One background pool.check() drains the
                # remaining dead sockets during the first backoff sleep.
                if not pool.closed and (sweep_task is None or sweep_task.done()):
                    sweep_task = asyncio.create_task(_sweep())
                raise

        extra_pool["check"] = _default_check

    # Construct with open=False before the probe so invalid sizes/kwargs fail at once
    # without touching the network.
    pool: AsyncConnectionPool[AsyncConnection[Any]] = AsyncConnectionPool(
        conn_string,
        min_size=resolved_min,
        max_size=max_size,
        kwargs=merged_conn_kwargs,
        open=False,
        **extra_pool,
    )
    conn_cls: type[AsyncConnection[Any]] = extra_pool.get(
        "connection_class", AsyncConnection
    )
    async with await conn_cls.connect(conn_string, **merged_conn_kwargs):
        pass
    async with pool:
        try:
            yield pool
        finally:
            if sweep_task is not None and not sweep_task.done():
                sweep_task.cancel()
                with suppress(asyncio.CancelledError):
                    await sweep_task

open_postgres_checkpointer.rehydrate

rehydrate: roll a database back to rows upstream's saver reads.

Every patch, every full copy and every pending write this saver compressed is rewritten in place as the serde's own bytes under the serde's own type, which is the row upstream would have written, and each patch's side row is deleted with it. The steps:

  1. Turn patching off (a row in opc_patching_off). From then on every put writes only upstream's rows; a running saver sees the switch on its next put.
  2. Wait until every transaction in this database that started before the switch has ended: those are the only puts that can still write a row of ours. A session left idle in a transaction holds rehydrate here until it ends; a warning names the sessions it waits for.
  3. Rewrite patches, then full copies, then compressed pending writes, in batches bounded by the bytes a batch holds in memory. Each batch is one statement, so an interrupted run leaves every row readable and a rerun continues where it stopped.
  4. Check that no row of ours is left. Our tables stay: the side table empty, the ledger, the switch's row, which nothing removes, and the thread head rows, which upstream never reads. So does the listing index opc_checkpoints_root_latest on upstream's checkpoints, which upstream's saver never uses but maintains on each root put until it is dropped by hand.

A dry run does none of that: it reports how many rows would be rewritten and how many bytes they take now and as plain rows, read from each zstd frame's header (a rewrite can need several times the disk the patches took). On the command line:

opc-rehydrate [--dry-run] [--batch-bytes N] [CONNINFO]
# or: python -m open_postgres_checkpointer.rehydrate [--dry-run] [--batch-bytes N] [CONNINFO]

The switch stays on afterwards: patches cannot be turned back on for a rehydrated database.

DEFAULT_BATCH_BYTES module-attribute

DEFAULT_BATCH_BYTES: Final = 64 * 1024 * 1024

Default bound on the bytes one batch holds decoded: the rewritten values and the bases their patches need.

RehydrateReport dataclass

RehydrateReport(patches: int = 0, full_copies: int = 0, writes: int = 0, stored_bytes: int = 0, rewritten_bytes: int = 0, batches: int = 0)

What one run of rehydrate found: the rows of ours, by kind, and their bytes.

A row is counted when the scan finds it. A row deleted before its batch is rewritten stays counted but is skipped. A dry run fills every field but batches.

batches class-attribute instance-attribute

batches: int = 0

Batches rewritten, one statement each; 0 for a dry run. A batch whose rows were all deleted meanwhile is counted too, though it sends no statement.

full_copies class-attribute instance-attribute

full_copies: int = 0

Full copies this saver compressed, found.

patches class-attribute instance-attribute

patches: int = 0

Patches found.

rewritten_bytes class-attribute instance-attribute

rewritten_bytes: int = 0

Bytes the same rows take as upstream's plain rows, from each zstd frame header: the figure to check against free disk.

stored_bytes class-attribute instance-attribute

stored_bytes: int = 0

Bytes those rows' stored values take as ours.

writes class-attribute instance-attribute

writes: int = 0

Pending writes this saver compressed, found.

rehydrate async

rehydrate(conn_string: str = '', *, batch_bytes: int = DEFAULT_BATCH_BYTES, dry_run: bool = False, conn_kwargs: Mapping[str, Any] | None = None) -> RehydrateReport

Rewrite every row of this saver's format on conn_string as plain langgraph-checkpoint-postgres rows (see module docstring for the four steps).

Resumable: safe to re-run after an interruption.

Parameters:

Name Type Description Default
conn_string str

libpq connection string or URI (default "", using PG* environment variables or .pgpass).

''
batch_bytes int

Maximum decoded bytes rewritten per batch (default 64 MiB).

DEFAULT_BATCH_BYTES
dry_run bool

When True, report rows and bytes to rewrite without modifying the database.

False
conn_kwargs Mapping[str, Any] | None

Extra keyword arguments passed to psycopg.AsyncConnection.connect (for example {"prepare_threshold": None} behind an older PgBouncer). autocommit=False is refused with PoolConfigError.

None

Returns:

Type Description
RehydrateReport
RehydrateReport

summarizing rows and bytes rewritten (or to be rewritten on a dry run).

Raises:

Type Description
ValueError

batch_bytes is less than 1.

PoolConfigError

conn_kwargs sets autocommit=False.

CheckpointerError

rows in this saver's format remain after all passes finish.

Source code in src/open_postgres_checkpointer/rehydrate.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
async def rehydrate(
    conn_string: str = "",
    *,
    batch_bytes: int = DEFAULT_BATCH_BYTES,
    dry_run: bool = False,
    conn_kwargs: Mapping[str, Any] | None = None,
) -> RehydrateReport:
    """Rewrite every row of this saver's format on `conn_string` as plain
    `langgraph-checkpoint-postgres` rows (see module docstring for the four steps).

    Resumable: safe to re-run after an interruption.

    Args:
        conn_string: libpq connection string or URI (default `""`, using `PG*`
            environment variables or `.pgpass`).
        batch_bytes: Maximum decoded bytes rewritten per batch (default 64 MiB).
        dry_run: When True, report rows and bytes to rewrite without modifying the database.
        conn_kwargs: Extra keyword arguments passed to `psycopg.AsyncConnection.connect`
            (for example `{"prepare_threshold": None}` behind an older PgBouncer).
            `autocommit=False` is refused with `PoolConfigError`.

    Returns:
        A [`RehydrateReport`][open_postgres_checkpointer.rehydrate.RehydrateReport]
        summarizing rows and bytes rewritten (or to be rewritten on a dry run).

    Raises:
        ValueError: `batch_bytes` is less than 1.
        PoolConfigError: `conn_kwargs` sets `autocommit=False`.
        CheckpointerError: rows in this saver's format remain after all passes finish.
    """
    if batch_bytes < 1:
        msg = f"batch_bytes must be at least 1; got {batch_bytes!r}"
        raise ValueError(msg)
    merged_conn_kwargs = _connection.merge_conn_kwargs(conn_string, conn_kwargs or {})
    report = RehydrateReport()
    async with await AsyncConnection.connect(conn_string, **merged_conn_kwargs) as conn:
        await check_head(conn)

        # 1. Turn patching off. 2. Wait out the transactions that started before.
        if not dry_run:
            await conn.execute(_sql.PATCHING_OFF_SQL)
            await _wait_for_older_transactions(conn)

        # 3. Rewrite patches, then full copies, then pending writes, a batch at a time.
        passes: tuple[_Pass, ...] = (
            _Pass(
                "patches",
                _sql.REHYDRATE_PATCHES_SQL,
                _sql.REHYDRATE_AFTER,
                _key,
                _rewrite,
            ),
            _Pass(
                "full_copies",
                _sql.REHYDRATE_FULL_COPIES_SQL,
                _sql.REHYDRATE_AFTER,
                _key,
                _rewrite,
            ),
            _Pass(
                "writes",
                _sql.REHYDRATE_WRITES_SQL,
                _sql.REHYDRATE_WRITES_AFTER,
                _write_key,
                _rewrite_writes,
            ),
        )
        for counter, query, after_sql, key, rewrite in passes:
            last_key: tuple[Any, ...] | None = None
            pending: list[DictRow] = []
            while True:
                if not pending:
                    pending = await _scan(conn, query, after_sql, last_key)
                    if not pending:
                        break
                if dry_run:
                    # a dry run decodes nothing, so it needs no bound on bytes held
                    batch = pending
                    pending = []
                    batch_rewritten = sum(_patch.frame_len(r["head"]) for r in batch)
                else:
                    batch, batch_rewritten = _batch(pending, batch_bytes)
                    del pending[: len(batch)]
                report.stored_bytes += sum(r["stored"] for r in batch)
                report.rewritten_bytes += batch_rewritten
                if counter == "patches":
                    report.patches += len(batch)
                elif counter == "full_copies":
                    report.full_copies += len(batch)
                else:
                    report.writes += len(batch)
                if not dry_run:
                    await rewrite(conn, batch)
                    report.batches += 1
                last_key = key(batch[-1])
        if dry_run:
            return report

        # 4. Check that no row of ours is left.
        cur = await conn.execute(_sql.REHYDRATE_LEFT_SQL)
        side_rows, ours_left = cast("tuple[int, int]", await cur.fetchone())
        if (side_rows, ours_left) != (0, 0):
            msg = (
                f"{side_rows} patch side rows and {ours_left} values or pending writes "
                "are still in this saver's format; re-run rehydrate to catch up with "
                "concurrent writers, and if counts do not fall inspect opc_blob_patch "
                "and checkpoint_blobs/checkpoint_writes for orphaned opc:% rows"
            )
            raise CheckpointerError(msg)
    return report