133 lines · 7.6 KB · TypeScriptRaw
/** * Every list, timed on the synthetic `lists` database (20,000 messages across * 300 chats, one of them 2,000 long, 5,000 photos, 3,000 people). * * node --experimental-strip-types scripts/perf/lists.ts <run dir> [--headless <cotton-headless>] [--times <n>] * * The run directory keeps the household it seeded (`<run>/household`), so a * second run over it re-times without re-seeding. The reads run on the * household's own file through `cotton-headless time` — the same list, page * and search handlers and SQL a phone's copy answers with. It writes * `<run>/lists.json`: one entry per read with its median and slowest * milliseconds, which `lists.budgets.ts` holds against the budgets below. */import { spawnSync } from 'node:child_process';import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..');/** * The owner's rule (15 Oct 2026): "we're on the local database, everything * should load instantly; users need to feel it." Each read a list or a page * waits on before its first frame, in milliseconds on a joined copy. The * screen budget is 100 ms to the first frame with real rows; the read is held * to a fifth of it, so drawing has the rest. */export const BUDGET = { /** A list's first page (`records.list`, page 0). */ listMs: 20, /** A chat's newest page, the 2,000-message one included. */ threadMs: 20, /** One keystroke of search, in a list or across everything. */ keystrokeMs: 50,} as const;/** One read the app makes, as `cotton-headless time` takes it. */export interface Call { name: string; method: string; args: Record<string, unknown> }export interface Timed { name: string; median_ms: number; max_ms: number; rows: number | null; total: unknown; ids?: string[]; error?: string }const today = () => new Date().toISOString().slice(0, 10);/** Tables left out of a run (`LISTS_SKIP=everything,record_version`): one that does not answer in minutes is named, not waited on. */const skipped = () => (process.env.LISTS_SKIP ?? '').split(',').filter(Boolean);/** Every table the kit carries — the tables the personal kit's tools name (`kits/personal/tools/<tool>/manifest.json`) and the shell's `kits/shell/tables` — by id. */export function kitTables(root = ROOT): string[] { const kits = join(root, 'crates/cotton-core/kits'); const tools = join(kits, 'personal/tools'); const named = readdirSync(tools) .filter(dir => existsSync(join(tools, dir, 'manifest.json'))) .flatMap(dir => (JSON.parse(readFileSync(join(tools, dir, 'manifest.json'), 'utf8')) as { tables?: string[] }).tables ?? []); const shell = readdirSync(join(kits, 'shell/tables')).filter(f => f.endsWith('.json')).map(f => f.replace(/\.json$/, '')); return [...new Set([...named, ...shell])].sort();}/** Every table the kit ships, as the app's list opens it. */export function listCalls(root = ROOT): Call[] { const tables = kitTables(root); return tables.filter(table => !skipped().includes(table)).map(table => ({ name: `list ${table}`, method: 'records.list', args: { table, page: 0, limit: 50, today: today() }, }));}/** A search typed one letter at a time, as the field sends each. */export function keystrokes(name: string, word: string, args: (typed: string) => Record<string, unknown>, method = 'records.list'): Call[] { return [...word].map((_, i) => word.slice(0, i + 1)).map(typed => ({ name: `${name} "${typed}"`, method, args: args(typed) }));}function run(program: string, args: string[], timeout = 600_000): string { const out = spawnSync(program, args, { encoding: 'utf8', timeout, maxBuffer: 64 << 20 }); if (out.status !== 0) throw new Error(`${program} ${args[0]}: ${out.stderr || out.stdout || out.error}`); return out.stdout;}/** Each read's line lands in `<run>/time.out` as it is timed, so a slow one shows which it is. */function time(headless: string, household: string, calls: Call[], times: number): Timed[] { const out = join(dirname(household), 'time.out'); const written = openSync(out, 'w'); const ran = spawnSync(headless, ['time', '--calls', JSON.stringify(calls), '--times', String(times), '--data-dir', household], { stdio: ['ignore', written, written], timeout: 3_600_000 }); closeSync(written); const lines = readFileSync(out, 'utf8').split('\n'); if (ran.status !== 0) throw new Error(`cotton-headless time: ${lines.filter(Boolean).at(-1) ?? ran.error}`); return lines.filter(line => line.startsWith('{')).map(line => JSON.parse(line) as Timed);}async function main(): Promise<void> { const argv = process.argv.slice(2); const runDir = resolve(argv[0] ?? ''); if (!argv[0]) throw new Error('usage: lists.ts <run dir> [--headless <path>] [--times <n>]'); const flag = (name: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; }; const headless = flag('--headless') ?? process.env.COTTON_HEADLESS ?? 'cotton-headless'; const times = Number(flag('--times') ?? 20); const household = join(runDir, 'household'); const log = join(runDir, 'lists.log'); mkdirSync(runDir, { recursive: true }); if (!existsSync(join(household, 'registry.db'))) { console.log('seeding the lists database…'); appendFileSync(log, run(headless, ['seed', '--data-dir', household, '--size', 'lists', '--seed', '7', '--name', 'perf-lists-household'], 3_600_000)); } // The chats, newest first, as the Messages list reads them; the longest // is the one `Plan::lists` gave 2,000 messages. const [chats] = time(headless, household, [{ name: 'chats', method: 'records.list', args: { table: 'thread', page: 0, limit: 500, today: today() } }], 1); const longest = longestThread(headless, household, chats?.ids ?? []); const calls: Call[] = [ ...listCalls(), { name: 'thread longest, newest page', method: 'records.list', args: { table: 'message', page: 0, limit: 50, where: { thread_id: longest }, today: today() } }, { name: 'thread longest, the chat', method: 'records.get', args: { table: 'thread', id: longest } }, ...keystrokes('search messages list', 'annie', typed => ({ table: 'thread', page: 0, limit: 50, query: typed, today: today() })), ...keystrokes('search people list', 'annie', typed => ({ table: 'person', page: 0, limit: 50, query: typed, today: today() })), ...keystrokes('search everything', 'annie', typed => ({ query: typed }), 'read.find'), ]; const timed = time(headless, household, calls, times); writeFileSync(join(runDir, 'lists.json'), `${JSON.stringify({ at: new Date().toISOString(), longest, budget: BUDGET, timed }, null, 2)}\n`); for (const t of timed.filter(t => t.error)) console.log(` refused ${t.name}: ${t.error}`); for (const t of timed.filter(t => !t.error).sort((a, b) => b.median_ms - a.median_ms)) { console.log(`${t.median_ms.toFixed(1).padStart(8)} ms max ${t.max_ms.toFixed(1).padStart(7)} ${String(t.rows ?? '-').padStart(4)} rows ${t.name}`); }}/** The chat with the most messages, by each chat's message count. */function longestThread(headless: string, household: string, ids: string[]): string { const counts = time(headless, household, ids.map(id => ({ name: id, method: 'records.list', args: { table: 'message', page: 0, limit: 1, where: { thread_id: id }, today: today() }, })), 1); const best = counts.reduce((a, b) => (Number(b.total ?? 0) > Number(a.total ?? 0) ? b : a)); return best.name;}if (process.argv[1] === fileURLToPath(import.meta.url)) { main().catch(error => { console.error(error instanceof Error ? error.message : error); process.exit(1); });}