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]]
|
|
required |
serde
|
SerializerProtocol | None
|
Optional checkpoint serializer (defaults to LangGraph's |
None
|
full_copies_only
|
bool
|
When True, write only plain |
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 | |
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 | |
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
|
|
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 | |
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
DeltaChannelthread 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, andacopy_threadrefuses 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
|
|
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 | |
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 | |
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 | |
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 | |
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 | |
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, asadelete_threaddoes. The other strategies never touch a thread's head row."keep_latest"keeps, per namespace, the latest checkpoint, as upstream'sprunedoes."keep_latest"withkeep_last=Nthins instead: per namespace, the latestNplus the latest checkpoint of each run, by therun_idin checkpoint metadata (it is there only when the caller passed it in configmetadataorconfigurable).
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
DeltaChannelthread, the ancestors its history walks back to each channel's snapshot, with their writes, so aDeltaChannelthread is pruned, not refused. A checkpoint kept only as such an ancestor reads back its own stored values, but not necessarily its ownDeltaChannelhistory. - 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.SerializationFailurewhen the transaction changed a row this one changes (a second prune, say). - It fails with
psycopg.errors.ForeignKeyViolationwhen 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
|
|
ValueError
|
an unknown |
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 | |
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 | |
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 | |
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-postgreswrote 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
|
|
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
delete_thread
delete_thread(thread_id: str) -> None
AsyncOpenPostgresCheckpointer.adelete_thread.
Source code in src/open_postgres_checkpointer/sync.py
247 248 249 | |
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 | |
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 | |
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 | |
get_tuple
get_tuple(config: RunnableConfig) -> CheckpointTuple | None
AsyncOpenPostgresCheckpointer.aget_tuple.
Source code in src/open_postgres_checkpointer/sync.py
210 211 212 | |
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 | |
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 | |
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 | |
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 | |
setup
setup() -> None
AsyncOpenPostgresCheckpointer.setup.
Source code in src/open_postgres_checkpointer/sync.py
206 207 208 | |
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 | |
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 | |
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()runsCREATE INDEX CONCURRENTLY(bothlanggraph-checkpoint-postgresmigrations 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 ( |
None
|
before
|
RunnableConfig | None
|
A |
None
|
limit
|
int | None
|
Maximum number of threads to yield. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
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 | |
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 | |
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 | |
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:
- 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. - 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.
- 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.
- 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_lateston upstream'scheckpoints, 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 |
''
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
RehydrateReport
|
|
RehydrateReport
|
summarizing rows and bytes rewritten (or to be rewritten on a dry run). |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
PoolConfigError
|
|
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 | |