peppa/bench/sqlite/run.ts
Асель 50b1d1afec PEP-36: benchmark SQLite vs Postgres and propose Bun + SQLite stack
bench/sqlite (outside the workspace): Peppa-like load with 10/20 runners,
a hook process per event, MCP, bot, web and watchdog; bun:sqlite,
node:sqlite, better-sqlite3, a single-writer service and Postgres; notify
replacements (cursor polling, fs.watch on WAL, unix-socket push); a
ceiling test; a schema port to sqlite with a data copy from Postgres and
a check of drizzle transactions.

openspec/changes/pep-36-lightweight-stack: proposal, design with the
numbers, specs (platform-storage, service-monitoring), phased tasks.
No product code changes; the move waits for the PM's decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:28:59 +05:00

129 lines
6.1 KiB
TypeScript

// Orchestrator: fresh database, then N runners (+ their hook processes) and N MCP
// servers, bot, web, watchdog (and the writer/hub when needed) for --duration seconds.
// node run.ts --backend bun --runtime bun --runners 10 --load 1 --duration 90 --notify poll:1000
// Prints and saves (results/<name>/summary.json) latency percentiles per operation.
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { parseArgs } from "node:util";
import { openPg, openSqlite } from "./lib/db.ts";
import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts";
const here = new URL(".", import.meta.url).pathname;
const { values: a } = parseArgs({
options: {
backend: { type: "string", default: "bun" },
runtime: { type: "string" },
runners: { type: "string", default: "10" },
load: { type: "string", default: "1" },
duration: { type: "string", default: "90" },
notify: { type: "string" },
name: { type: "string" },
},
});
const backend = a.backend!;
const runtime = a.runtime ?? (backend === "node" || backend === "better" || backend === "pg" ? "node" : "bun");
const notify = a.notify ?? (backend === "pg" ? "pg" : "poll:1000");
const runners = Number(a.runners);
const name = a.name ?? `${backend}-${runtime}-r${runners}-x${a.load}-${notify.replace(":", "")}`;
const bin = runtime === "bun" ? `${homedir()}/.bun/bin/bun` : process.execPath;
const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-bench-${process.pid}`;
const out = `${here}results/${name}`;
rmSync(out, { recursive: true, force: true });
mkdirSync(out, { recursive: true });
mkdirSync(work, { recursive: true });
const sockDir = `/tmp/pb-${process.pid}`;
mkdirSync(sockDir, { recursive: true });
const env: Record<string, string> = {
...(process.env as Record<string, string>),
BENCH_BACKEND: backend,
BENCH_NOTIFY: notify,
BENCH_LOAD: a.load!,
BENCH_OUT: out,
BENCH_DB: `${work}/peppa.db`,
// macOS caps unix socket paths at 104 bytes, so sockets live in a short /tmp dir.
BENCH_WRITER_SOCK: `${sockDir}/writer.sock`,
BENCH_HUB_SOCK: `${sockDir}/hub.sock`,
BENCH_READ_KIND: runtime === "bun" ? "bun" : "node",
BENCH_WRITER_KIND: runtime === "bun" ? "bun" : "node",
};
// Fresh database with the seed.
if (backend === "pg") {
if (!env.BENCH_PG_URL) throw new Error("BENCH_PG_URL (…/peppa_bench) is required");
if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL)) throw new Error("refusing to use a database other than peppa_bench");
const db = await openPg(env.BENCH_PG_URL);
await db.all("drop schema public cascade");
await db.all("create schema public");
for (const s of pgSchema) await db.all(s);
await db.tx(seedStmts(runners));
await db.close();
} else {
const db = await openSqlite("node", env.BENCH_DB);
await db.all("PRAGMA journal_mode = WAL");
for (const s of sqliteSchema) await db.all(s);
await db.tx(seedStmts(runners));
await db.close();
}
const procs: ChildProcess[] = [];
const start = (role: string, extra: Record<string, string> = {}) => {
const p = spawn(bin, [`${here}roles.ts`, role], { env: { ...env, ...extra }, stdio: ["ignore", "inherit", "inherit"] });
procs.push(p);
return p;
};
const waitSock = async (s: string) => {
for (let i = 0; i < 100 && !existsSync(s); i++) await new Promise((r) => setTimeout(r, 50));
};
const servers: ChildProcess[] = [];
if (backend === "writer") {
servers.push(start("writer", { BENCH_SOCK: env.BENCH_WRITER_SOCK }));
await waitSock(env.BENCH_WRITER_SOCK);
} else if (notify === "push") {
servers.push(start("writer", { BENCH_SOCK: env.BENCH_HUB_SOCK, BENCH_HUB_ONLY: "1" }));
await waitSock(env.BENCH_HUB_SOCK);
}
procs.length = 0;
const clients = [start("bot"), start("web"), start("watchdog")];
for (let i = 1; i <= runners; i++) clients.push(start("mcp", { BENCH_SESSION: String(i) }), start("runner", { BENCH_SESSION: String(i) }));
console.error(`[bench] ${name}: ${clients.length} processes for ${a.duration}s`);
await new Promise((r) => setTimeout(r, Number(a.duration) * 1000));
const exited = (ps: ChildProcess[]) => Promise.all(ps.map((p) => (p.exitCode !== null ? null : new Promise((r) => p.on("exit", r)))));
for (const p of clients) p.kill("SIGTERM");
await Promise.race([exited(clients), new Promise((r) => setTimeout(r, 90_000).unref())]);
for (const p of servers) p.kill("SIGTERM");
await exited(servers);
// Aggregate.
type S = { kind: string; op: string; ms: number; busy?: number; error?: string };
const all: S[] = readdirSync(out)
.filter((f) => f.endsWith(".jsonl"))
.flatMap((f) => readFileSync(`${out}/${f}`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)));
const pct = (xs: number[], p: number) => (xs.length ? xs[Math.min(xs.length - 1, Math.floor((p / 100) * xs.length))] : NaN);
const summarize = (xs: S[]) => {
const ms = xs.map((x) => x.ms).sort((x, y) => x - y);
const r = (v: number) => +v.toFixed(2);
return { n: ms.length, p50: r(pct(ms, 50)), p95: r(pct(ms, 95)), p99: r(pct(ms, 99)), max: r(ms.at(-1) ?? NaN), busy: xs.reduce((s, x) => s + (x.busy ?? 0), 0), errors: xs.filter((x) => x.error).length };
};
const groups = new Map<string, S[]>();
for (const s of all) {
const k = `${s.kind} ${s.op}`;
groups.set(k, [...(groups.get(k) ?? []), s]);
}
const rows: Record<string, ReturnType<typeof summarize>> = {};
rows["write ALL"] = summarize(all.filter((s) => s.kind === "write"));
for (const k of [...groups.keys()].sort()) rows[k] = summarize(groups.get(k)!);
const errors = [...new Set(all.filter((s) => s.error).map((s) => s.error))];
const summary = { name, backend, runtime, notify, runners, load: Number(a.load), duration: Number(a.duration), rows, errors, at: new Date().toISOString() };
writeFileSync(`${out}/summary.json`, JSON.stringify(summary, null, 2));
for (const f of readdirSync(out)) if (f.endsWith(".jsonl")) rmSync(`${out}/${f}`);
console.log(`\n== ${name}`);
console.table(rows);
if (errors.length) console.log("errors:", errors);
rmSync(work, { recursive: true, force: true });
rmSync(sockDir, { recursive: true, force: true });