Skip to content

2.0 PostgreSQL storage: ancestor-location lists and group-ranged reads #758

Done

Description

@yifanxuaaa

Goal

Make PostgreSQL Store reads and Saves stop paying one serial round-trip pair per delta-chain level, without changing SQLite. In 2.0, a cold read costs at most 3 round trips per locate wave with chains (2 without) plus 1 per 2 MiB returned, whatever the chain depth. The design must extend unchanged to the 3.0 storage split (#759).

Why

stored_base (core/crates/layerfs-storage/src/encoding/delta/read.rs) is the only reader of a delta edge. Reconstructing a delta of depth d therefore runs this loop until it reaches a FULL record:

  1. locate the record;
  2. fetch its pack;
  3. decode the base id;
  4. locate the base, and repeat.

On SQLite each level costs microseconds. On PostgreSQL each level costs 2 round trips.

Evidence from the real quarry-v2 Store (1,693,320 objects, 38,680 packs, 4,514 Commits):

  • Delta share and chain depth (p50 / p90 / max):

    Class Stored as delta p50 p90 max
    WholeFile 72 % 5 14 16
    Chunk 68 % 2 7 8
    Metadata 53 % 1 6 8
  • No chain reuses a pack: each level is a different pack.

  • Today a small-file read takes 11.4 round trips and a chunked-file read 21.8 (mean).

  • In the 24-version bench, a PostgreSQL cold read is 12.7× slower than SQLite.

  • 79 % of a Save's round trips are single-pack reads of delta bases through the same fetch path (pg_stat_statements attribution).

Owner decisions

  • SQLite: no schema or behaviour change in 2.0. SQLite + bucket becomes an independent 3.0 backend (3.0 storage: new SQLite + bucket and PostgreSQL + S3 Store kinds, with a machine-wide NVMe cache #759).
  • Core: a small, backend-neutral core change (option A), not a hidden PostgreSQL-only cache.
  • PostgreSQL: speed first; a larger catalog is accepted, and storage savings are still shown.
  • No flattering: no limit on project size, file count, file size, change size, history length or concurrency may be chosen to improve results. Benches use shipped defaults (synchronous_commit = local).
  • D1–D6: taken as recommended; see the table below.

2.0 scope

Item What Risk
Core Save passes each record's logical base. The port gains locate_chains(roots) and read_groups(reads), both defaulting to today's behaviour, so SQLite is unchanged. A stale hint falls back to the level-by-level read and is counted; tests and benches run strict (chain_hint_stale == 0). The cache unit becomes (pack, group range). Counters are added. About 100–135 lines. low
Ancestor lists object_location.ancestors bytea: each delta row's chain as physical locators, nearest base first, in chained zigzag varints. Filled inside the publish statement from the catalog's winning rows (publications serialise on store_lane). locate_chains makes two statements per locate wave (design B, provider-only): roots, raw lists and root packs; then member packs by primary key after the lists are decoded in Rust. medium
Group directory pack.directory bytea: a copy of the pack header and group directory, 2.8 MB at quarry. Reads fetch only the needed groups of many packs in one statement. medium
Freeze settings Early-freeze reloptions on pack and object_location. low
Schema Version bump; pre-2.0 PostgreSQL dev Stores refused at open. low
Prototype cleanup Remove the prototype's SQLite base column, migration and fill. low
Verification Bench modes for a large file, a large commit and history and catalog scaling; client per-byte profile; release-gate run (below, about 1–1.5 h of machine time). –

Order: cleanup and core first; then both columns in one schema change; then freeze settings, schema bump, verification.

Minimum cut: both columns plus core plus ancestor lists. Ranged reads can then land in 2.0.x without a migration.

Invariant: PostgreSQL 2.0 never moves a record inside a retained pack and keeps every ancestor of a retained row. This holds today, because compaction copies retained packs and rows unchanged. It is guarded by:

  • the immutable-pack trigger;
  • a compaction verification scan;
  • strict compaction tests.

Not in 2.0:

Item Why
Narrowed locator row With bigint pack ids it saves nothing; integer would cap a Store at about 4.4 M packs.
Server-side GC mark from the lists Deferred (D2).
4-round-trip and pipelined publication Deferred (D4).
Partitioned pack with generational compaction After 2.0.
Locator blocks After 2.0.
Record-exact ranges After 2.0.

Expected results

All are estimates from the real quarry edges and group extents unless marked measured. The release gate replaces them with measurements.

Storage, all 1.69 M quarry locators loaded in PostgreSQL (measured):

B/locator Quarry At 10×
today 113.4 192 MB 1.92 GB
2.0, varint lists 136.4 (+20 %) 231 MB 2.31 GB
fixed 14-byte entries (rejected) 155.0 (+37 %) 262 MB 2.62 GB

pack.directory adds 2.8 MB at quarry. Pack bodies are unchanged. SQLite is 55.7 B/locator.

Reads (PostgreSQL):

Read Round trips Bytes Wall at 0.375 ms RTT Wall at 1 ms RTT
small file 11.4 → 3 206 → 117 KB 5.15 → ~1.4 ms 12.3 → ~3.3 ms
chunked file 21.8 → ~9.9 5.70 → 2.50 MB 14.9 → ~6.2 ms 28.5 → ~12.4 ms
head mount (249 k objects) 1,720 → ~1,360 3.15 → 2.55 GB 4.88 → ~2.84 s 5.95 → ~3.69 s
1 GiB file ~1,225 → ~567 1.83 → 0.78 GB 2.25 → ~0.86 s 3.02 → ~1.22 s
bench cold read (72 files) 1,247 → ~300 40.8 → 18–33 MB 661 → ~260–315 ms 3,784 → ~1,020–1,060 ms (netem arm)

The SQLite bench cold read is 52 ms. Needed-group reads save 1.24–2.28× in bytes against whole packs.

Saves:

Today 2.0
Round trips per bench Save ~53 ~14
Save at 0.036 / 0.375 / 1 ms RTT 50 / 68 / 101 ms 48 / 53 / 60 ms
Base-fetch round trips in a commit of ≥ 578 packs ≥ 578 ~20–30

SQLite: 24.3 ms per bench Save.

Unchanged: SQLite statements and schema; the GC mark; compaction; the Commit history half.

Release gate before merging into layerfs_v2_0_0

Owner direction: the final tests take about 25 minutes, the benchmarks about 40, and most of layerfs-benchmark is not needed.

  • Baselines are reused, not re-measured. They were taken on the same machine with the same harness, workload and settings:
    • the storage bench at 343c59b2ca;
    • the real quarry locator loads;
    • the pgr2-final end-to-end report (that row runs with synchronous_commit = off, as that report did).
  • Thresholds are frozen before the first sample. Each row is measured once.

Tests: one final run, about 26 minutes including the warm build

One --no-run build, then four commands.

  • Core layerfs-storage:
    • new: chain_hints, group_reads;
    • existing: selected_group_reads, pack_range_contract, read_pack_locality, verified_pack_read, pack_cache_contract, read_demand_custody, wave_reference_locates, chain_memo_reads, save_resolved_reads, concurrent_winner_chain.
  • layerfs-persistence, PostgreSQL:
    • new: postgresql_ancestor_lists, postgresql_group_directory, postgresql_chain_property (seed count fixed to fit 100 s), postgresql_history_scaling;
    • existing: postgresql_narrow_locations, postgresql_identical_ids, postgresql_commit_round_trips, concurrent_pooled_saves, postgresql_compact, postgresql_compact_fixtures, postgresql_gc_mark, postgresql_open_check, postgresql_doctor_physical, postgresql_statement_schema, heads.
  • SQLite smoke: sqlite_publication, sqlite_compact_repack, old_format_open.
  • Lint: Clippy and fmt on both packages.

These checks are counter assertions inside tests, not benchmark rows:

  • full rewrites (no chains) cost nothing extra;
  • 8 concurrent writers leave no delta row without a list, with chain_hint_stale == 0;
  • per-read round trips stay flat on long histories.

Benchmarks: about 40 minutes, run once

# Row Compared with Time
B1 Storage bench (72 files, 24 versions), published port today's run of the same bench ~3 min
B2 Same, +1 ms netem today's run ~5 min
B3 One 256 MiB file, 10 versions, Saves and a cold read round trips ≤ 3 per wave with chains (2 without) + 1 per 2 MiB; bytes ≤ 1.1× model ~6 min
B4 One Save adding ≥ 578 packs base-fetch round trips ≤ 40 ~4 min
B5 Product chain statements and row on the 1.69 M real quarry locators ≤ 141.8 B/locator; statement 1 ≤ 1.25× and statement 2 ≤ 0.5× today's locate on the same roots in the same run, random and depth ≥ 14 ~3 min
B6 One fs-bench-quick case (Commit and a cold 64 MiB cat), Docker, PostgreSQL published port pgr2-final rows for that case ~8 min
B7 History scaling: one growing history to 1,600 versions, probed at 100, 400 and 1,600 section below ~5 min
B8 Catalog scaling: the real 1.69 M locators vs a 10× synthetic copy with the same distribution section below ~6–8 min

Not run:

  • the quarry-to-PostgreSQL converter;
  • the 18 × 3 end-to-end matrix;
  • the long-history end-to-end case;
  • latency arms beyond 1 ms;
  • 1 GiB files;
  • the wide-tree shape.

Scaling: what must not grow with history

Each operation is judged with its own input fixed: file size, Commit size and head tree size. Delta chains are capped (16 / 8 / 8), so nothing on a read or Save path may grow with history length, and nothing may grow quadratically.

Class Metrics Bound
Constant cold read of one file (round trips, statements, bytes, wall); head mount of a fixed tree; Save / Commit of a fixed change (round trips, statements, bytes written, WAL, lane hold); catalog bytes added per Commit; ancestor-list bytes per delta row; bytes per locator; directory bytes per pack; client memory; chain_hint_stale = 0 counters equal; wall within +25 % or +5 ms
Logarithmic server time per located id and per chain root (B-tree depth) ≤ 1.5× for 10–16× more rows
Linear in its own input only total catalog and pack bytes (in stored objects, with flat bytes per locator); reads, Saves and mounts of larger inputs; doctor full never in history length

How these are checked:

  • postgresql_history_scaling (test): probes at 50, 200 and 800 versions. Counters must be equal at every checkpoint. No existing row may be updated during Saves (n_tup_upd = 0 on object_location and pack). The locate, chain and publish statements must use the indexes, with no sequential scan.
  • B7 (timing): constant rows ≤ 1.25× from 100 to 1,600 versions; logarithmic rows ≤ 1.5×; totals about 16× with flat per-unit bytes.
  • B8: at 10×, time per call ≤ 1.5× and buffers per call ≤ 2×; identical plans; bytes per locator within 5 %.
  • Real history (B5 data): roots from the first and the last 10 % of quarry's Commits have the same chain-statement time.
  • Quadratic check: any log-log slope ≥ 1.5 between the last two checkpoints fails.

GC mark and compaction do not change in 2.0, so they are outside this gate.

Acceptance

Criterion Threshold
Tests all pass
Cold read, published port (B1) ≤ 0.45× today: ≤ 300 ms against 661 ms. The SQLite ratio is reported, not gated, until the Rust client's per-byte cost is fixed
Cold read, +1 ms (B2) ≤ 0.30× today: ≤ 1,135 ms against 3,784 ms
Round trips (B1–B3) ≤ 3 per locate wave with chains, ≤ 2 without, + 1 per 2 MiB
Statements per cold read (B1) ≤ 0.30× today
Bytes (B1, B3) ≤ 1.1× the needed-groups model
Real catalog (B5) ≤ 141.8 B/locator; statement 1 ≤ 1.25× and statement 2 ≤ 0.5× today's locate, same run
Saves (B1, B2, B4) round trips ≤ 0.5× today; total Save wall ≤ today
End to end (B6) Commit and Exec ≤ pgr2-final + 5 % or + 5 ms
Scaling (test, B7, B8) as above
SQLite unchanged identical statement counts; not re-benchmarked

Run rules

  • While fixing: run only the tests the change reaches; the full covering run happens once, at the frozen change set.

  • No timed benchmarks per phase: development asserts counters (round trips, statements, bytes) in tests instead.

  • After a failure:

    • tests: rerun the failed tests and the targets the fix reaches;
    • benchmarks: rerun the failed row and the rows on the code the fix touches.

    Everything else keeps its result. Nothing is rerun to get a better number, and baselines are never rerun.

Chain lookup design (owner decision during Phase 2)

Phase 2 measured on the 1.69 M real quarry rows that a single chain statement cannot meet the original 15 ms per 4,096 roots:

  • finding member packs means decoding the varint lists inside SQL, at 2–3 µs per entry (61–127 ms);
  • even without the decode it takes 18–21 ms, and today's locate alone takes 19–27 ms.

The 15 ms came from a lists-only research run, so B5's time limit was restated relative to today's locate, measured in the same run.

Design Round trips per wave with chains Core change Decision
A: one statement, decode in SQL 2 none rejected (61–127 ms)
B: two statements in the provider; lists decoded in Rust 3 none chosen for 2.0
C: read_groups resolves member packs server-side 2 reopens core (planning rule and 2 MiB budget move after the read) after 2.0, if round trips dominate
Fused locate-and-read 1 per reference level large; decoding and planning move onto the shared server, needs an SQL-readable list format after 2.0 option, PostgreSQL only

A6 stays at ≤ 300 ms. B is estimated at about 260–315 ms; a miss is recorded as FAILED, not loosened.

Decisions (taken)

# Decision Taken
D1 List encoding chained zigzag varints (136.4 B/locator, measured) over fixed 14-byte entries (155.0)
D2 Server-side GC mark in 2.0 after 2.0 (prerequisite for #759's zero-bucket-read mark)
D3 Compaction rebuild threshold keep 10 %
D4 4-round-trip publication after 2.0, with pipelining
D5 Pre-2.0 PostgreSQL dev Stores refused at open
D6 Gate thresholds frozen before the first sample

3.0 extension (#759)

Call PostgreSQL 2.0 PostgreSQL + S3 SQLite + bucket SQLite local
publish base derives the physical list same, or a logical list stores the base locally ignored
locate_chains two statements (lists, then member packs) same; members name bucket packs local walk locate
read_groups batched substring parallel ranged GETs parallel ranged GETs whole packs
cache unit (pack_id, range) + digest (pack digest, range) on NVMe same today's

3.0 compaction rewrites packs. It must therefore either remap every affected list in the transaction that swaps in new locations, or switch to logical id-prefix lists. Logical lists measured 39–61 ms per 4,096 roots. The core port does not change either way.

Open risks

  1. Client cost per byte: the bench implies about 4 ms/MB in the Rust client, against 0.45 ms/MB for psql. Profile first: if it holds, byte savings matter about 5× more.
  2. Mount model: the head-mount estimate assumes an unbounded cache, so real numbers may be worse.
  3. Stale-hint retry: it is new logic in reconstruction and needs a deterministic wrong-hint test.
  4. List fill: it relies on publications serialising on store_lane, so it needs a two-Save test. It adds about 3 µs of lane hold per delta row whose base lies outside the batch.
  5. Large shapes: S1 and S2 expectations are extrapolated from quarry files of at most 15 MB.
  6. Unmeasured: PostgreSQL Commit p50 on a quarry replay and PostgreSQL GC mark time have never been measured. Nothing here claims them.

Corrections to earlier comments

Activity

  1. added this to the LayerFS v2.0.0 milestone on Nov 22, 2026
  2. added
    postgresql
    garbage collection
    v2.0.0
    P2
    core/storage
    engine/store
    P0
    and removed
    P2
    on Nov 22, 2026
  3. changed the title [-]2.0 storage: record each payload record's delta base in the catalog (hint column) so chains fetch in one wave[/-] [+]2.0 PostgreSQL storage: ancestor-location lists, group-ranged reads and a narrowed locator row[/+] on Nov 23, 2026
  4. changed the title [-]2.0 PostgreSQL storage: ancestor-location lists, group-ranged reads and a narrowed locator row[/-] [+]2.0 PostgreSQL storage: ancestor-location lists and group-ranged reads[/+] on Nov 23, 2026
  5. yifanxuaaa commented on Nov 24, 2026

    @yifanxuaaa
    ContributorAuthor

    Status 2026-11-24: frozen gate run once, does not pass; 3 decisions open

    Where the work is

    • Implementation: claude/758-pg-storage-2-0-d0f80c, local only, not pushed. 15 commits on layerfs_v2_0_0 8676948f10; frozen gate commit 960a823691. 106 files, +10,626 / −262. Design B (amendment of 2026-11-23): two-statement locate_chains, D1 varint ancestor lists, group-ranged reads.
    • Not merged into layerfs_v2_0_0, and it won't be until the decisions below are made.

    1. Final frozen gate (one run, 2026-11-24 01:44–02:12, commit 960a823691)

    The host was in its slow state during the run: SQLite on the same binary was about 1.37× slower than in its fast window. By the rules, a row over its limit counts as FAILED regardless.

    Passed (selected rows):

    Row Limit Measured
    A7 B2 cold read ≤ 1,135 ms 880.6 ms
    A8 round trips (B1/B2/B3) per-wave budget 257/273, 257/273, 907/1,023
    A9 statements ≤ 373 254
    A11 bytes ≤ 1.1× model 0.999 (B1), 1.015 (B3)
    A10/A12 B5 storage ≤ 141.8 B/locator 130.0
    B5 statement 1 vs locate ≤ 1.25× 0.733 random, 0.999 deep
    B5 statement 2 vs locate ≤ 0.5× 0.151 random, 0.073 deep
    A13 Save round trips ≤ 686 399
    A14 Save wall B2 ≤ 5,002 ms 2,590 ms
    A21 SQLite unchanged identical yes

    Also passed: B7 lane hold, logarithmic and quadratic rows; B8 time per call, locate/chain1 buffers and bytes per locator; same-decision digests (byte-identical on B1/B3/B4).

    Failed:

    Row Limit Measured
    A6 B1 cold read ≤ 300 ms 316.7 ms (slow host state)
    A14 Save wall B1 ≤ 1,637.1 ms 1,800.6 ms (+10 %, slow host state)
    B4 base-fetch round trips ≤ 40 41
    A15 B6 Exec ≤ 356.27 ms 938.0 ms
    A15 B6 Commit ≤ 18.05 ms 77.7 ms
    A22 history-scaling, stage 5 counters equal Save counters (11,19,3) → (12,23,4) → (12,20,3); read bytes 2.84 → 3.59 MB
    B7 "constant" rows equal, or ≤ 1.25× grow with history: cold read wall 2.03×, bytes 2.45×; head mount wall 1.68×; Save statements 11 → 13; catalog bytes per Commit +5.7 %; bytes per locator +0.13 %; client maxrss after cold read +24.8 %

    Not run: B4 Save round trips / wall vs today, because no B4 baseline exists.

    Six rows where the criterion itself may be wrong (owner decision):

    Row Why it can't hold as written What the data shows instead
    B7 totals ~16× totals include version 0's full copy the per-version increment is flat (slopes 0.88–0.99)
    B7 Save WAL / catalog bytes "equal" page-granular (8 KiB) rows and packs added are equal
    B7 directory bytes per pack "equal" the cumulative average includes version 0 the per-interval value is flat (43.8 / 43.9)
    B7 list bytes per delta row "equal" varint pack-id deltas widen as ids grow bounded by the depth cap
    B8 chain-2 buffers ≤ 2× at 387k pack rows the planner switches bitmap → index scan time per call ≤ 1.03×
    B8 "identical plans" same switch on the same pack_pkey same indexes, no Seq Scan

    2. B6 after the gate (DIAGNOSTIC samples only, not gate results)

    The docker-host change, merged into layerfs_v2_0_0 as #772 (87e46c652a): Store URLs are dialled as configured, and the per-call docker exec getent (52–103 ms in every Sandbox call's route step) is gone. #758 plus that change, one sample, load 8.3:

    ms create mount Exec Commit unmount remove
    #758 960a823691 169.5 120.0 798.8 75.4 88.0 133.4
    #758 + #772 81.8 53.6 742.1 16.0 27.4 65.2
    old build 76a32a9a10 (B6 baseline era), same host 319.4 30.5 739.2 18.8 22.7 232.2

    Commit is under its limit after #772. Exec is not.

    Where Exec's time goes (profiled on fd898060be; note b6-exec-profile.md):

    • LayerFS: every step outside the command in the Sandbox totals about 13 ms (true Exec 13–15 ms). The 68 statements take 42–67 ms of server time.
    • The rest is Docker Desktop's published-port forwarder.
    Path from worker to PostgreSQL Exec Raw 64 MiB COPY, no LayerFS com.docker.backend CPU
    published port (host.docker.internal), as in B6 663–721 ms 362–391 ms ~1.7 s per 64 MiB
    PostgreSQL container's bridge IP 316–339 ms 43–50 ms ~40 ms
    • The baseline build is equally slow today. The old build 76a32a9a10 has the same profile and the same ~740 ms. The 356.27 ms limit comes from the 11-06 sample (339.30 ms), when this path cost about 24 ms extra.
    • Unexplained: Docker Desktop 4.76.0, its settings and macOS are unchanged since then. A Docker Desktop restart at 12:37 changed nothing: COPY 368–386 ms, Exec 663.5 ms.
    • LayerFS-side options, none of which gets Exec under the limit on this path:

    3. Decisions open (owner)

    1. The six criterion rows above: keep as written, or judge by the per-increment / per-call measures.
    2. The real regressions: accept or fix the B7 cold-read and head-mount growth, B4 41 vs 40, and A6/A14 in the slow host state. Fixing means a fix round and a new frozen gate.
    3. B6 Exec: re-baseline A15 on today's host; or have B6 reach PostgreSQL over the Docker network instead of the published port; or keep the row open. Commit no longer needs a decision.

    Related

    🤖 Generated with Claude Code

  6. added a commit that references this issue on Nov 24, 2026
  7. yifanxuaaa commented on Nov 24, 2026

    @yifanxuaaa
    ContributorAuthor

    Merged into layerfs_v2_0_0 (2026-11-24)

    Owner decision: "merge 758 and accept b6 regression"; the other failed gate rows were accepted as minor ("i think others are quite minor?" → "proceed").

    PR What Merge
    #772 Store URLs dialled as configured; loopback refused with a host hint 87e46c652a
    #774 this issue: 2.0 PostgreSQL storage (design B) 6800e971fb
    #777 every Sandbox gets its own private network (includes the second-review fixes of #772) 73369a47b4

    Accepted gate rows:

    Row Measured Limit
    A15 B6 Exec 663–742 ms 356.27 ms
    A6 cold read 316.7 ms 300 ms
    A14 B1 Save wall 1,800.6 ms 1,637.1 ms
    B4 base-fetch round trips 41 40

    B6 Exec is over because of Docker Desktop's published-port forwarder. Over the Docker network, Exec is 316–339 ms, and the baseline-era build is equally slow on today's host.

    Also accepted:

    • A22 stage 5;
    • the six rows whose criterion can't hold as written;
    • the B7 drifts in bytes per locator and catalog bytes per Commit.

    A15 B6 Commit now passes: 14.2–16.0 ms after #772.

    Tracked follow-ups:

    Verification on the combined tree (87e46c652a + #774 + #777):

    • Linux, 513 targets of 12 crates: 2,063 passed.
    • macOS, the same targets with the PostgreSQL tests against a local trust-auth server: 2,031 passed. layerfs-storage 166/0, layerfs-persistence 566/0.
    • Failures: every one is also a failure on base, or passed on re-run. The one exception was a test-gating defect, fixed in Every Sandbox gets its own private network, with outbound access #777 (0363a8496c).

    🤖 Generated with Claude Code

  8. added a commit that references this issue on Nov 24, 2026
  9. 5 remaining items

  10. added 9 commits that reference this issue on Nov 24, 2026
  11. yifanxuaaa commented on Nov 24, 2026

    @yifanxuaaa
    ContributorAuthor

    Closing: merged into layerfs_v2_0_0 via #774 (6800e971fb); the owner accepted the failed gate rows. Follow-ups are tracked in #773, #768 and #771.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P0core/storageengine/storegarbage collectionpostgresqlv2.0.0

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions