Optimization backlog
Performance and allocation candidates identified during a full-package scrutiny of src/open_postgres_checkpointer/, with measured outcomes for every item.
Every number is tagged using the design-notes label convention (measured vs. inferred). Any latency or disk claim intended for release docs still requires a full four-arm run under the benchmark rule in benchmarks/README.md.
1. Implemented and measured
Wave 1 — Warm BaseCache ZstdDict reuse & hot-path allocations
| # | Optimization | Where | Measured before → after | Delta |
|---|---|---|---|---|
| 1.1 | Reuse BaseCache's ZstdDict on warm patched aget_tuple reads (with Rule 1 zstd-checksum fallback to DB base) |
aio.py, _patch.py |
measured (1 MiB base, ×50): 4.704 ms (4.23 MiB peak) → 1.032 ms (3.30 MiB peak) |
−78.1% (4.6× faster), −22% peak RAM |
| 1.2 | _load_page single-pass partition, lazy parent_config, in-place channel_values merge |
aio.py |
measured (1-row, 10 inline + 2 blobs, ×5k): 28.99 µs → 19.09 µs |
−34.1% |
| 1.3 | aput single-pass channel split (no .copy()/.pop() or unchanged blob_values) |
aio.py |
measured (10 inline + 20 unchanged + 1 changed, ×1k): 316.29 µs → 162.68 µs |
−48.6% |
| 1.4 | Precomputed _PATCH_OPTIONS / _DECODE_PATCH_OPTIONS & direct base keys in Stored |
_patch.py |
measured (3.7 KiB, ×3k): make_patch 25.62 µs → 17.44 µs; decode 4.75 µs → 4.03 µs |
−31.9% / −15.2% |
| 1.5 | _load_delta_history single-pass partition & conditional sort |
aio.py |
measured (1 write + 1 seed, ×5k): 2.34 µs → 1.36 µs |
−41.9% |
| 1.6 | slots=True on ThreadInfo, SweepReport, RehydrateReport |
listing.py, aio.py, rehydrate.py |
measured: 344 B each → 56 B / 64 B / 80 B |
−83.7% / −81.4% / −76.7% |
Wave 2 — Wire-skip cached base blobs, direct BASES_SQL, and tuple_row reads
| # | Optimization | Where | Measured before → after (Postgres 16, force_generic_plan) |
Delta |
|---|---|---|---|---|
| 2.1 | Wire-skip cached base blobs on warm aget_tuple (GET_LATEST_SKIP_SQL / GET_BY_ID_SKIP_SQL when BaseCache.scope_bases is non-empty, with StaleCachedBaseError re-fetch fallback) |
_patch.py, _sql.py, aio.py |
measured (485 KiB compressed / 1.1 MiB raw base): 2.784 ms → 0.916 ms (bad_seq=False); cold/small reads stay on plain GET_LATEST_SQL (0.666 ms, zero regression) |
−67.1% (3.04× faster) |
| 2.2 | BASES_SQL direct JSONB key extraction (->> w.channel) instead of jsonb_each_text + join |
_sql.py |
measured: narrow 5ch 0.829 ms → 0.600 ms; wide 50ch 0.723 ms → 0.637 ms |
−27.7% / −11.9% |
| 2.3 | Positional tuple_row (_fetch_tuples) for _read_sql in aget_tuple and alist |
aio.py, listing.py, benchmarks/_greenfield.py |
measured: aget_tuple(1, 20ch) 1.836 ms → 1.386 ms; alist(100, 2,100 rows) 54.992 ms → 43.288 ms |
−24.5% / −21.3% |
Earlier pass (commit fbda731)
- Eliminated duplicate multi-MB
ZstdDict.dict_contentcopy on first decode of an unkept base inStored.raw()(measured: −68.8% on 4 MiB base). - Drained
_scan()'s 500-row buffer acrossrehydratebatches and removed doubleframe_len()calls (measured: −92.5% DB scans, −40.2%frame_lencalls at 2 rows/batch). - Skipped
Counteron 1-row_load_page(aget_tuple), guardedwrites.sort()forlen <= 1, and decodedtask_idonce per pending write (measured: −26.3% on 0-write 1-row_load_page, −16.6% on 10-write_load_page). - Built
aput_writesplainfallback lazily, markedRETAIN_DELETE_SQL'skeptCTEMATERIALIZED, and deduplicatedsync.py's_run_on().
2. Measured and ruled out (keep as-is)
Recorded here so these are not re-proposed without new evidence:
| Candidate | Where | Measured result / constraint | Verdict |
|---|---|---|---|
Guard PUT_SQL parent CTE with token_seq IS NOT NULL AND checkpoint_ns = '' |
_sql.py (PUT_SQL) |
measured (Postgres 16 EXPLAIN (ANALYZE, BUFFERS), force_generic_plan): checkpoints_idx_loops=0 already on tokenless root puts and subgraph puts; 1 only on fenced puts |
Drop — Postgres already short-circuits via InitPlan |
Materialize jsonb_each_text once in _read_sql (page_versions + HashAggregate + LEFT JOIN) |
_sql.py (_read_sql) |
measured (Postgres 16, force_generic_plan, 20 ch/cp): aget_tuple(1) 0.870 ms → 1.383 ms (+59% slower); alist(100) 30.70 ms → 39.51 ms (+29% slower) |
Drop — CTE materialization + join costs far more than running jsonb_each_text twice |
Reuse ZstdCompressor (set_pledged_input_size + FLUSH_FRAME) in _patch.compress() |
_patch.py (compress) |
measured (2 KiB – 1 MiB high-entropy payloads): −2.2% to +1.0% (noise; streaming output resizing loses one-shot ZSTD_compressBound buffer) |
Drop — one-shot zstd.compress() earns its place |
Reuse ZstdDecompressor across frames in _patch.decode() |
_patch.py (decode) |
measured (backports.zstd / PEP 784): raises EOFError: Already at the end of a Zstandard frame. |
Not supported by PEP 784 API |
Single-pass loop in aio.py _store() instead of list comprehensions |
aio.py (_store) |
measured: at n=50, single-pass Python loop is 24.17 µs vs. 12.17 µs (+98.5% slower); at n=5, 2.15 µs vs. 2.43 µs (noise) |
Drop — C-speed list comprehensions are faster and clearer |
Optimize COPY_TARGET_ROWS_SQL row-count verification in acopy_thread |
_sql.py (COPY_TARGET_ROWS_SQL) |
measured (2,100-row thread): 2.36 ms out of 28.79 ms total (8.2%) |
Keep as-is — small fraction of a rare operation |
Hold raw base bytes in Stored._decoded on alist to avoid dict_content copy |
_patch.py (Stored) |
measured: dict_content on 1 MiB takes 39.3 µs; holding raw alongside ZstdDict doubles live base RAM for the entire page |
Drop — bad RAM-for-microseconds trade |
3. Deferred / architectural trade-offs (revisit only if profiling flags them)
- Bypassing
_on_codec_threadfor tiny payloads (aio.py): Explicitly ruled out byaio.pyRule 5 (all serde and zstd stay off the event loop and in one allocator arena). Revisit only if high-concurrency profiling (see Concurrentputprofile) shows codec-thread queueing on small-state graphs. asweep_expiredper-thread transaction loop (aio.py,_sql.py):SWEEP_DELETE_SQLmust run in a newer READ COMMITTED snapshot afterSWEEP_LOCK_SQLacquiresFOR UPDATE SKIP LOCKED, so they cannot be merged into one statement. Batching multiple threads into one transaction widens lock hold time andForeignKeyViolationrollback blast radius; bounded concurrency or pipelining is only worth adding if expiry backlog throughput becomes a real bottleneck.- Bounded concurrency for
aprune/adelete_for_runs(aio.py): Per-thread sequential execution avoids starving live graph traffic on a shared pool; only revisit if bulk pruning latency matters. rehydratetrailing empty scan & I/O–CPU overlap (rehydrate.py): One-shot rollback tool; skipping the trailing empty scan saves at most 3 queries total, and prefetching would double live decoded memory againstbatch_bytes.
4. Proposed, not yet measured (package review, 2026-12-05)
Candidates from a read-only efficiency review of src/open_postgres_checkpointer/. Nothing here was
measured and nothing was changed: every saving is inferred. Each row names the benchmark case
(just bench-case <case>) and the figure that would move it to section 1 or section 2.
| # | Candidate | Where | Expected effect (inferred) |
Measure with | Open question |
|---|---|---|---|---|---|
| 4.1 | Memoize the loaded object per (thread, ns, channel, version) on a page, so a value several checkpoints name is deserialized once, not once per checkpoint |
aio.py (_load_page, step 1: serde.loads_typed(stored.raw(key))) |
Less client CPU on whole-history alist when a large channel is unchanged across N checkpoints (N loads_typed calls → 1) |
history: alist p50 and client CPU |
The tuples of a page would share one mutable object where today, as with upstream, each has its own: a behaviour change to decide before measuring |
| 4.2 | Do not keep a base's raw bytes in Stored._decoded when its ZstdDict is already in Stored._dicts |
_patch.py (Stored.raw, Stored._dict: the if key in self._keep store) |
Lower peak RSS on alist pages where a kept value is also a patch's base; costs one dict_content copy per later read (39.3 µs per MiB, section 2) |
history: peak RSS, alist p50 |
Section 2 already ruled out holding raw bytes beside the dictionary; this path still does for keys in both keep and _dicts |
| 4.3 | Run the skip read for every aget_tuple, with empty skip_channels/skip_versions when no base is held, and drop GET_LATEST_SQL/GET_BY_ID_SQL and the if cached_bases branch |
_sql.py (_read_sql(skip=True)), aio.py (aget_tuple) |
Two prepared read statements instead of four; item 2.1 measured only plain against skip-with-hits, never skip with nothing to skip | quick and large (large_threads.py --warm beside the default): get_tuple p50 and p95 on cold reads; test_read_plans.py for the plan |
The skip variant's UNION ALL holds only for a one-checkpoint page, so alist keeps the plain statement either way |
| 4.4 | On the ForeignKeyViolation retry in aput, re-encode only the values that were patches and reuse the full copies already encoded |
aio.py (aput: _encode_values(values, {}, retry_bound)) |
Less codec-thread work on a rare path (a prune racing a writer) | retention: put p95 under the racing prune loop |
Rare enough that the result may be noise |
| 4.5 | In rehydrate's patches pass, also write back each compressed base it fetched and decoded, so the full-copies pass does not fetch and decompress it again |
rehydrate.py (_rewrite and the pass table) |
One fetch and one zstd decompression fewer per compressed base, on a one-shot command | No case covers rehydrate: time rehydrate() on a database a core run left |
Shifts RehydrateReport's per-pass counts; reviewer's reading of _rewrite, not re-checked |
| 4.6 | Read delta history as positional tuples, as item 2.3 did for the main reads | aio.py (aget_delta_channel_history → _load_delta_history) |
Item 2.3 measured −21% to −25% for _read_sql reads; this result has one row per pending write along the walk |
history: delta-history read p50 |
Positional indexes cost readability in _load_delta_history |