Skip to content

Patch write and read paths

Status: built 2026-11-12 (src/open_postgres_checkpointer/_patch.py, aio.py). The stored format is the one accepted in patch-placement.md; this note records how the saver writes and reads it, and the choices that are not in architecture.md. Labels follow Labels on numbers.

Stored values

Value checkpoint_blobs.type Side row
Below 256 serialized bytes, or not smaller once compressed the serde's own type —
Full copy opc:zstd:<serde type> —
Patch: the value compressed with its base's bytes as a zstd prefix opc:zstd-patch:<serde type> opc_blob_patch, naming the base version
  • A base is always a full copy (either of the first two rows), never a patch, so a read applies at most one patch per value, whatever the thread's length. There are no chains.
  • Every zstd frame carries its content checksum. A patch applied to any bytes other than its base's fails the checksum and raises PatchError; a test sabotages the base to show it (tests/test_patch.py::test_a_patch_applied_to_other_bytes_fails_its_checksum, measured).
  • A patch is kept only when it is at most a quarter of its base's stored size (write path step 2); otherwise the value is written as a full copy and becomes the new base.
  • opc_blob_patch and our ledger opc_migrations were added in stage 3 (later stages added opc_patching_off, opc_thread_head, opc_head_seq and opc_checkpoints_root_latest; see Adopting the saver). A database upstream set up therefore needs one setup() call before this saver uses it; that call adds only our own objects (tests/integration/test_setup_and_pool.py, measured). Upstream's ledger is untouched.

Write path

  1. Serialize each changed value with the saver's serde.
  2. Find each value's base, for values of at least 1,024 bytes (MIN_PATCH_BYTES; inferred from _patch.py):
  3. the base the saver holds in memory for (thread_id, checkpoint_ns, channel);
  4. otherwise the full copy the parent checkpoint's value rests on: that value itself, or its base if it is a patch. One extra statement (write rule 1). A channel the parent holds no stored value for (the run's input __start__) gets no base, so it is never patched; its fetch returns no row (known limit 1). The fetch leaves out a base the put could not use: one larger than the base cache holds, one that with the value exceeds the patch's 256 MiB window, or one more than four times the value's size. A base's stored size never exceeds its serde size, so the statement drops most of these by stored size without sending them, and the saver drops the rest by the frame's recorded content size before decompressing.
  5. Encode: a patch when the base is not the value's own version, the base is at most four times the value's size, and the patch is small enough; else a full copy. A value far smaller than its base (a summary, a trimmed window) would otherwise patch to almost nothing while every read of it decoded the whole base and kept it stored.
  6. One statement writes the blob rows, the checkpoint row, and a side row for each patch row that statement inserted (the blob insert's RETURNING), so a retried put whose rows already exist writes nothing new.
  7. If the deferred foreign key refuses a patch at commit (SQLSTATE 23503: another process deleted the base), nothing was written. The saver forgets those bases and writes the put once more with full copies only.
  8. Only after the commit do newly inserted full copies become the saver's bases, and only for channels this put had a base for. A base the database never stored would make every later patch against it fail; a channel nothing provided a base for (the run's input) would otherwise be patched by the same saver's next run. A new thread's second put therefore fetches its base from the parent once.

A run's opening aget_tuple primes the writer (write path step 1): each value's full copy, or a patch's base, becomes the base for that channel, from the bytes the read already decoded. alist and delta history do not prime. A test pins that a warm saver never patches the run's input (test_the_run_input_is_never_patched_even_by_a_warm_saver, measured; it fails when every new full copy becomes a base).

Note (2026-11-30): the write path changed in a5fa49c (inferred from aio.py).

  • Step 6 is superseded. After the commit, every new full copy of a channel that _is_cacheable_channel accepts becomes a base, a thread's first put included. __start__ and __pregel_tasks never do.
  • An aput that holds no base for a channel fetches it, then decodes the base and encodes the value in one codec-thread hop (_fetch_and_encode_missing).
  • _patch.Base holds a raw-prefix ZstdDict, not the base's bytes.
  • Under § Read path: an alist with no checkpoint_ns first reads the matching keys (_sql.list_keys_sql), so it sends two statements, not one.

Read path

Each read stays one statement, as in stage 2:

  • aget_tuple and alist: the page's distinct stored values, each patch's side row, and each base the page does not already hold, fetched once.
  • Delta history: each seed row joins its side row and its base. The walk reaches only ancestors no newer than the target, as upstream's paged walk does, and ends where a parent chain loops back (only reused checkpoint ids make one). Upstream's walk never returns on such a loop; stage 2's walk did not return either, which the stage 3 differential found (test_delta_history_stops_at_an_ancestor_newer_than_the_target_like_upstream, measured).

Each base is decompressed once per read and held as one zstd dictionary that every patch on it reads through. A value that several checkpoints of a page name is decompressed once and kept decoded for the page, which holds one loaded object per name anyway. Other values are not kept decoded, so a page of large values that each appear once holds only their stored bytes.

zstd parameters for a patch

The value is compressed at level 3 with the dfast strategy, a window that holds the base and the value (ceil(log2(base + value)), at least 2^10), long-distance matching on, both match tables fixed at 2^17 slots, the content checksum on, and the frame's content size recorded. The base's bytes go in as a zstd prefix, not a dictionary. A read decodes a patch with the base's bytes as a prefix too, which reads a prefix-made patch and a raw-content-dictionary-made one alike. The binding is the standard library's compression.zstd on Python 3.14+ and backports.zstd before it.

Why a prefix: zstd cuts a dictionary at 16.78 MB

