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>
337 lines
14 KiB
TypeScript
337 lines
14 KiB
TypeScript
// One process of the simulated Peppa: `<runtime> roles.ts <role>`; run.ts starts them.
|
||
// Load per runner is taken from the live peppa DB (see README.md): a hook every ~10 s
|
||
// (a new process each time, like Claude's command hooks), 10 % of them a blocking
|
||
// question polled every 1.5 s, MCP progress every ~30 s and get_task every ~15 s.
|
||
// BENCH_LOAD multiplies these rates for the stress runs.
|
||
import { spawn } from "node:child_process";
|
||
import { appendFileSync, rmSync } from "node:fs";
|
||
import { createServer, type ServerResponse } from "node:http";
|
||
import { openDb, openSqlite, type Backend, type Db, type Row } from "./lib/db.ts";
|
||
import { publish, subscribe } from "./lib/notify.ts";
|
||
|
||
const env = process.env;
|
||
const role = process.argv[2];
|
||
const backend = env.BENCH_BACKEND as Backend;
|
||
const mode = env.BENCH_NOTIFY ?? "poll:1000";
|
||
const load = Number(env.BENCH_LOAD ?? 1);
|
||
const now = () => performance.timeOrigin + performance.now();
|
||
// Sleeps end early on SIGTERM so every process stops right after the run.
|
||
const wakers = new Set<() => void>();
|
||
const sleep = (ms: number) =>
|
||
new Promise<void>((r) => {
|
||
const done = () => (clearTimeout(t), wakers.delete(done), r());
|
||
const t = setTimeout(done, ms);
|
||
wakers.add(done);
|
||
});
|
||
const expo = (mean: number) => -Math.log(1 - Math.random()) * mean;
|
||
|
||
const samples: unknown[] = [];
|
||
const rec = (kind: string, op: string, ms: number, extra: object = {}) => samples.push({ kind, op, ms: +ms.toFixed(3), ...extra });
|
||
function flush() {
|
||
if (samples.length) appendFileSync(`${env.BENCH_OUT}/${role}-${process.pid}.jsonl`, samples.map((s) => JSON.stringify(s)).join("\n") + "\n");
|
||
samples.length = 0;
|
||
}
|
||
|
||
let stopping = false;
|
||
const stops: (() => void)[] = [];
|
||
process.on("SIGTERM", () => {
|
||
stopping = true;
|
||
stops.forEach((f) => f());
|
||
wakers.forEach((f) => f());
|
||
});
|
||
|
||
/** A write transaction with latency, busy retries and errors recorded. */
|
||
async function write(db: Db, op: string, stmts: [string, unknown[]][]): Promise<Row[][] | null> {
|
||
const t = now();
|
||
try {
|
||
const r = await db.tx(stmts);
|
||
rec("write", op, now() - t, db.lastBusy ? { busy: db.lastBusy } : {});
|
||
return r;
|
||
} catch (e) {
|
||
rec("write", op, now() - t, { busy: db.lastBusy, error: String((e as Error).message).slice(0, 80) });
|
||
return null;
|
||
}
|
||
}
|
||
async function read(db: Db, op: string, sql: string, params: unknown[] = []) {
|
||
const t = now();
|
||
const r = await db.all(sql, params);
|
||
rec("read", op, now() - t);
|
||
return r;
|
||
}
|
||
|
||
/** Reads events after the cursor whenever woken; records event→consumer latency. */
|
||
function consume(db: Db, who: string) {
|
||
let cursor = 0;
|
||
let busy = false;
|
||
let again = false;
|
||
const check = async () => {
|
||
if (busy) return void (again = true);
|
||
busy = true;
|
||
try {
|
||
do {
|
||
again = false;
|
||
const rows = await db.all("select id, payload from events where id > ? order by id limit 500", [cursor]);
|
||
for (const r of rows) {
|
||
cursor = Number(r.id);
|
||
const p = typeof r.payload === "string" ? JSON.parse(r.payload) : r.payload;
|
||
if (p?.t0) rec("deliver", who, now() - p.t0);
|
||
}
|
||
} while (again);
|
||
} finally {
|
||
busy = false;
|
||
}
|
||
};
|
||
db.all("select coalesce(max(id), 0) m from events").then((r) => (cursor = Number(r[0].m)));
|
||
stops.push(subscribe(db, mode, () => void check().catch(() => {})));
|
||
}
|
||
|
||
async function hook() {
|
||
const t0 = Number(env.BENCH_SPAWN_T);
|
||
rec("startup", "hook", now() - t0);
|
||
process.on("exit", flush);
|
||
const sid = Number(env.BENCH_SESSION);
|
||
const tOpen = now();
|
||
const db = await openDb(backend);
|
||
rec("open", "hook", now() - tOpen);
|
||
const [s] = await read(db, "hook.session", "select id, task_id, generation from sessions where id = ?", [sid]);
|
||
const ts = Date.now();
|
||
if (Math.random() < 0.1) {
|
||
const r = await write(db, "hook.question", [
|
||
["insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook, created_at) values (1, ?, ?, 'permission', 'Allow Bash(rm -rf build)', ?, true, ?) returning id", [s.task_id, sid, JSON.stringify(["Да", "Нет"]), ts]],
|
||
["update sessions set status = 'waiting_input', last_activity_at = ? where id = ?", [ts, sid]],
|
||
["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'question', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now() }), ts]],
|
||
]);
|
||
if (r) {
|
||
await publish(db, mode, Number(r[2][0].id));
|
||
const qid = Number(r[0][0].id);
|
||
const tAsk = now();
|
||
// Blocking PermissionRequest hook: poll for the PM's answer (hook.ts, every 1.5 s).
|
||
for (let i = 0; i < 40 && !stopping; i++) {
|
||
const [q] = await read(db, "hook.poll", "select answer from questions where id = ?", [qid]);
|
||
if (q?.answer) break;
|
||
await sleep(1500);
|
||
}
|
||
rec("roundtrip", "question", now() - tAsk);
|
||
await write(db, "hook.answered", [
|
||
["update questions set awaiting_hook = false where id = ?", [qid]],
|
||
["update sessions set status = 'running', auto_nudges = 0, last_activity_at = ? where id = ?", [Date.now(), sid]],
|
||
]);
|
||
}
|
||
} else {
|
||
const r = await write(db, "hook.event", [
|
||
["update sessions set status = 'running', last_activity_at = ? where id = ? and generation = ?", [ts, sid, s.generation]],
|
||
["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now(), hook: "Stop" }), ts]],
|
||
]);
|
||
if (r) await publish(db, mode, Number(r[1][0].id));
|
||
}
|
||
await db.close();
|
||
rec("total", "hook", now() - t0);
|
||
flush();
|
||
}
|
||
|
||
/** Plays Claude for one session: fires hooks one after another, each a new process. */
|
||
async function runner() {
|
||
const sid = env.BENCH_SESSION!;
|
||
while (!stopping) {
|
||
await sleep(expo(10_000 / load));
|
||
if (stopping) break;
|
||
const child = spawn(process.execPath, [new URL(import.meta.url).pathname, "hook"], {
|
||
env: { ...env, BENCH_SPAWN_T: String(now()), BENCH_SESSION: sid },
|
||
stdio: ["ignore", "ignore", "inherit"],
|
||
});
|
||
const kill = () => child.kill("SIGTERM");
|
||
stops.push(kill);
|
||
const code = await new Promise((r) => child.on("exit", r));
|
||
stops.splice(stops.indexOf(kill), 1);
|
||
// A hook killed by our own SIGTERM at the end of the run is not a failure.
|
||
if (code !== 0 && !(code === null && stopping)) rec("write", "hook.crashed", 0, { error: `hook exited with ${code}` });
|
||
}
|
||
flush();
|
||
}
|
||
|
||
async function mcp() {
|
||
const sid = Number(env.BENCH_SESSION);
|
||
const db = await openDb(backend);
|
||
const progress = async () => {
|
||
while (!stopping) {
|
||
await sleep(expo(30_000 / load));
|
||
if (stopping) break;
|
||
const ts = Date.now();
|
||
const r = await write(db, "mcp.progress", [
|
||
["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'progress', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: now(), text: "Сделал шаг 3 из 7" }), ts]],
|
||
["update tasks set updated_at = ? where id = ?", [ts, sid]],
|
||
]);
|
||
if (r) await publish(db, mode, Number(r[0][0].id));
|
||
}
|
||
};
|
||
const getTask = async () => {
|
||
while (!stopping) {
|
||
await sleep(expo(15_000 / load));
|
||
if (stopping) break;
|
||
await read(db, "mcp.get_task", "select * from tasks where id = ?", [sid]);
|
||
await read(db, "mcp.get_task", "select * from events where task_id = ? order by id desc limit 20", [sid]);
|
||
}
|
||
};
|
||
await Promise.all([progress(), getTask()]);
|
||
await db.close();
|
||
flush();
|
||
}
|
||
|
||
/** Telegram bot: outbox loop (1 s), reconcile (10 s + on events), heartbeat, PM answers. */
|
||
async function bot() {
|
||
const db = await openDb(backend);
|
||
consume(db, "bot");
|
||
let updateId = 1;
|
||
const answering = new Set<number>();
|
||
const reconcile = async () => {
|
||
const qs = await read(db, "bot.reconcile", "select id from questions where answer is null and telegram_message_id is null");
|
||
for (const q of qs) {
|
||
const id = Number(q.id);
|
||
await write(db, "bot.enqueue", [
|
||
["insert into telegram_outbox (dedupe_key, method, params, question_id, next_attempt_at, created_at) values (?, 'sendMessage', ?, ?, ?, ?) on conflict (dedupe_key) do nothing", [`q:${id}`, JSON.stringify({ chat_id: 1, text: "?" }), id, Date.now(), Date.now()]],
|
||
]);
|
||
if (answering.has(id)) continue;
|
||
answering.add(id);
|
||
// The PM taps a button 2–8 s later: record the update first, then answer (bot.ts).
|
||
setTimeout(async () => {
|
||
const u = updateId++;
|
||
await write(db, "bot.update", [["insert into telegram_updates (update_id, status, created_at) values (?, 'dispatching', ?)", [u, Date.now()]]]);
|
||
const r = await write(db, "bot.answer", [
|
||
["update questions set answer = 'Да', answered_via = 'telegram', answered_at = ? where id = ? and answer is null", [Date.now(), id]],
|
||
["update telegram_updates set status = 'done' where update_id = ?", [u]],
|
||
["insert into events (project_id, type, payload, created_at) values (1, 'question_answered', ?, ?) returning id", [JSON.stringify({ t0: now() }), Date.now()]],
|
||
]);
|
||
if (r) await publish(db, mode, Number(r[2][0].id));
|
||
}, 2000 + Math.random() * 6000);
|
||
}
|
||
};
|
||
const loops = [
|
||
(async () => {
|
||
while (!stopping) {
|
||
const rows = await read(db, "bot.outbox", "select id, question_id from telegram_outbox where status = 'pending' and next_attempt_at <= ? order by id limit 20", [Date.now()]);
|
||
for (const o of rows)
|
||
await write(db, "bot.sent", [
|
||
["update telegram_outbox set status = 'sent', attempts = attempts + 1, telegram_message_id = ?, sent_at = ? where id = ?", [Number(o.id) + 1000, Date.now(), o.id]],
|
||
["update questions set telegram_message_id = ? where id = ?", [Number(o.id) + 1000, o.question_id]],
|
||
]);
|
||
await sleep(1000);
|
||
}
|
||
})(),
|
||
(async () => {
|
||
while (!stopping) {
|
||
await reconcile();
|
||
await sleep(2000);
|
||
}
|
||
})(),
|
||
(async () => {
|
||
while (!stopping) {
|
||
await write(db, "bot.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:bot', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]);
|
||
await sleep(30_000);
|
||
}
|
||
})(),
|
||
];
|
||
await new Promise<void>((r) => stops.push(r));
|
||
await Promise.race([Promise.all(loops), sleep(3000)]);
|
||
flush();
|
||
await db.close();
|
||
}
|
||
|
||
/** Web: 3 open boards refreshing every 5 s + a live-update consumer. */
|
||
async function web() {
|
||
const db = await openDb(backend);
|
||
consume(db, "web");
|
||
const viewer = async () => {
|
||
await sleep(Math.random() * 5000);
|
||
while (!stopping) {
|
||
const t = now();
|
||
await db.all("select id, number, title, status, updated_at from tasks where project_id = 1 order by number");
|
||
await db.all("select id, task_id, status, last_activity_at from sessions where status in ('starting','running','waiting_input','idle','stalled','rate_limited')");
|
||
await db.all("select count(*) c from questions where answer is null");
|
||
await db.all("select id, type, created_at from events where project_id = 1 order by id desc limit 30");
|
||
rec("read", "web.board", now() - t);
|
||
await sleep(5000);
|
||
}
|
||
};
|
||
await Promise.all([viewer(), viewer(), viewer()]);
|
||
flush();
|
||
await db.close();
|
||
}
|
||
|
||
/** Watchdog tick every 30 s: list sessions, touch some, heartbeat. */
|
||
async function watchdog() {
|
||
const db = await openDb(backend);
|
||
while (!stopping) {
|
||
const ss = await read(db, "wd.sessions", "select id, task_id, status, last_activity_at from sessions where status not in ('done','failed')");
|
||
for (const s of ss) {
|
||
if (Math.random() >= 0.1) continue;
|
||
const r = await write(db, "wd.stalled", [
|
||
["update sessions set status = 'stalled' where id = ? and status = 'running'", [s.id]],
|
||
["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'stalled', ?, ?) returning id", [s.task_id, s.id, JSON.stringify({ t0: now() }), Date.now()]],
|
||
]);
|
||
if (r) await publish(db, mode, Number(r[1][0].id));
|
||
}
|
||
await write(db, "wd.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:watchdog', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]);
|
||
for (let i = 0; i < 30 && !stopping; i++) await sleep(1000);
|
||
}
|
||
flush();
|
||
await db.close();
|
||
}
|
||
|
||
/**
|
||
* The only process that opens the SQLite file for writing (backend=writer), or just a
|
||
* notify hub (notify=push with direct SQLite). Pushes new event ids to /subscribe.
|
||
*/
|
||
async function writer() {
|
||
const sock = env.BENCH_SOCK!;
|
||
rmSync(sock, { force: true });
|
||
const db = env.BENCH_HUB_ONLY ? null : await openSqlite((env.BENCH_WRITER_KIND as any) ?? "bun", env.BENCH_DB!);
|
||
const subs = new Set<ServerResponse>();
|
||
const push = (ids: unknown[]) => {
|
||
const line = JSON.stringify(ids) + "\n";
|
||
for (const s of subs) s.write(line);
|
||
};
|
||
const server = createServer((req, res) => {
|
||
if (req.url === "/subscribe") {
|
||
res.writeHead(200, { "content-type": "text/plain" });
|
||
res.flushHeaders();
|
||
subs.add(res);
|
||
req.on("close", () => subs.delete(res));
|
||
return;
|
||
}
|
||
let body = "";
|
||
req.setEncoding("utf8");
|
||
req.on("data", (c) => (body += c));
|
||
req.on("end", async () => {
|
||
const j = JSON.parse(body);
|
||
try {
|
||
if (req.url === "/publish") {
|
||
push(j.ids);
|
||
return void res.end("null");
|
||
}
|
||
const rows = await db!.tx(j.stmts);
|
||
const ids = j.stmts.flatMap(([s]: [string], i: number) => (s.startsWith("insert into events") ? rows[i].map((r) => r.id) : []));
|
||
res.end(JSON.stringify({ rows }));
|
||
if (ids.length) push(ids);
|
||
} catch (e) {
|
||
res.statusCode = 500;
|
||
res.end(JSON.stringify({ error: (e as Error).message }));
|
||
}
|
||
});
|
||
});
|
||
server.listen(sock);
|
||
await new Promise<void>((r) => stops.push(r));
|
||
server.close();
|
||
for (const s of subs) s.end();
|
||
await db?.close();
|
||
}
|
||
|
||
const roles: Record<string, () => Promise<void>> = { hook, runner, mcp, bot, web, watchdog, writer };
|
||
roles[role]().then(
|
||
() => process.exit(0),
|
||
(e) => {
|
||
console.error(`[${role}]`, e);
|
||
flush();
|
||
process.exit(1);
|
||
},
|
||
);
|