From 6c247c52e8a155108fa84fa1050eec22f690873b Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 17:06:16 +0800 Subject: [PATCH 01/15] #758 phase 0: gate bench modes B1-B8 and client per-byte profile Adds the release-gate benchmark harness for #758 (spec section 5) as the example `storage_gate_bench` in layerfs-persistence, plus a diagnostic PostgreSQL client profile. Tooling only: no product code changes. - B1/B2: the prototype storage bench (delta_hint_bench, built from 343c59b2ca) with its workload, seeds, sizes, Save pattern, cache-state declaration and write/catalog/cold_read lines unchanged, so rows compare 1:1 with pg-parent-0ms/1ms and sqlite-parent. The hinted and nulled arms are gone; `hinted=` counts rows with a non-empty ancestors list. Added lines: RTT, WAL, server time by statement class, wire bytes, the needed-groups model and its ratios. `netem add|del` applies the +1 ms arm exactly as the baselines did. - B3/B4: one 256 MiB file over 10 versions (S1 edits) in resumable build steps and a cold read with locate waves, round trips, A8 budget, wire and product bytes; then one Save adding >= 578 packs, with base-fetch and publication calls attributed by pg_stat_statements statement class. - Needed-groups model computed independently of the product read plan: reference closure from content, delta chains from record headers over bench-fetched bodies, group extents from each pack's own directory. - B7: the 72-file history grown to 1,600 versions in resumable steps, with probes (catalog per Commit, cold read, chain statement, cold-cache Save, row-update counts). - B8: 1x and 10x synthetic catalogs from r758.lvar (quarry distribution of pack ids, roles, lists, groups; fresh ids for copies 1-9; real-length directories), resumable load, index, analyze, samples (random and depth >= 14), EXPLAIN-based measurement of a statement taken from a file, guest free-space guard, drop. - Hooks for later phases: the strict_hints switch (refused as NOT_WIRED until Phase 1), the chain statement file (Phase 2), extra DDL (b8 sql); new Diagnostics counters are read by name and print NA until present. - pg_client_profile and pg_copy_probe.py: the per-byte cost is the macOS Docker Desktop published-port transport (Rust and Python clients both about 4.1-4.4 ms/MB over it; in-VM paths 0.38-0.52 ms/MB), not the Rust driver. Smoke-checked at small sizes against today's product; no gate rows run. No tests deleted. Production LOC: 207,613 -> 207,613 (delta 0) core 40,989 -> 40,989 (0) engine 96,933 -> 96,933 (0) control 59,366 -> 59,366 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 8676948f10 and the staged tree (examples are excluded) Co-Authored-By: Claude Opus 5.5 --- .../examples/pg_client_profile.rs | 231 ++++++++++ .../examples/storage_gate_bench.rs | 95 ++++ .../examples/storage_gate_bench/b1.rs | 194 +++++++++ .../examples/storage_gate_bench/b7.rs | 248 +++++++++++ .../examples/storage_gate_bench/b8.rs | 404 +++++++++++++++++ .../examples/storage_gate_bench/b8_locate.sql | 1 + .../storage_gate_bench/b8_reference_chain.sql | 1 + .../examples/storage_gate_bench/common.rs | 307 +++++++++++++ .../examples/storage_gate_bench/large.rs | 293 +++++++++++++ .../examples/storage_gate_bench/model.rs | 266 ++++++++++++ .../examples/storage_gate_bench/monitor.rs | 410 ++++++++++++++++++ .../storage_gate_bench/pg_copy_probe.py | 132 ++++++ 12 files changed, 2582 insertions(+) create mode 100644 engine/crates/layerfs-persistence/examples/pg_client_profile.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/b1.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/b7.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/b8.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/b8_locate.sql create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/b8_reference_chain.sql create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/common.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/large.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/model.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/monitor.rs create mode 100644 engine/crates/layerfs-persistence/examples/storage_gate_bench/pg_copy_probe.py diff --git a/engine/crates/layerfs-persistence/examples/pg_client_profile.rs b/engine/crates/layerfs-persistence/examples/pg_client_profile.rs new file mode 100644 index 0000000000..e2be201276 --- /dev/null +++ b/engine/crates/layerfs-persistence/examples/pg_client_profile.rs @@ -0,0 +1,231 @@ +//! #758 open risk 1 DIAGNOSTIC: per-byte cost of reading pack bodies from +//! PostgreSQL in the Rust client, by stage, against the same bytes read by +//! other clients and paths. Not a qualification; one sample per arm. +//! +//! ```text +//! cargo +1.85.1 build --locked -j 6 --release -p layerfs-persistence --example pg_client_profile +//! target/release/examples/pg_client_profile "" +//! ``` +//! +//! The pack set is every pack of `` (a Store written by +//! `storage_gate_bench`, so real pack lengths and bodies), read in pack-id +//! order. Cache state (declared): the server's buffers are warmed by one +//! unmeasured COPY of the set; every arm then reads the same set once. +//! +//! Arms, all over the same connection string (macOS host, published port): +//! - `server`: server-only time, `EXPLAIN (ANALYZE, SERIALIZE BINARY)` of the +//! batched statement (detoast and serialization, nothing sent); +//! - `copy_out`: `COPY (...) TO STDOUT (FORMAT binary)` through +//! `postgres::Client::copy_out`, bytes counted and dropped: the driver's +//! transport floor; +//! - `rows_borrow`: one prepared statement for the whole set, binary result, +//! each body borrowed as `&[u8]` (no copy); +//! - `rows_vec`: the same, each body decoded as `Vec` (one copy), the +//! product's decode; +//! - `per_pack_vec`: one statement per pack (the product's per-pack round +//! trip shape), `Vec`; +//! - `text_hex`: the simple (text) protocol, bytea as hex text, decoded; +//! - `sha256`: SHA-256 over the bodies already in memory (the product's +//! whole-pack authentication); +//! - `port_read_packs`: the product port, `PostgresStorage::read_packs` in +//! batches within its 2 MiB budget (statement, decode, copy, SHA-256). +//! +//! The non-Rust comparisons (psql inside the server container over its Unix +//! socket and over TCP in its network namespace, and a Python stdlib client +//! on the host over the published port) are run by +//! `storage_gate_bench/pg_copy_probe.py`; see `758-impl/phase0-client-profile.md`. +use layerfs_persistence::{PostgresHandles, PostgresSelection}; +use layerfs_storage::port::PackPersistence; +use postgres::{Client, NoTls, SimpleQueryMessage}; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::time::Instant; + +const BINDING: &[u8] = b"delta-hint-bench"; +const CURSOR: [u8; 32] = [58; 32]; +const BUDGET: usize = 2 * 1024 * 1024; + +fn report(arm: &str, ms: f64, bytes: u64, statements: usize) { + println!( + "arm={arm} ms={ms:.2} bytes={bytes} statements={statements} ms_per_mb={:.3} mb_per_s={:.1}", + ms / (bytes as f64 / 1e6), + bytes as f64 / 1e6 / (ms / 1e3) + ); +} + +fn hex(text: &str) -> Vec { + let raw = text.strip_prefix("\\x").expect("hex bytea").as_bytes(); + let nibble = |c: u8| match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + _ => panic!("hex digit"), + }; + raw.chunks(2) + .map(|p| (nibble(p[0]) << 4) | nibble(p[1])) + .collect() +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (url, schema) = (&args[1], &args[2]); + let mut c = Client::connect(url, NoTls).unwrap(); + let packs: Vec<(i64, i64)> = c + .query( + &format!("SELECT pack_id, length FROM {schema}.pack ORDER BY pack_id"), + &[], + ) + .unwrap() + .iter() + .map(|r| (r.get(0), r.get(1))) + .collect(); + let ids: Vec = packs.iter().map(|p| p.0).collect(); + let total: i64 = packs.iter().map(|p| p.1).sum(); + let list = ids.iter().map(i64::to_string).collect::>().join(","); + let copy = format!( + "COPY (SELECT body FROM {schema}.pack WHERE pack_id IN ({list}) ORDER BY pack_id) TO STDOUT (FORMAT binary)" + ); + println!( + "set: schema={schema} packs={} body_bytes={total} mean_pack={:.0}", + packs.len(), + total as f64 / packs.len() as f64 + ); + + // Warm the server's buffers (unmeasured). + let mut sink = Vec::new(); + c.copy_out(copy.as_str()) + .unwrap() + .read_to_end(&mut sink) + .unwrap(); + + // server + let plan = c + .query( + &format!("EXPLAIN (ANALYZE, SERIALIZE BINARY, TIMING OFF, SUMMARY ON, FORMAT TEXT) SELECT body FROM {schema}.pack WHERE pack_id = ANY($1) ORDER BY pack_id"), + &[&ids], + ) + .unwrap(); + for row in &plan { + let line: String = row.get(0); + if line.contains("Execution Time") || line.contains("Serialization") { + println!("arm=server {}", line.trim()); + } + } + + // copy_out + let t = Instant::now(); + let mut reader = c.copy_out(copy.as_str()).unwrap(); + let mut buffer = vec![0u8; 1 << 20]; + let mut wire = 0u64; + loop { + let n = reader.read(&mut buffer).unwrap(); + if n == 0 { + break; + } + wire += n as u64; + } + drop(reader); + report("copy_out", t.elapsed().as_secs_f64() * 1e3, wire, 1); + + let batched = c + .prepare(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id = ANY($1) ORDER BY pack_id" + )) + .unwrap(); + // rows_borrow + let t = Instant::now(); + let rows = c.query(&batched, &[&ids]).unwrap(); + let mut n = 0u64; + for row in &rows { + n += row.get::<_, &[u8]>(0).len() as u64; + } + report("rows_borrow", t.elapsed().as_secs_f64() * 1e3, n, 1); + drop(rows); + + // rows_vec + let t = Instant::now(); + let rows = c.query(&batched, &[&ids]).unwrap(); + let bodies: Vec> = rows.iter().map(|r| r.get::<_, Vec>(0)).collect(); + let n: u64 = bodies.iter().map(|b| b.len() as u64).sum(); + report("rows_vec", t.elapsed().as_secs_f64() * 1e3, n, 1); + drop(rows); + + // per_pack_vec + let one = c + .prepare(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id = $1" + )) + .unwrap(); + let t = Instant::now(); + let mut n = 0u64; + for id in &ids { + let row = c.query_one(&one, &[id]).unwrap(); + n += row.get::<_, Vec>(0).len() as u64; + } + report( + "per_pack_vec", + t.elapsed().as_secs_f64() * 1e3, + n, + ids.len(), + ); + + // text_hex + let t = Instant::now(); + let messages = c + .simple_query(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id IN ({list}) ORDER BY pack_id" + )) + .unwrap(); + let received = t.elapsed().as_secs_f64() * 1e3; + let mut n = 0u64; + for m in &messages { + if let SimpleQueryMessage::Row(r) = m { + n += hex(r.get(0).unwrap()).len() as u64; + } + } + let decoded = t.elapsed().as_secs_f64() * 1e3; + println!("arm=text_hex received_ms={received:.2} (hex text, 2x bytes on the wire)"); + report("text_hex", decoded, n, 1); + drop(messages); + + // sha256 + let t = Instant::now(); + let mut acc = 0u8; + for b in &bodies { + acc ^= Sha256::digest(b)[0]; + } + report("sha256", t.elapsed().as_secs_f64() * 1e3, n, 0); + std::hint::black_box(acc); + drop(bodies); + + // port_read_packs + let handles = + PostgresHandles::open_read_only(&PostgresSelection::new(url, schema), BINDING, CURSOR) + .unwrap(); + let port = handles.storage.clone(); + let mut batches: Vec> = vec![Vec::new()]; + let mut held = 0usize; + for (id, length) in &packs { + if held + *length as usize > BUDGET && !batches.last().unwrap().is_empty() { + batches.push(Vec::new()); + held = 0; + } + held += *length as usize; + batches.last_mut().unwrap().push(*id); + } + let w0 = port.diagnostics().unwrap(); + let t = Instant::now(); + let mut out = Vec::new(); + let mut n = 0u64; + for batch in &batches { + port.read_packs(batch, &mut out).unwrap(); + n += out.iter().map(|p| p.body().len() as u64).sum::(); + } + let ms = t.elapsed().as_secs_f64() * 1e3; + let w1 = port.diagnostics().unwrap(); + report( + "port_read_packs", + ms, + n, + (w1.statements - w0.statements) as usize, + ); +} diff --git a/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs b/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs new file mode 100644 index 0000000000..375f25d815 --- /dev/null +++ b/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs @@ -0,0 +1,95 @@ +//! #758 release-gate benchmark rows B1-B4, B7 and B8 (spec `SPEC-758-2.0.md` +//! section 5), each one bounded command, longer rows as resumable steps. +//! +//! Build once (release, as the baselines were): +//! +//! ```text +//! cargo +1.85.1 build --locked -j 6 --release -p layerfs-persistence --example storage_gate_bench +//! BIN=target/release/examples/storage_gate_bench +//! U="host=127.0.0.1 port=55758 user=postgres dbname=postgres sslmode=disable" +//! export LAYERFS_CONSTRUCTION_WORKERS=1 +//! ``` +//! +//! Server: the dedicated bench container `lfs-bench-758-pg` (published port +//! 55758; `GATE_PG_CONTAINER` overrides the name used for wire bytes, guest +//! space and netem). Shipped defaults (`synchronous_commit = local`); `SYNC=off` +//! only for B6-style diagnostics. Add `--strict-hints` to every read row once +//! Phase 1's switch is wired (`common::strict`, marked HOOK); until then it +//! is refused as NOT_WIRED. +//! +//! | Row | Commands, in order | Key output | +//! |---|---|---| +//! | B1 | `$BIN b1 postgresql "$U" g0_b1 g0` | `write:` `catalog:` `cold_read:` (as the baselines), `cold_read_counters:`, `cold_read_bytes:` (model, ratios), `cold_read_server:` | +//! | B2 | `$BIN netem add`; `$BIN b1 postgresql "$U" g0_b2 g0+1ms`; `$BIN netem del` | as B1; `arm: rtt_select1_median_us` shows the delay | +//! | B3 | `$BIN reset "$U" g0_b3`; `$BIN b3 build "$U" g0_b3 --to 4`; `... --to 7`; `... --to 10`; `$BIN b3 read "$U" g0_b3` | `b3_save:` per version; `b3_cold_read:` (`locate_waves`, `round_trips`, `a8_budget_round_trips`), `b3_cold_read_bytes:` (`model_bytes`, ratios) | +//! | B4 | `$BIN b4 save "$U" g0_b3` (after B3) | `b4_shape:`, `b4_construct:`, `b4_save:` (`packs_added`, `shape_ok`, `base_fetch_round_trips`, `publication_calls`) | +//! | B7 | `$BIN reset "$U" g0_b7`; `b7 grow --to 100`; `b7 probe`; `b7 grow --to 400`; `b7 probe`; `b7 grow --to 1000`; `b7 grow --to 1600`; `b7 probe` (each `"$U" g0_b7`, probes with `--chain-sql FILE` once Phase 2 exists) | `b7_grow:`, `b7_catalog:`, `b7_cold_read:`, `b7_chain_statement:`, `b7_save:` | +//! | B8 | per size S in {`g0_b8_x1` (copy 0), `g0_b8_x10` (copies 0-9)}: `b8 create "$U" S --pack-lengths packs.tsv`; `b8 load "$U" S --copy C` per copy; `b8 index`; [`b8 sql "$U" S extra.sql`]; `b8 analyze`; `b8 samples`; `b8 measure "$U" S --sql STATEMENT --label L`; after both sizes, `b8 drop` each | `b8_catalog:` (`bytes_per_locator`), `b8_statement:` per sample (`exec_ms`, `buffers`, `plan_md5`, `plan`) | +//! +//! `b8 measure` with `storage_gate_bench/b8_locate.sql` runs today's locate +//! statement; the Phase 2 chain statement goes in a file of the same form +//! (`{schema}`, `$1` ids `bytea[]`, optional `$2` keys `bigint[]`). The +//! `g0_b8_x1` measurement is also the B5 row (real locators, product row). +//! `b8 space` prints the Docker guest's free bytes; `load` refuses a copy +//! that would leave under 20 GiB. +//! +//! **Counters.** `statements`/`round_trips`/`prepares` are the port's own +//! `SqlWork` (the baselines' counters). Server time and the per-class call +//! counts come from `pg_stat_statements`, reset before each phase, the +//! bench's own statements excluded (`monitor`). Wire bytes are the server +//! container's `eth0` counters read before and after, outside timed regions. +//! The needed-groups model is in `storage_gate_bench/model.rs`. +//! +//! **Cache state (declared).** As the baselines: each read row's reader is a +//! fresh `Storage` (empty locator and pack caches); the server's buffers are +//! warm (the Store was just written). B8 runs one unmeasured execution before +//! its one measured EXPLAIN. One sample per case; nothing is rerun for a +//! number. Size overrides (`VERSIONS`, `FILES_*`, `B3_MIB`, `B4_FILES`) exist +//! for smoke runs only; rows print `gate_size=false` when one is set. +//! +//! Every command fits the 2-minute limit at gate size except where the +//! how-to (`758-impl/phase0-bench-howto.md`) says otherwise; split B3/B7 +//! steps further with smaller `--to` increments if a step approaches it. + +#[path = "storage_gate_bench/b1.rs"] +mod b1; +#[path = "storage_gate_bench/b7.rs"] +mod b7; +#[path = "storage_gate_bench/b8.rs"] +mod b8; +#[path = "storage_gate_bench/common.rs"] +mod common; +#[path = "storage_gate_bench/large.rs"] +mod large; +#[path = "storage_gate_bench/model.rs"] +mod model; +#[path = "storage_gate_bench/monitor.rs"] +mod monitor; + +fn main() { + let args: Vec = std::env::args().collect(); + let row = args.get(1).map(String::as_str).unwrap_or(""); + let step = args.get(2).map(String::as_str).unwrap_or(""); + match (row, step) { + ("b1", _) => b1::run(&args), + ("b3", "build") => large::b3_build(&args), + ("b3", "read") => large::b3_read(&args), + ("b4", "save") => large::b4_save(&args), + ("b7", "grow") => b7::grow(&args), + ("b7", "probe") => b7::probe(&args), + ("b8", _) => b8::run(&args), + ("netem", action) => std::process::exit(monitor::netem(action)), + ("reset", _) => large::reset(&args), + _ => { + eprintln!( + "usage: storage_gate_bench b1 (postgresql | sqlite )