At the fast and dfast strategies, zstd 1.5.7 loads only the last 2^24 - 2 bytes (about 16.78 MB) of a dictionary it digests (inferred from zstd's zstd_compress.c, where the cut applies to tagged dictionary indices). The first binding, python-zstandard, always digested the base as a dictionary, so the head of a base above that size was out of reach: the patch of an append had to carry the head again, failed the quarter test, and the value was written as a full copy. Benchmark 1 stopped patching after about 20 MB for this reason (claimed by the investigation that found the cut; its probe logs are not in this repository).

A prefix is not digested that way: it is the window's start, and long-distance matching finds any part of it. Small fixed tables then suffice, because the long-distance matcher, not the tables, reaches the far base.

A 1 MB append of the tests' text (_text in tests/test_patch.py) against bases of each size, the old parameters (dictionary, both tables at ceil(log2(base)) - 2) and the new ones, run once (inferred: one run, script not kept; the 24 MB row is pinned by tests/test_patch.py::test_a_base_above_zstds_dictionary_cut_still_patches_an_append_small, measured, which fails on the old parameters):

Base Patch, old Patch, new Time, old Time, new
0.25 MB 395 KB 390 KB 0.01 s 0.01 s
1.3 MB 391 KB 394 KB 0.02 s 0.02 s
10 MB 376 KB 399 KB 0.17 s 0.03 s
24 MB 3,017 KB: over a quarter of the base's 9.4 MB stored size 402 KB 0.57 s 0.06 s
100 MB 30,760 KB 413 KB 3.90 s 0.20 s

The 1 MB append alone compresses to about 389 KB, so every new patch is the append and little else. A 9-byte append on a 10 MB base patches to 973 B old and 1,098 B new (inferred, the same run).

The investigation reports, for the new parameters (claimed, not reproduced here): a 1 MB append on a 210 MB base patches to 0.351 MB in 0.34 s, with 36 MiB of extra resident memory against 512 MiB for the old parameters; a 100 MB base with 2,000 scattered edits and a 1 MB append patches to 0.475 MB; bases of 0.25–10 MB patch within 0.0002 MB of the old size with less memory; and a flipped bit in the base fails the checksum. The decode of patches written by python-zstandard is pinned by tests/test_patch.py::test_a_patch_and_a_full_copy_written_by_python_zstandard_still_decode (measured), against fixtures that binding wrote.

The window limit is 2^28 (256 MiB) for base plus value (inferred from _WINDOW_LOG in _patch.py); the decoder is told to accept it. Patches written under the earlier 2^27 limit have smaller windows and still decode.

Memory

  • The base cache holds base bytes only, never compressors (write rule 2), keyed by (thread_id, checkpoint_ns, channel) and bounded by bytes, least recently used out first. A base larger than the bound is not held. Default bound: 64 MiB per saver (base_cache_bytes; inferred from DEFAULT_BASE_CACHE_BYTES in aio.py).
  • Serialized bytes are not kept after a put returns, except as a base inside the bound. (The prototype kept every put's serialized values, which held most of its resident growth.)
  • Serializing, compressing, patching and decoding run on one thread per saver, never on the event loop and never across a pool of threads. With glibc, each thread that allocates gets its own arena; zstd's short-lived buffers spread over many arenas are what the process keeps.
  • The saver never changes allocator settings (ADR-0011). An operator who needs the resident size close to the cache bound can start the process with MALLOC_MMAP_THRESHOLD_=131072, which makes glibc return large buffers to the system when they are freed. The memory bar is judged without it.

Whether this meets the memory bar is measured in stage 3's benchmark, not here.

Full-copies mode

AsyncOpenPostgresCheckpointer(pool, full_copies_only=True) writes exactly stage 2's rows, which upstream's saver reads, holds no bases and fetches none, and still reads patches. A fleet deploys with it everywhere, then turns patches on (ADR-0009). Patches are on by default (ADR-0037).

Tests

tests/integration/test_patch_storage.py, test_differential.py and test_conformance.py (all measured by those tests; each guard was shown to fail when the behaviour it guards was sabotaged, before public release):

  • The prototype's failing cells: C0 (upstream's keep_latest that would drop a kept patch's base fails whole and changes nothing), C1 (a writer whose base another process pruned writes a full copy that every reader reads), C2 (threads whose version strings coincide), C3 (a saver without the bases reads every checkpoint).
  • A failure before or after each of a run's five statements, recovered by a retry on the same saver or by a restarted saver; a put cancelled between serializing and executing; two concurrent runs on one thread through one saver and through two; three savers reading one base's patches while a run writes them.
  • Upstream reads every checkpoint and state a full-copies saver wrote for plain and DeltaChannel graphs. Conformance passes in both modes.
  • The differential: rows identical to upstream's in full-copies mode (200 sequences); with patches on, every checkpoint and its delta history read back as upstream's (200 sequences on one thread, 145 patch rows at the end of the run).

C2 is guarded twice: the cache is keyed by thread and namespace, and a base remembered under the wrong thread would name a row the foreign key does not find in this thread, so the write would fall back to a full copy (inferred from the keys; no sabotage run separates the two guards).

Rollback: rehydrate

python -m open_postgres_checkpointer.rehydrate CONNINFO [--dry-run] [--batch-bytes N] (src/open_postgres_checkpointer/rehydrate.py) rewrites every patch, every compressed full copy and every compressed pending write (ADR-0036) as the serde's own bytes under the serde's own type, the row upstream would have written, and deletes each patch's side row in the same statement (compatibility.md):

  1. It turns patching off: one row in opc_patching_off, a table our ledger's migration 3 creates. Every put that would write a row of ours checks the switch in its own statement's snapshot; a saver that finds it writes that put, and every later one, as in full-copies mode. The switch is never turned back on.
  2. It waits until every client transaction in this database that began before the switch has ended: only those can still write a row of ours. A session left idle in a transaction holds it there until that transaction ends; every _WARN_EVERY_S (10 s) of waiting it logs a warning naming each such session's pid and application_name.
  3. It rewrites patches first, then full copies, then compressed pending writes, so a base is rewritten only after every patch on it. Each batch is one statement and holds at most --batch-bytes decoded (default 64 MiB; a single larger value goes alone); a base its patches share is fetched once. Peak memory is about 3× that, from the decoded values, psycopg's joined array parameter and libpq's send buffer (inferred from the code, not measured). A row a put or delete changed since the scan is left for the next run. An interrupted run leaves every value readable; a rerun continues.
  4. It checks that no side row and no tagged value or pending write is left. Our tables (opc_*), sequence (opc_head_seq) and listing index (opc_checkpoints_root_latest) stay until dropped by hand (Rolling back). Nothing turns the switch off; a database rehydrated and then meant to store patches again needs that row deleted by hand.

A dry run changes nothing and reports the rows and their bytes now and as plain rows, read from each zstd frame's header (ADR-0010: a rewrite may need about 7× the disk, measured on the 400-step graph before public release). The test checks the reported plain bytes against the rewrite's (measured).

The CI rehearsal (tests/integration/test_rehydrate.py, measured): plain, DeltaChannel and subgraph threads written by real graphs plus a patched thread are rehydrated in 16 KiB batches, then upstream's saver lists every checkpoint, rebuilds each graph's state history and every delta history as ours read them before, and prunes and deletes. Each step's guard failed under sabotage (switch ignored, no wait, no byte bound, side rows kept, patches copied undecoded, dry run counting stored bytes).

Not done here

  • A digest of the base in the side row, verified on read: the frame checksum already refuses a wrong base, and a new column would change the DDL accepted in patch-placement.md. Left open.