// PEP-225: load of the tab channel — N tabs (WebSockets) on a COPY of a database, each watching // what a tab watches (home or a project board, a story, attention, version, me), while a writer // changes story statuses. Reports CPU of the process (hub + sockets), SQLite time of the hub's // checks and how fast an event reaches every tab. // PEPPA_DB= PEPPA_SECRET=x node apps/web/scripts/bench-live.ts [tabs=50] [seconds=20] [writesPerSec=2] import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { discussionUnread, getNotifyPrefs, getUser, sign, userProjectIds } from "@peppa/core"; import { createDb } from "@peppa/db"; import { liveHub, setLiveProvider } from "@peppa/runner"; import { createLiveWs, readCookie } from "@peppa/runner/live-ws"; const tabs = Number(process.argv[2] ?? 50); const seconds = Number(process.argv[3] ?? 20); const rate = Number(process.argv[4] ?? 2); const db = createDb(); const c = db.$client; const owner = c.prepare(`SELECT owner_id AS id FROM projects WHERE owner_id IS NOT NULL AND deleted_at IS NULL GROUP BY owner_id ORDER BY count(*) DESC LIMIT 1`).get() as { id: number }; const user = (await getUser(db, owner.id))!; const projects = c.prepare(`SELECT id FROM projects WHERE owner_id = ? AND deleted_at IS NULL`).all(user.id) as Array<{ id: number }>; const taskRows = c.prepare(`SELECT id, project_id AS p, status FROM tasks WHERE project_id IN (${projects.map((p) => p.id).join(",")}) AND archived_at IS NULL LIMIT 40`).all() as Array<{ id: number; p: number; status: string }>; if (!taskRows.length) throw new Error("no tasks to change"); setLiveProvider("attention", async (_db, uid) => { // The queries of navCounts (lib/queries.ts needs the Next bundler for its imports). const ids = await userProjectIds(db, uid); const q = ids.length ? (c.prepare(`SELECT count(*) AS n FROM questions WHERE answered_at IS NULL AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0; const w = ids.length ? (c.prepare(`SELECT count(*) AS n FROM sessions WHERE status = 'waiting_input' AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0; const chats = [...(await discussionUnread(db, uid)).values()].reduce((a, b) => a + b, 0); const { sound } = await getNotifyPrefs(db, uid); return { count: q + w, chats, sound }; }); const token = sign({ uid: user.id, exp: Date.now() + 3600_000 }); const ws = createLiveWs({ db, authenticate: async (req) => (readCookie(req.headers.cookie, "peppa_session") === token ? user : null), boot: () => "bench" }); const server = createServer((_q, r) => r.end()); server.on("upgrade", (q, s, h) => ws.handleUpgrade(q, s, h)); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const port = (server.address() as AddressInfo).port; // Every change: when it was written, when each tab got it. const written = new Map(); const lat: number[] = []; let events = 0; const socks: WebSocket[] = []; for (let i = 0; i < tabs; i++) { const t = taskRows[i % taskRows.length]!; const scopes = i % 3 === 0 ? ["home", "attention", "version", "me"] : ["attention", "version", "me", `project:${t.p}`, `task:${t.id}`]; const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(`ws://127.0.0.1:${port}/api/ws`, { headers: { cookie: `peppa_session=${token}` } }); sock.onopen = () => scopes.forEach((scope) => sock.send(JSON.stringify({ t: "sub", scope }))); sock.onmessage = (e) => { const m = JSON.parse(String(e.data)) as { t: string; type?: string; tasks?: Array<{ id: number; status: string }> }; if (m.t !== "ev") return; events++; for (const r of m.tasks ?? []) { const at = written.get(`${r.id}:${r.status}`); if (at) lat.push(performance.now() - at); } }; socks.push(sock); } await new Promise((r) => setTimeout(r, 1500)); console.log(`tabs: ${tabs} open=${ws.clients}, watched scopes: ${liveHub(db).watched.length}`); // Time spent in the hub's checks (SQLite fingerprints + providers). const hub = liveHub(db) as unknown as { check: () => Promise }; const orig = hub.check.bind(hub); let checkMs = 0; let checks = 0; hub.check = async () => { const t = performance.now(); await orig(); checkMs += performance.now() - t; checks++; }; // Time per scope kind (BENCH_SCOPES=1). const perKind = new Map(); if (process.env.BENCH_SCOPES) { const h = liveHub(db) as unknown as { checkOne: (w: { scope: string }) => Promise }; const one = h.checkOne.bind(h); h.checkOne = async (w) => { const t = performance.now(); await one(w); const k = w.scope.split(":")[0]!; perKind.set(k, (perKind.get(k) ?? 0) + performance.now() - t); }; } const cpu0 = process.cpuUsage(); const t0 = performance.now(); const statuses = ["in_progress", "review", "backlog"]; let writes = 0; const writer = setInterval(() => { const t = taskRows[writes % taskRows.length]!; const next = statuses[(statuses.indexOf(t.status) + 1) % statuses.length]!; t.status = next; written.set(`${t.id}:${next}`, performance.now()); c.prepare(`UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?`).run(next, Date.now(), t.id); writes++; }, 1000 / rate); await new Promise((r) => setTimeout(r, seconds * 1000)); clearInterval(writer); await new Promise((r) => setTimeout(r, 1500)); const cpu = process.cpuUsage(cpu0); const wall = performance.now() - t0; lat.sort((a, b) => a - b); const pct = (p: number) => (lat.length ? lat[Math.min(lat.length - 1, Math.floor(lat.length * p))]!.toFixed(0) : "-"); console.log(`writes: ${writes} in ${seconds}s, events delivered: ${events}, hub checks: ${checks} (${(checkMs / Math.max(1, checks)).toFixed(1)} ms each, ${((checkMs / wall) * 100).toFixed(1)}% of wall time)`); console.log(`CPU: ${(((cpu.user + cpu.system) / 1000 / wall) * 100).toFixed(1)}% of one core (user ${(cpu.user / 1000).toFixed(0)} ms, system ${(cpu.system / 1000).toFixed(0)} ms)`); console.log(`write → tab latency: p50 ${pct(0.5)} ms, p95 ${pct(0.95)} ms, max ${pct(0.999)} ms (${lat.length} deliveries)`); if (perKind.size) console.log("ms per scope kind:", Object.fromEntries([...perKind].map(([k, v]) => [k, Math.round(v)]))); for (const s of socks) s.close(); ws.close(); server.close(); // Restore nothing: run it on a copy only. process.exit(0);