From b4252cfe60bac2967ff2f53f1f0fa707b66e174d Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 20 Nov 2026 21:27:28 +0500 Subject: [PATCH] =?UTF-8?q?PEP-225:=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=2050?= =?UTF-8?q?=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4=D0=BE=D0=BA,=20=D0=BA=D1=8D?= =?UTF-8?q?=D1=88=20=D0=BF=D1=83=D1=82=D0=B8=20tasks.md=20=D0=B2=20=D1=85?= =?UTF-8?q?=D0=B0=D0=B1=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/scripts/bench-live.ts | 116 +++++++++++++++++++++++++++++++++ packages/runner/src/live.ts | 16 ++++- 2 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 apps/web/scripts/bench-live.ts diff --git a/apps/web/scripts/bench-live.ts b/apps/web/scripts/bench-live.ts new file mode 100644 index 00000000..b439e891 --- /dev/null +++ b/apps/web/scripts/bench-live.ts @@ -0,0 +1,116 @@ +// 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); diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts index 2869c435..c52158a7 100644 --- a/packages/runner/src/live.ts +++ b/packages/runner/src/live.ts @@ -121,6 +121,19 @@ const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' type Parts = Record; const str = (row: Record | undefined): Parts => Object.fromEntries(Object.entries(row ?? {}).map(([k, v]) => [k, String(v ?? "")])); +/** tasks.md of a change, found once a minute: the archive listing is the slow part of a story's check (PEP-225 bench). */ +const mdPaths = new Map(); +function tasksMdPath(ws: string, change: string): string | null { + const key = `${ws}|${change}`; + const hit = mdPaths.get(key); + if (hit && Date.now() - hit.at < 60_000 && (!hit.file || existsSync(hit.file))) return hit.file; + const found = findChangeDir(ws, change); + const file = found ? join(found.dir, "tasks.md") : null; + if (mdPaths.size > 2000) mdPaths.clear(); + mdPaths.set(key, { file, at: Date.now() }); + return file; +} + /** * One SQL per scope, split into named parts; frequent fields (last_activity_at, steps, * heartbeats) are left out. Part `t` is covered by the task rows sent along (see taskRows). @@ -148,8 +161,7 @@ function fingerprint(db: Db, scope: LiveScope, userId: number): Parts { // tasks.md of the working copy changes without a database write (agent ticks items). let tasksMtime = 0; if (row.ws && row.ch) { - const found = findChangeDir(String(row.ws), String(row.ch)); - const file = found && join(found.dir, "tasks.md"); + const file = tasksMdPath(String(row.ws), String(row.ch)); if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs; } const { ws: _ws, ch: _ch, ...rest } = row;