chadtmiller.com/monolith
An atproto PDS
0
0
Benchmarks run every server in Docker; perf held to its baseline
.knotless/workflows/gates.yml+2−2
| @@ -21,10 +21,10 @@ runners: [runner.knotless.dev] | ||
on: | ||
push: | ||
refs: [refs/heads/main] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/upgrade/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/upgrade/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/perf-baseline.json, harness/package*.json] | ||
pull: | ||
base: [refs/heads/main] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/upgrade/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/upgrade/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/perf-baseline.json, harness/package*.json] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, /opt/cargo-deny, /opt/browsers, /opt/chromium-debs, harness/node_modules, harness/spaces/node_modules, web/node_modules] | ||
env: | ||
PLAYWRIGHT_BROWSERS_PATH: /opt/browsers | ||
.knotless/workflows/perf.ymlnew+29−0
| @@ -0,0 +1,29 @@ | ||
# The server's speed against the reference's alone (spec/OPERATIONS.md, | ||
# "Performance"), as the nightly's perf step runs it, without the scale | ||
# run: when the owner asks, on main or on a branch (`knotless run rerun | ||
# <repo> --ref refs/heads/<branch> --workflow perf`). Its log is each part's | ||
# ratios to the reference's, from which harness/perf-baseline.json is set, | ||
# raised or lowered by a pull. Asked for when nothing else runs on the | ||
# runner, as the nightly runs it alone. | ||
# | ||
# Node, the harness's and the pages' packages and the build are kept | ||
# between runs. | ||
image: rust:1.98 | ||
runners: [runner.knotless.dev] | ||
on: | ||
asked: {refs: [refs/heads/*]} | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules, web/node_modules] | ||
steps: | ||
- uses: chadtmiller.com/steps/node@1 | ||
with: {version: 24.22.1} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: harness} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: web} | ||
# The pages, which pds-server embeds. | ||
- name: web | ||
run: cd web && PATH=/opt/node/bin:$PATH npm run build | ||
- name: build | ||
run: cargo build --release -p pds | ||
- name: perf | ||
run: cd harness && PATH=/opt/node/bin:$PATH node perf.mjs -- ../target/release/pds serve | ||
bench/docker/reference.Dockerfilenew+17−0
| @@ -0,0 +1,17 @@ | ||
# The reference PDS as the benchmark runs it (bench/README.md): dev-env's | ||
# TestPds from the harness's own packages, pinned by | ||
# harness/package-lock.json, on the Node of .node-version, started by | ||
# harness/bench-reference.mjs. Built by `node bench.mjs --setup` with | ||
# harness/ as its context: | ||
# | ||
# docker build -t spec-pds-bench-reference:local -f bench/docker/reference.Dockerfile harness | ||
# | ||
# The image also answers the benchmark's client ceiling (bench.mjs), with | ||
# its node and another entrypoint. | ||
FROM node:24.22.1-trixie-slim | ||
WORKDIR /bench | ||
COPY package.json package-lock.json ./ | ||
RUN npm ci --no-audit --no-fund | ||
COPY bench-reference.mjs ./ | ||
VOLUME /data | ||
ENTRYPOINT ["node", "bench-reference.mjs"] | ||
bench/docker/reference.Dockerfile.dockerignorenew+4−0
| @@ -0,0 +1,4 @@ | ||
* | ||
!package.json | ||
!package-lock.json | ||
!bench-reference.mjs | ||
bench/store/src/ladder.rsnew+211−0
| @@ -0,0 +1,211 @@ | ||
//! A record read a stage at a time (README.md): the read `getRecord` makes, | ||
//! taken apart, each stage the one before and one step more, over the same | ||
//! records in a table for each account, read through one block cache as | ||
//! the server reads them. The last stage, over HTTP, is `ladder.mjs`'s, | ||
//! of the records `records` prints. | ||
| ||
use crate::data::{SEED, State}; | ||
use crate::stores::{self, key, table_path}; | ||
use crate::util::{Rng, at, cores, par, scratch, us}; | ||
use pds_repo::data::{cid_string, decode, encode, to_json}; | ||
use pds_store::table::{BlockCache, Table}; | ||
use serde_json::json; | ||
use std::hint::black_box; | ||
use std::sync::Arc; | ||
use std::time::{Duration, Instant}; | ||
| ||
/// The bytes the block cache may hold: more than the data, so that every | ||
/// read after the first pass is of blocks it holds. | ||
const CACHE: u64 = 1 << 30; | ||
| ||
/// The records read one after another, and on each of the threads. | ||
const LOOKUPS: usize = 20_000; | ||
const THREADS: usize = 16; | ||
const EACH: usize = 5_000; | ||
| ||
/// The stages, each with what it adds to the one before. | ||
const STAGES: [&str; 4] = [ | ||
"the path's CID, from the account's table", | ||
"the record's block, by its CID", | ||
"the block decoded, as the server decodes it (`pds_repo::data::decode`)", | ||
"the record as `getRecord` answers it: `{uri, cid, value}` as JSON, `value` from `pds_repo::data::to_json`, serialized", | ||
]; | ||
| ||
/// An account: its DID and its table. | ||
struct Account { | ||
did: String, | ||
table: Table, | ||
} | ||
| ||
/// The CID and rev of the record at `path`, as the server takes them from | ||
/// its `P` entry. | ||
fn path_entry(a: &Account, cache: &BlockCache, path: &str) -> (Vec<u8>, String) { | ||
let v = a | ||
.table | ||
.get(&key(b'P', path.as_bytes()), cache) | ||
.expect("the table read") | ||
.expect("the path"); | ||
let n = usize::from(v[0]); | ||
let rev = String::from_utf8(v[1 + n..].to_vec()).expect("a rev"); | ||
(v[1..1 + n].to_vec(), rev) | ||
} | ||
| ||
/// The bytes of the block of `cid`, as the server takes them from its `B` | ||
/// entry: its rev read, its bytes held as the server's source answers them | ||
/// and copied into the record, as `pds_repo::Repo::get` does. | ||
fn block(a: &Account, cache: &BlockCache, cid: &[u8]) -> Vec<u8> { | ||
let v = a | ||
.table | ||
.get(&key(b'B', cid), cache) | ||
.expect("the table read") | ||
.expect("the record's block"); | ||
let n = usize::from(v[4]); | ||
std::str::from_utf8(&v[5..5 + n]).expect("a rev"); | ||
let held: Arc<[u8]> = v[5 + n..].into(); | ||
held.to_vec() | ||
} | ||
| ||
/// A read of the record at `path` of `a`, as far as `stage`: the bytes it | ||
/// leaves, so that nothing of it is left out. | ||
fn read(stage: usize, a: &Account, cache: &BlockCache, path: &str) -> usize { | ||
let (cid, rev) = path_entry(a, cache, path); | ||
if stage == 1 { | ||
return black_box((cid, rev)).0.len(); | ||
} | ||
let bytes = block(a, cache, &cid); | ||
if stage == 2 { | ||
return black_box(bytes).len(); | ||
} | ||
let value = decode(&bytes).expect("a record that decodes"); | ||
if stage == 3 { | ||
return black_box((value, bytes)).1.len(); | ||
} | ||
let (collection, rkey) = path.split_once('/').expect("a collection and a key"); | ||
let body = json!({ | ||
"uri": format!("at://{}/{collection}/{rkey}", a.did), | ||
"cid": cid_string(&cid), | ||
"value": to_json(&value), | ||
}) | ||
.to_string() | ||
.into_bytes(); | ||
black_box(body).len() | ||
} | ||
| ||
/// A record to read: its account and its path. | ||
type Want = (usize, String); | ||
| ||
/// `n` records drawn from all of them, the same for the same `which`. | ||
fn wants(paths: &[Want], which: u64, n: usize) -> Vec<Want> { | ||
let mut r = Rng::of(&[SEED, 9, which]); | ||
(0..n) | ||
.map(|_| paths[r.below(paths.len() as u64) as usize].clone()) | ||
.collect() | ||
} | ||
| ||
pub fn ladder(accounts: usize, records: usize) { | ||
let dir = scratch("ladder"); | ||
std::fs::create_dir_all(dir.join("tables")).expect("a directory"); | ||
// The accounts' tables, as `reads` writes them; and every record held | ||
// to decode, and to encode again to its own bytes, as the server's | ||
// records do. | ||
let made: Vec<(Vec<Want>, usize)> = par(accounts, cores(), |a| { | ||
let s = State::new(SEED, a as u64, accounts as u64, records); | ||
stores::write_table(&table_path(&dir, a), &s); | ||
let mut bytes = 0; | ||
for r in &s.records { | ||
let v = decode(&r.bytes).expect("a record that decodes"); | ||
assert_eq!(encode(&v), r.bytes, "a record in canonical DAG-CBOR"); | ||
bytes += r.bytes.len(); | ||
} | ||
( | ||
s.records.iter().map(|r| (a, r.path.clone())).collect(), | ||
bytes, | ||
) | ||
}); | ||
let block_bytes: usize = made.iter().map(|(_, b)| b).sum(); | ||
let paths: Vec<Want> = made.into_iter().flat_map(|(p, _)| p).collect(); | ||
let cache = BlockCache::new(CACHE); | ||
let open: Vec<Account> = (0..accounts) | ||
.map(|a| Account { | ||
did: crate::data::did(SEED, a as u64), | ||
table: Table::open(&table_path(&dir, a), &cache).expect("the account's table"), | ||
}) | ||
.collect(); | ||
| ||
// One pass over every record, the whole read, so that the cache holds | ||
// all a read touches. | ||
let mut body_bytes = 0; | ||
for (a, path) in &paths { | ||
body_bytes += read(4, &open[*a], &cache, path); | ||
} | ||
| ||
let one = wants(&paths, 0, LOOKUPS); | ||
let mut order: Vec<usize> = (0..one.len()).collect(); | ||
Rng::of(&[SEED, 10]).shuffle(&mut order); | ||
let many: Vec<Vec<Want>> = (0..THREADS) | ||
.map(|t| wants(&paths, 1 + t as u64, EACH)) | ||
.collect(); | ||
let rows: Vec<(Vec<Duration>, f64)> = (1..=STAGES.len()) | ||
.map(|stage| { | ||
let mut times: Vec<Duration> = order | ||
.iter() | ||
.map(|&i| { | ||
let (a, path) = &one[i]; | ||
let at = Instant::now(); | ||
black_box(read(stage, &open[*a], &cache, path)); | ||
at.elapsed() | ||
}) | ||
.collect(); | ||
times.sort(); | ||
let started = Instant::now(); | ||
std::thread::scope(|scope| { | ||
for mine in &many { | ||
let (open, cache) = (&open, &cache); | ||
scope.spawn(move || { | ||
for (a, path) in mine { | ||
black_box(read(stage, &open[*a], cache, path)); | ||
} | ||
}); | ||
} | ||
}); | ||
let rate = (THREADS * EACH) as f64 / started.elapsed().as_secs_f64(); | ||
(times, rate) | ||
}) | ||
.collect(); | ||
| ||
println!( | ||
"{accounts} accounts of {records} realistic records each, a table for each account read as the server reads one (`Table` through one `BlockCache`), after one pass over every record: every block a read touches is in the cache. A record's block is {} bytes on average; its `getRecord` body {} bytes. One at a time: {LOOKUPS} records drawn from all, on one thread; on {THREADS} threads, {EACH} each.\n", | ||
block_bytes / paths.len(), | ||
body_bytes / paths.len() | ||
); | ||
println!( | ||
"| stage | adds to the one before | one at a time: p50 µs | p99 µs | on {THREADS} threads: per s |" | ||
); | ||
println!("|--:|---|--:|--:|--:|"); | ||
for (i, (adds, (times, rate))) in STAGES.iter().zip(&rows).enumerate() { | ||
println!( | ||
"| {} | {adds} | {:.2} | {:.2} | {rate:.0} |", | ||
i + 1, | ||
us(times[times.len() / 2]), | ||
us(at(times, 99)), | ||
); | ||
} | ||
drop(open); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// The records of `accounts` accounts of `records` each, a line of JSON a | ||
/// record, `{account, rkey, value}`: what `ladder.mjs` writes through the | ||
/// server. | ||
pub fn records(accounts: usize, records: usize) { | ||
use std::io::Write; | ||
let mut out = std::io::BufWriter::new(std::io::stdout().lock()); | ||
for a in 0..accounts { | ||
for r in State::new(SEED, a as u64, accounts as u64, records).records { | ||
let value = decode(&r.bytes).expect("a record that decodes"); | ||
let (_, rkey) = r.path.split_once('/').expect("a collection and a key"); | ||
let line = json!({ "account": a, "rkey": rkey, "value": to_json(&value) }); | ||
writeln!(out, "{line}").expect("written"); | ||
} | ||
} | ||
} | ||
bench/store/src/main.rs+10−1
| @@ -9,6 +9,8 @@ | ||
//! store-bench firehose <commits> <accounts> [every] the events of one log for all, of SQLite, of RocksDB, and of a log for each account | ||
//! store-bench reads <accounts> <records> records read from tables, from SQLite and from RocksDB | ||
//! store-bench size <accounts> <records> what each takes on disk, and what zstd makes of a table | ||
//! store-bench ladder <accounts> <records> a record read from a table a stage at a time, to the body getRecord answers | ||
//! store-bench ladder-records <accounts> <records> those records as JSON, a line each, for ladder.mjs to write through the server | ||
//! | ||
//! Its files go under `BENCH_DIR`, by default `target/data` beside this | ||
//! crate, and are removed after: what a sync costs is that directory's | ||
| @@ -21,6 +23,7 @@ mod data; | ||
mod firehose; | ||
mod fj; | ||
mod frame; | ||
mod ladder; | ||
mod reads; | ||
mod rocks; | ||
mod scan; | ||
| @@ -65,6 +68,12 @@ fn main() { | ||
(Some("size"), &[accounts, records]) if accounts >= 1 && records >= 1 => { | ||
size::size(accounts as usize, records as usize) | ||
} | ||
(Some("ladder"), &[accounts, records]) if accounts >= 1 && records >= 1 => { | ||
ladder::ladder(accounts as usize, records as usize) | ||
} | ||
(Some("ladder-records"), &[accounts, records]) if accounts >= 1 && records >= 1 => { | ||
ladder::records(accounts as usize, records as usize) | ||
} | ||
// One store read one way, in a process of its own: `reads` starts these. | ||
(Some("reads-child"), _) if args.len() == 6 => { | ||
let number = |i: usize| args[i].parse().expect("a number"); | ||
| @@ -78,7 +87,7 @@ fn main() { | ||
} | ||
_ => { | ||
eprintln!( | ||
"store-bench write <commits> <writers> | spread <commits> <writers> <accounts> | unsynced <commits> <writers> <accounts> | scan <MiB>... | firehose <commits> <accounts> [every] | reads <accounts> <records> | size <accounts> <records>" | ||
"store-bench write <commits> <writers> | spread <commits> <writers> <accounts> | unsynced <commits> <writers> <accounts> | scan <MiB>... | firehose <commits> <accounts> [every] | reads <accounts> <records> | size <accounts> <records> | ladder <accounts> <records> | ladder-records <accounts> <records>" | ||
); | ||
std::process::exit(2); | ||
} | ||
bench/store/src/stores.rs+1−1
| @@ -60,7 +60,7 @@ pub fn db_path(dir: &Path) -> PathBuf { | ||
} | ||
| ||
/// Write an account's table: its blocks in order of CID, then its paths. | ||
fn write_table(path: &Path, s: &State) { | ||
pub fn write_table(path: &Path, s: &State) { | ||
let mut blocks: Vec<(&[u8], Vec<u8>)> = s | ||
.records | ||
.iter() | ||
bench/store/Cargo.lock+434−7
441 lines changed: not loaded until asked for.
bench/store/Cargo.toml+2−0
| @@ -9,6 +9,8 @@ publish = false | ||
| ||
[dependencies] | ||
pds-store = { path = "../../crates/pds-store" } | ||
# The ladder part's records decoded and rendered as the server's are. | ||
pds-repo = { path = "../../crates/pds-repo" } | ||
rusqlite = { version = "0.32", features = ["bundled"] } | ||
serde_json = "1" | ||
hex = "0.4" | ||
bench/store/ladder.mjsnew+258−0
| @@ -0,0 +1,258 @@ | ||
// The store benchmark's ladder over HTTP (README.md, "A record read, a | ||
// stage at a time"): the stage after `store-bench ladder`'s, the record read | ||
// through the server. Prints a Markdown table. | ||
// | ||
// node ladder.mjs <accounts> <records> | ||
// | ||
// The server (`../../target/release/pds`, built already with `just build`, | ||
// or `PDS_BIN`) is given `accounts` accounts, made with `createAccount` | ||
// against a directory of DIDs this script serves, and the records | ||
// `store-bench ladder-records` prints, `records` each, the records | ||
// `store-bench ladder` reads, written with `applyWrites`, 50 to a call and | ||
// 16 calls at once (a call a sync). Its backfill window is | ||
// half a second, so that once the writes stop an account's next write | ||
// folds its log into its table: the records are read from tables, as the | ||
// stages before read them. Then, on one kept-alive connection, one pass over | ||
// every record, and `_health` and `getRecord` timed one at a time; then each | ||
// 16 at once, a connection each. Its data directory is under `BENCH_DIR`, by | ||
// default `target/data` here, and is removed after. | ||
| ||
import { spawn, execFileSync } from 'node:child_process' | ||
import { existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, closeSync } from 'node:fs' | ||
import { Agent, createServer as httpServer, request } from 'node:http' | ||
import { createServer } from 'node:net' | ||
import { createHash } from 'node:crypto' | ||
import { join, resolve } from 'node:path' | ||
| ||
const here = new URL('.', import.meta.url).pathname | ||
const BIN = resolve(process.env.PDS_BIN ?? join(here, '../../target/release/pds')) | ||
const BENCH = join(here, 'target/release/store-bench') | ||
const ROOT = resolve(process.env.BENCH_DIR ?? join(here, 'target/data')) | ||
const [ACCOUNTS, RECORDS] = process.argv.slice(2).map(Number) | ||
if (!(ACCOUNTS >= 1 && RECORDS >= 1)) { | ||
console.error('node ladder.mjs <accounts> <records>') | ||
process.exit(2) | ||
} | ||
for (const [bin, how] of [[BIN, '`just build` first, or set PDS_BIN'], [BENCH, '`cargo build --release` here first']]) { | ||
if (!existsSync(bin)) { | ||
console.error(`no ${bin}: ${how}`) | ||
process.exit(1) | ||
} | ||
} | ||
| ||
/// The reads one at a time, and on each of the connections at once, as | ||
/// `store-bench ladder` makes them. | ||
const LOOKUPS = 20000 | ||
const AT_ONCE = 16 | ||
const EACH = 2000 | ||
const BATCH = 50 | ||
const COLLECTION = 'app.bsky.feed.post' | ||
| ||
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms)) | ||
const sha256 = (s) => createHash('sha256').update(s).digest() | ||
| ||
/// Numbers that are the same for the same seed (splitmix64). | ||
function rng(seed) { | ||
let x = BigInt(seed) | ||
return (n) => { | ||
x = (x + 0x9e3779b97f4a7c15n) & 0xffffffffffffffffn | ||
let z = x | ||
z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & 0xffffffffffffffffn | ||
z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & 0xffffffffffffffffn | ||
z ^= z >> 31n | ||
return Number((z * BigInt(n)) >> 64n) | ||
} | ||
} | ||
| ||
const freePort = () => new Promise((ok) => { | ||
const s = createServer().listen(0, '127.0.0.1', () => { | ||
const { port } = s.address() | ||
s.close(() => ok(port)) | ||
}) | ||
}) | ||
| ||
/// A directory of DIDs: it takes every operation posted to it, and serves | ||
/// each DID's document as its last operation makes it. | ||
async function directory() { | ||
const ops = new Map() | ||
const doc = (did, op) => ({ | ||
'@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1', 'https://w3id.org/security/suites/secp256k1-2019/v1'], | ||
id: did, | ||
alsoKnownAs: op.alsoKnownAs, | ||
verificationMethod: Object.entries(op.verificationMethods).map(([name, key]) => ({ | ||
id: `${did}#${name}`, type: 'Multikey', controller: did, publicKeyMultibase: key.slice('did:key:'.length), | ||
})), | ||
service: Object.entries(op.services).map(([name, s]) => ({ id: `#${name}`, type: s.type, serviceEndpoint: s.endpoint })), | ||
}) | ||
const server = httpServer((req, res) => { | ||
const chunks = [] | ||
req.on('data', (c) => chunks.push(c)) | ||
req.on('end', () => { | ||
const [did, ...rest] = decodeURIComponent(req.url.slice(1)).split('/') | ||
const answer = (status, body) => { | ||
res.writeHead(status, { 'content-type': 'application/json' }) | ||
res.end(body === undefined ? '' : JSON.stringify(body)) | ||
} | ||
if (req.method === 'POST') { | ||
ops.set(did, [...(ops.get(did) ?? []), JSON.parse(Buffer.concat(chunks))]) | ||
return answer(200) | ||
} | ||
const log = ops.get(did) | ||
if (!log) return answer(404, { message: `DID not registered: ${did}` }) | ||
const last = log.at(-1) | ||
switch (rest.join('/')) { | ||
case '': return answer(200, doc(did, last)) | ||
case 'data': return answer(200, { did, ...last }) | ||
case 'log/last': return answer(200, last) | ||
case 'log/audit': return answer(200, log.map((operation) => ({ did, operation, nullified: false }))) | ||
default: return answer(404) | ||
} | ||
}) | ||
}) | ||
await new Promise((ok) => server.listen(0, '127.0.0.1', ok)) | ||
return { url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() } | ||
} | ||
| ||
/// A request on `agent`: its status and body. | ||
const call = (agent, port, method, path, body, headers = {}) => new Promise((ok, fail) => { | ||
const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body)) | ||
const req = request({ host: '127.0.0.1', port, method, path, agent, headers: data ? { 'content-type': 'application/json', 'content-length': data.length, ...headers } : headers }, (res) => { | ||
const chunks = [] | ||
res.on('data', (c) => chunks.push(c)) | ||
res.on('end', () => ok({ status: res.statusCode, body: Buffer.concat(chunks) })) | ||
res.on('error', fail) | ||
}) | ||
req.on('error', fail) | ||
req.end(data) | ||
}) | ||
| ||
const dir = join(ROOT, 'ladder') | ||
rmSync(dir, { recursive: true, force: true }) | ||
mkdirSync(dir, { recursive: true }) | ||
const plc = await directory() | ||
const port = await freePort() | ||
const url = `http://127.0.0.1:${port}` | ||
const out = openSync(`${dir}.out`, 'w') | ||
const proc = spawn(BIN, ['serve'], { | ||
env: { | ||
PATH: process.env.PATH, PDS_PORT: String(port), PDS_DATA_DIR: dir, PDS_HOSTNAME: 'localhost', PDS_PUBLIC_URL: url, | ||
PDS_HANDLE_DOMAINS: '.test', PDS_PLC_URL: plc.url, PDS_PLC_ROTATION_KEY_HEX: sha256('rotation').toString('hex'), | ||
PDS_ADMIN_PASSWORD: 'admin-pass', PDS_INVITE_REQUIRED: 'false', PDS_RATE_LIMITS_ENABLED: 'false', | ||
PDS_REPO_BACKFILL_LIMIT_MS: '500', | ||
}, | ||
stdio: ['ignore', out, out], | ||
}) | ||
let exited = null | ||
proc.on('exit', (code) => (exited = code ?? 'killed')) | ||
const failed = (what) => new Error(`${what}${exited === null ? '' : `; the server exited ${exited}`}: ${readFileSync(`${dir}.out`, 'utf8').slice(-2000)}`) | ||
| ||
const one = new Agent({ keepAlive: true, maxSockets: 1 }) | ||
const many = new Agent({ keepAlive: true, maxSockets: AT_ONCE }) | ||
for (;;) { | ||
if (exited !== null) throw failed('starting') | ||
try { | ||
if ((await call(one, port, 'GET', '/xrpc/_health')).status === 200) break | ||
} catch {} | ||
await sleep(5) | ||
} | ||
| ||
// The accounts, and their records, 16 at once. | ||
const accounts = [] | ||
for (let i = 0; i < ACCOUNTS; i++) { | ||
const res = await call(one, port, 'POST', '/xrpc/com.atproto.server.createAccount', { handle: `ladder${i}.test`, email: `ladder${i}@example.com`, password: `ladder-${i}` }) | ||
if (res.status !== 200) throw failed(`createAccount: ${res.status} ${res.body}`) | ||
const { did, accessJwt } = JSON.parse(res.body) | ||
accounts.push({ did, auth: { authorization: `Bearer ${accessJwt}` } }) | ||
} | ||
const records = execFileSync(BENCH, ['ladder-records', String(ACCOUNTS), String(RECORDS)], { maxBuffer: 1 << 30 }) | ||
.toString().trim().split('\n').map((l) => JSON.parse(l)) | ||
const write = async (account, body, method) => { | ||
const a = accounts[account] | ||
const res = await call(many, port, 'POST', `/xrpc/com.atproto.repo.${method}`, { repo: a.did, validate: false, ...body }, a.auth) | ||
if (res.status !== 200) throw failed(`${method}: ${res.status} ${res.body}`) | ||
return JSON.parse(res.body) | ||
} | ||
const written = [] | ||
// An account's records, in order, at most `BATCH` to a call: one commit, | ||
// and one sync, each. | ||
const batches = [] | ||
for (let a = 0; a < ACCOUNTS; a++) { | ||
for (let i = 0; i < RECORDS; i += BATCH) batches.push(records.slice(a * RECORDS + i, a * RECORDS + Math.min(i + BATCH, RECORDS))) | ||
} | ||
await Promise.all(Array.from({ length: AT_ONCE }, async () => { | ||
while (batches.length) { | ||
const mine = batches.shift() | ||
const writes = mine.map(({ rkey, value }) => ({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTION, rkey, value })) | ||
const { results } = await write(mine[0].account, { writes }, 'applyWrites') | ||
mine.forEach((r, j) => written.push({ path: `/xrpc/com.atproto.repo.getRecord?repo=${accounts[r.account].did}&collection=${COLLECTION}&rkey=${r.rkey}`, cid: results[j].cid })) | ||
} | ||
})) | ||
| ||
// Past the backfill window twice over, one more record each, which folds | ||
// the log of each into its table; then until every fold is in place. | ||
await sleep(1200) | ||
await Promise.all(accounts.map((_, account) => write(account, { collection: COLLECTION, record: records[account * RECORDS].value }, 'createRecord'))) | ||
for (const at = performance.now(); ; await sleep(20)) { | ||
const folded = accounts.every(({ did }) => { | ||
const files = readdirSync(join(dir, 'repos', did)) | ||
return files.includes('repo.checkpoint') && !files.includes('repo.checkpoint.tmp') && files.filter((f) => f.endsWith('.log')).length === 1 | ||
}) | ||
if (folded) break | ||
if (performance.now() - at > 30000) throw failed('the accounts\' logs not folded in 30 s') | ||
} | ||
| ||
// One pass over every record, each checked. | ||
for (const w of written) { | ||
const res = await call(one, port, 'GET', w.path) | ||
if (res.status !== 200 || JSON.parse(res.body).cid !== w.cid) throw failed(`getRecord: ${res.status} ${res.body}`) | ||
} | ||
| ||
const draws = (seed, n) => { | ||
const below = rng(seed) | ||
return Array.from({ length: n }, () => written[below(written.length)].path) | ||
} | ||
/// Each of `paths` one after another on one connection: the times in µs, sorted. | ||
const timed = async (paths) => { | ||
const times = [] | ||
for (const path of paths) { | ||
const at = performance.now() | ||
const res = await call(one, port, 'GET', path) | ||
times.push((performance.now() - at) * 1000) | ||
if (res.status !== 200) throw failed(`${path}: ${res.status}`) | ||
} | ||
return times.sort((a, b) => a - b) | ||
} | ||
/// `paths` for each of 16 connections, at once: requests per second. | ||
const rate = async (paths) => { | ||
const started = performance.now() | ||
await Promise.all(paths.map(async (mine) => { | ||
for (const path of mine) { | ||
const res = await call(many, port, 'GET', path) | ||
if (res.status !== 200) throw failed(`${path}: ${res.status}`) | ||
} | ||
})) | ||
return (AT_ONCE * EACH) / ((performance.now() - started) / 1000) | ||
} | ||
const health = Array.from({ length: LOOKUPS }, () => '/xrpc/_health') | ||
await timed(health.slice(0, 2000)) | ||
const rows = [ | ||
['5a', 'a request answered with no record, `GET /xrpc/_health`: HTTP, the server\'s router and the client', await timed(health), await rate(Array.from({ length: AT_ONCE }, () => health.slice(0, EACH)))], | ||
['5b', 'stage 4 over HTTP, `com.atproto.repo.getRecord`: that, and the server\'s own work around the store', await timed(draws(1, LOOKUPS)), await rate(Array.from({ length: AT_ONCE }, (_, t) => draws(2 + t, EACH)))], | ||
] | ||
| ||
proc.kill('SIGTERM') | ||
await new Promise((ok) => (exited === null ? proc.on('exit', ok) : ok())) | ||
one.destroy() | ||
many.destroy() | ||
plc.close() | ||
closeSync(out) | ||
rmSync(dir, { recursive: true, force: true }) | ||
rmSync(`${dir}.out`, { force: true }) | ||
| ||
const at = (sorted, perCent) => sorted[Math.min(Math.floor((sorted.length * perCent) / 100), sorted.length - 1)] | ||
console.log(`Over HTTP, from the server (\`target/release/pds\`): ${ACCOUNTS} accounts of ${RECORDS} of the same records each, written with \`applyWrites\` and folded into their tables, after one pass over every record. One at a time: ${LOOKUPS} requests on one kept-alive connection from Node's \`http\` client; at once, ${AT_ONCE} connections of ${EACH} requests each.\n`) | ||
console.log(`| stage | is | one at a time: p50 µs | p99 µs | ${AT_ONCE} at once: per s |`) | ||
console.log('|--:|---|--:|--:|--:|') | ||
for (const [stage, adds, times, perS] of rows) { | ||
console.log(`| ${stage} | ${adds} | ${at(times, 50).toFixed(1)} | ${at(times, 99).toFixed(1)} | ${perS.toFixed(0)} |`) | ||
} | ||
bench/store/README.md+59−5
| @@ -3,8 +3,9 @@ | ||
What the way the server keeps its data costs, measured apart from the rest | ||
of the server: its logs and tables (`crates/pds-store`) beside SQLite and | ||
RocksDB under the same commits, in writes, replays, reads and bytes on | ||
disk, and how the server's start and memory follow the number of accounts | ||
in its service log. | ||
disk; a record's read taken a stage at a time, from the table to the | ||
server's `getRecord`; and how the server's start and memory follow the | ||
number of accounts in its service log. | ||
The PDS benchmark ([`../README.md`](../README.md)) measures whole servers, | ||
each with its own durability, in its own language and some in a container; | ||
this holds everything but the layout the same. The last results are in | ||
| @@ -29,9 +30,9 @@ Its files go under `BENCH_DIR`, by default `bench/store/target/data`, and | ||
are removed after each part; what a sync costs is that directory's disk's | ||
and file system's, so `BENCH_DIR` names the disk measured. It needs cargo, | ||
a C and a C++ compiler, libclang, Node and `ps`, and nothing of the | ||
harness's; without a server | ||
at `target/release/pds` (or `PDS_BIN`) the last part is left out, and says | ||
so. The parts before the last take about sixteen minutes on a laptop, at | ||
harness's; without a server at `target/release/pds` (or `PDS_BIN`) the | ||
last part and the ladder's stage over HTTP are left out, and say so. The | ||
parts that need no server take about sixteen minutes on a laptop, at | ||
most 5 GiB under `BENCH_DIR` and 1.5 GiB of memory, and a limit on open | ||
files of 20,000 or more: the benchmark raises its limit to the most it is | ||
allowed, as the server does when it starts, and under a lower one the row | ||
| @@ -445,6 +446,59 @@ figures from 16 threads are not that table's. Per way: a record by its | ||
path, a listing of 50 and the first read of an account, cold, and | ||
records per second from 16 threads, cold and warm. | ||
| ||
**A record read, a stage at a time** (`store-bench ladder <accounts> | ||
<records>`, then `node ladder.mjs <accounts> <records>`). The read a | ||
`getRecord` makes, taken apart, so that when it gets slower the stage that | ||
did can be named: 40 accounts of 100 realistic records each, the same | ||
records at every stage, each stage the one before and one step more. | ||
| ||
| stage | is | | ||
|--:|---| | ||
| 1 | the record's CID and rev, taken from its path's entry in the account's table (`Table::get` through one `BlockCache`, as the server reads its tables) | | ||
| 2 | that, and the record's block by its CID from the same table, its bytes copied out as the server's `Repo::get` copies them | | ||
| 3 | that, and the block decoded as the server decodes it (`pds_repo::data::decode`) | | ||
| 4 | that, and the body `getRecord` answers: `{uri, cid, value}` with `value` from `pds_repo::data::to_json`, serialized to bytes, as the server's `record_json` makes it and its router writes it | | ||
| 5a | `GET /xrpc/_health` from the server: a call that reads no record, what HTTP, the server's router and the client cost | | ||
| 5b | `com.atproto.repo.getRecord` of a record from the server: stage 4 and all the server does around it | | ||
| ||
Stages 1 to 4 are in Rust (`src/ladder.rs`), in one process, over tables | ||
written as the read part writes them, every record first held to decode | ||
and to encode again to its own bytes. Stage 5 is in Node (`ladder.mjs`): | ||
the server (`target/release/pds`, or `PDS_BIN`), with a directory of DIDs | ||
that the script serves, is given the 40 accounts by `createAccount` and | ||
the same records, as `store-bench ladder-records` prints them, by | ||
`applyWrites`, an account's records 50 to a call, 16 calls at once: a | ||
commit and a sync a call, so that the writes take seconds where a | ||
`createRecord` each would take a sync each. They are written with `validate: false`: a | ||
reply in them holds its CIDs as links where `app.bsky.feed.post` has | ||
strings, which the lexicon refuses. Its backfill window is half a second | ||
(`PDS_REPO_BACKFILL_LIMIT_MS=500`), so that once the writes have stopped, | ||
one more write to each account folds its log into its table, which the | ||
script waits for: every record is then read from a table, as in stages 1 | ||
to 4. | ||
| ||
Each stage is measured after one pass over every record, so that the | ||
block cache holds all a read touches, the server's too: 20,000 reads | ||
drawn from all the records, one after another on one thread (for stage 5, | ||
on one kept-alive connection from Node's `http` client), their p50 and | ||
p99; and reads per second from 16 threads of 5000 each (16 connections at | ||
once, 2000 requests each). The gaps say: | ||
| ||
- 2 less 1: a second key found in the table and its bytes copied; | ||
- 3 less 2: about 300 bytes of DAG-CBOR made into values; | ||
- 4 less 3: rendering: the values made JSON, the CIDs base32, the URI | ||
made, and all of it serialized; | ||
- 5a: the least a call through HTTP costs here, with no store in it, the | ||
client's own share among it; | ||
- 5b less 5a less 4: the server's own work around the store: the query | ||
read and the call routed to its method, the account found and its store | ||
locked, the takedowns looked at, the answer's headers. When `getRecord` | ||
gets slower and stages 1 to 4 do not, it is here. | ||
| ||
The client is in 5a and 5b alike, and drops out of the difference; at 16 | ||
at once it shares the machine's cores with the server, so those figures | ||
are of both. | ||
| ||
**Size and compression** (`store-bench size <accounts> <records>`). 200 | ||
accounts of 500 realistic commits each, a record a commit, and what they | ||
take on disk: | ||
bench/store/RESULTS.md+62−0
bench/store/run.sh+12−2
bench/impls.json+12−4
bench/README.md+170−76
bench/results.json+4653−600
A large diff, not shown.
bench/RESULTS.md+338−250
588 lines changed: not loaded until asked for.
docs/guide/comparing.md+26−9
docs/guide/contributing.md+3−2
harness/lib/loadpool.mjsnew+127−0
harness/bench-reference.mjsnew+27−0
harness/bench.mjs+788−389
1177 lines changed: not loaded until asked for.