diff --git a/bench/sqlite/.gitignore b/bench/sqlite/.gitignore new file mode 100644 index 00000000..2be94185 --- /dev/null +++ b/bench/sqlite/.gitignore @@ -0,0 +1,2 @@ +node_modules +results/ diff --git a/bench/sqlite/README.md b/bench/sqlite/README.md new file mode 100644 index 00000000..ac8249e3 --- /dev/null +++ b/bench/sqlite/README.md @@ -0,0 +1,64 @@ +# PEP-36: замер SQLite vs Postgres под нагрузкой Пеппы + +Не часть продукта: отдельный `package.json` вне pnpm-воркспейса, свои зависимости. +Результаты — `RESULTS.md`, выводы — `openspec/changes/pep-36-lightweight-stack/design.md`. +Решение PM: Node 26 + `node:sqlite` (Bun замерен для сравнения). Прототип драйвера drizzle +на `node:sqlite` — `schema-port/node-sqlite-driver.ts`, проверки — `node schema-port/drizzle-check.ts`. + +```bash +cd bench/sqlite +pnpm install --ignore-workspace # better-sqlite3 под Node 26 собирается из исходников (node-gyp) +# один прогон +node run.ts --backend bun --runners 10 --load 1 --duration 90 --notify poll:1000 +# вся матрица (~35 мин); Postgres — только одноразовая БД peppa_bench +BENCH_PG_URL=postgres://peppa:…@127.0.0.1:5433/peppa_bench ./matrix.sh +``` + +`results/<прогон>/summary.json` — перцентили по каждой операции (в git не кладутся). + +## Модель нагрузки + +Частоты сняты с боевой БД `peppa` (только чтение, 2026-11-13): за сутки 107 событий, +медианный промежуток между событиями одной сессии 16 с, пик 6 событий в минуту на сессию. +Хуки Claude у Пеппы срабатывают на prompt / notification / stop / permission, не на каждый +вызов инструмента. Модель с запасом: + +| Процесс | Что делает | Частота (×1) | +|---|---|---| +| хук (`peppa-hook`) | **новый процесс на каждое событие**: открыть БД, прочитать сессию, транзакция «update sessions + insert events» | экспоненциально, в среднем раз в 10 с на раннер | +| хук-вопрос | 10 % хуков: insert questions + update sessions + insert events, затем опрос ответа раз в 1,5 с (как PermissionRequest) и снятие `awaiting_hook` | — | +| MCP (`peppa-mcp`) | долгоживущий на раннер: `report_progress` (insert events + update tasks), `get_task` (2 чтения) | 30 с / 15 с | +| бот | outbox раз в 1 с, reconcile раз в 2 с, ответ «PM» через 2–8 с (insert telegram_updates → update questions), heartbeat 30 с; потребитель событий | — | +| веб | 3 открытые доски, 4 запроса раз в 5 с; потребитель событий | — | +| вачдог | tick раз в 30 с: список сессий, 10 % — stalled (update + insert), heartbeat | — | + +`--load 10` умножает частоты хуков и MCP в 10 раз (стресс). `--runners` — 10 или 20. + +## Варианты (`--backend`) + +- `bun` — `bun:sqlite`, каждый процесс открывает файл сам; WAL, `busy_timeout=5000`, + `synchronous=NORMAL`, транзакции записи `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`. +- `node` — то же на `node:sqlite` (Node 26). +- `better` — то же на `better-sqlite3` 13 (Node). +- `writer` — один процесс-писатель (Bun) владеет записью, остальные шлют транзакции по + HTTP через unix-сокет; чтения идут прямо в файл (читатели WAL не блокируются). +- `pg` — текущий стек: Postgres 17 (docker), postgres.js, Node; хук открывает соединение. + +## Доставка событий (`--notify`) + +Потребитель (бот, веб) будится и читает `events where id > cursor`. Задержка — от момента +перед записью события до момента, когда потребитель его прочитал. + +- `pg` — LISTEN/NOTIFY (как сейчас в боте) +- `poll:N` — опрос с курсором каждые N мс +- `fswatch` — `fs.watch` на `-wal` файле (+ страховочный опрос раз в 5 с) +- `push` — писатель (или маленький хаб) рассылает id новых событий подписчикам по unix-сокету + +## Найденные ловушки + +- `PRAGMA busy_timeout` должен идти **первым** после открытия. Если раньше выполнить хоть + что-то (даже `journal_mode`), при одновременном открытии файла многими процессами + прилетает `SQLITE_BUSY_RECOVERY` сразу, без ожидания. `journal_mode=WAL` постоянный — + ставится один раз при создании файла. +- Путь unix-сокета на macOS ограничен 104 байтами — сокеты держать в коротком каталоге. +- На Bun `fetch(..., { unix })` заметно быстрее `node:http` для одноразовых процессов. diff --git a/bench/sqlite/RESULTS.md b/bench/sqlite/RESULTS.md new file mode 100644 index 00000000..c12b7993 --- /dev/null +++ b/bench/sqlite/RESULTS.md @@ -0,0 +1,79 @@ +# PEP-36: результаты замера (2026-11-13, Mac Пеппы, Bun 1.4.4, Node 26.8.1, Postgres 17.11) + +Сгенерировано `node report.ts` после `./matrix.sh`; потолок — `contention.ts`. + +## Записи и доставка + +| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 35.77 / 38.68 | 31.94 | 459 / 974 / 993 (poll:1000) | +| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 98.08 / 9112 | 96.21 | 421 / 906 / 950 (poll:1000) | +| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 103 / 6117 | 97.01 | 556 / 981 / 987 (poll:1000) | +| 10 | ×1 | один писатель (Bun) | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 31.10 / 6036 | 22.56 | 0.97 / 3.20 / 1547 (push) | +| 10 | ×1 | Postgres (Node) | 177 | 9.60 | 18.11 | 36.05 | 38.15 | 0 | 0 | 132 / 6156 | 92.00 | 13.32 / 23.25 / 39.90 (pg) | +| 10 | ×10 | bun:sqlite | 728 | 0.24 | 0.78 | 1.22 | 5.96 | 0 | 0 | 30.37 / 7535 | 24.86 | 478 / 937 / 992 (poll:1000) | +| 10 | ×10 | node:sqlite | 696 | 0.14 | 0.38 | 0.94 | 1.76 | 0 | 0 | 77.71 / 7573 | 74.67 | 519 / 960 / 996 (poll:1000) | +| 10 | ×10 | better-sqlite3 | 698 | 0.17 | 0.49 | 1.41 | 2.51 | 0 | 0 | 81.82 / 6091 | 73.97 | 508 / 951 / 987 (poll:1000) | +| 10 | ×10 | один писатель (Bun) | 719 | 1.16 | 2.12 | 2.60 | 6.55 | 0 | 0 | 30.22 / 7530 | 23.42 | 0.81 / 2.05 / 3.50 (push) | +| 10 | ×10 | Postgres (Node) | 691 | 8.03 | 12.61 | 16.25 | 24.60 | 0 | 0 | 114 / 7628 | 74.03 | 11.21 / 16.51 / 19.12 (pg) | +| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 33.67 / 6035 | 28.45 | 454 / 925 / 991 (poll:1000) | +| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 73.96 / 7562 | 71.88 | 553 / 982 / 1013 (poll:1000) | +| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 96.47 / 9084 | 87.91 | 497 / 944 / 985 (poll:1000) | +| 20 | ×1 | один писатель (Bun) | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 31.33 / 6050 | 25.39 | 1.11 / 2.94 / 5.29 (push) | +| 20 | ×1 | Postgres (Node) | 306 | 8.06 | 17.16 | 29.14 | 36.39 | 0 | 0 | 121 / 7621 | 85.12 | 11.42 / 20.32 / 32.03 (pg) | +| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 23.34 / 6035 | 19.45 | 503 / 945 / 991 (poll:1000) | +| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 70.15 / 6074 | 68.68 | 480 / 941 / 993 (poll:1000) | +| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 75.04 / 6085 | 68.83 | 509 / 946 / 993 (poll:1000) | +| 20 | ×10 | один писатель (Bun) | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 24.81 / 6033 | 19.62 | 0.71 / 1.30 / 2.35 (push) | +| 20 | ×10 | Postgres (Node) | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | 0 | 0 | 102 / 6120 | 67.98 | 9.76 / 15.06 / 17.73 (pg) | +| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 18.78 / 6029 | 15.53 | 515 / 949 / 994 (poll:1000) | +| 20 | ×50 | один писатель (Bun) | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 19.89 / 6032 | 15.64 | 0.39 / 0.85 / 1.48 (push) | +| 20 | ×50 | Postgres (Node) | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | 0 | 0 | 96.66 / 6116 | 68.14 | 6.17 / 11.37 / 14.30 (pg) | + +## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10) + +| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 | +|---|---|---|---|---|---|---| +| fswatch | 26.29 | 192 | 300 | 508 | 26.29 | 193 | +| poll:1000 | 503 | 945 | 991 | 1002 | 509 | 947 | +| poll:200 | 100 | 192 | 200 | 204 | 103 | 192 | +| push | 0.80 | 1.42 | 2.48 | 46.85 | 0.83 | 1.47 | +| Postgres LISTEN/NOTIFY (для сравнения) | 9.76 | 15.06 | 17.73 | 28.17 | 9.72 | 14.71 | + +## Самые медленные операции записи (p99, мс) при 20 раннерах ×10 + +| операция | bun:sqlite | node:sqlite | better-sqlite3 | один писатель (Bun) | Postgres (Node) | +|---|---|---|---|---|---| +| bot.answer | 0.50 | 0.49 | 0.14 | 5.32 | 9.32 | +| bot.enqueue | 5.15 | 1.32 | 0.13 | 0.93 | 9.33 | +| bot.heartbeat | 2.93 | 0.15 | 0.71 | 7.01 | 43.83 | +| bot.sent | 0.18 | 0.91 | 0.08 | 1.10 | 10.21 | +| bot.update | 0.45 | 0.48 | 0.52 | 1.56 | 9.55 | +| hook.answered | 6.17 | 2.29 | 7.86 | 4.07 | 30.26 | +| hook.event | 0.64 | 0.30 | 1.47 | 2.47 | 14.20 | +| hook.question | 5.43 | 0.33 | 1.06 | 2.40 | 14.27 | +| mcp.progress | 1.71 | 0.81 | 0.60 | 2.75 | 19.55 | +| wd.heartbeat | 0.15 | 0.07 | 0.06 | 0.92 | 5.60 | +| wd.stalled | 5.48 | 0.66 | 0.20 | 8.42 | 17.87 | + +## Потолок (contention.ts, 10 с, без пауз) + +``` +{"backend":"bun","procs":20,"seconds":10,"txPerSec":33537,"p50":"0.02","p95":"0.08","p99":"4.24","max":"2710.8","busyRetries":0,"errors":0} +{"backend":"bun","procs":40,"seconds":10,"txPerSec":27223,"p50":"0.03","p95":"0.31","p99":"21.96","max":"2930.6","busyRetries":0,"errors":0} +{"backend":"node","procs":20,"seconds":10,"txPerSec":48578,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5405.9","busyRetries":1,"errors":0} +{"backend":"node","procs":40,"seconds":10,"txPerSec":47694,"p50":"0.02","p95":"0.03","p99":"0.06","max":"6413.2","busyRetries":3,"errors":0} +{"backend":"better","procs":20,"seconds":10,"txPerSec":47456,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5359.5","busyRetries":1,"errors":0} +{"backend":"better","procs":40,"seconds":10,"txPerSec":45076,"p50":"0.02","p95":"0.03","p99":"0.06","max":"5937.5","busyRetries":2,"errors":0} +{"backend":"pg","procs":20,"seconds":10,"txPerSec":4890,"p50":"3.88","p95":"6.82","p99":"9.01","max":"97.1","busyRetries":0,"errors":0} +{"backend":"pg","procs":40,"seconds":10,"txPerSec":7555,"p50":"5.47","p95":"6.95","p99":"8.33","max":"210.2","busyRetries":0,"errors":0} +``` + +## drizzle на node:sqlite и bun:sqlite (`schema-port/drizzle-check.ts`) + +Транзакция хука (update sessions + insert events) через drizzle, 20 000 подряд в одном процессе: + +| драйвер | мкс на транзакцию | +|---|---| +| node:sqlite (Node 26.8, прослойка `node-sqlite-driver.ts`) | 53.0 | +| bun:sqlite (Bun 1.4.4, `drizzle-orm/bun-sqlite`) | 62.9 | diff --git a/bench/sqlite/contention.ts b/bench/sqlite/contention.ts new file mode 100644 index 00000000..9b4129a3 --- /dev/null +++ b/bench/sqlite/contention.ts @@ -0,0 +1,76 @@ +// Ceiling test: P processes write hook-like transactions back to back, no pauses. +// Far beyond Peppa's real load; shows where each backend starts to bend. +// node contention.ts --backend bun --procs 20 --seconds 10 +import { spawn } from "node:child_process"; +import { homedir } from "node:os"; +import { parseArgs } from "node:util"; +import { openDb, openPg, openSqlite, type Backend } from "./lib/db.ts"; +import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts"; + +const { values: a } = parseArgs({ options: { backend: { type: "string", default: "bun" }, procs: { type: "string", default: "20" }, seconds: { type: "string", default: "10" }, worker: { type: "boolean" } } }); +const backend = a.backend as Backend; +const now = () => performance.timeOrigin + performance.now(); + +if (a.worker) { + const db = await openDb(backend); + const sid = Number(process.env.BENCH_SESSION); + const end = Number(process.env.BENCH_END); + const ms: number[] = []; + let busy = 0; + let errors = 0; + while (Date.now() < end) { + const t = now(); + try { + await db.tx([ + ["update sessions set status = 'running', last_activity_at = ? where id = ?", [Date.now(), sid]], + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: t }), Date.now()]], + ]); + } catch { + errors++; + } + busy += db.lastBusy; + ms.push(now() - t); + } + await db.close(); + // A file, not stdout: process.exit() can cut a large pipe write short. + (await import("node:fs")).writeFileSync(`${process.env.BENCH_DB}.${sid}.json`, JSON.stringify({ ms, busy, errors })); + process.exit(0); +} + +const procs = Number(a.procs); +const runtime = backend === "pg" || backend === "node" || backend === "better" ? process.execPath : `${homedir()}/.bun/bin/bun`; +const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-contention-${process.pid}`; +const env = { ...process.env, BENCH_BACKEND: backend, BENCH_DB: `${work}.db` } as Record; +if (backend === "pg") { + if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL ?? "")) throw new Error("BENCH_PG_URL must point at 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(procs)); + 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(procs)); + await db.close(); +} +const end = Date.now() + 1000 + Number(a.seconds) * 1000; +const results = await Promise.all( + Array.from({ length: procs }, (_, i) => + new Promise<{ ms: number[]; busy: number; errors: number }>((resolve) => { + const p = spawn(runtime, [new URL(import.meta.url).pathname, "--worker", "--backend", backend], { env: { ...env, BENCH_SESSION: String(i + 1), BENCH_END: String(end) }, stdio: ["ignore", "inherit", "inherit"] }); + p.on("exit", async () => { + const fs = await import("node:fs"); + const f = `${env.BENCH_DB}.${i + 1}.json`; + resolve(fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, "utf8")) : { ms: [], busy: 0, errors: 1 }); + fs.rmSync(f, { force: true }); + }); + }), + ), +); +const ms = results.flatMap((r) => r.ms).sort((x, y) => x - y); +const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor((p / 100) * ms.length))].toFixed(2); +console.log(JSON.stringify({ backend, procs, seconds: Number(a.seconds), txPerSec: Math.round(ms.length / Number(a.seconds)), p50: pct(50), p95: pct(95), p99: pct(99), max: ms.at(-1)!.toFixed(1), busyRetries: results.reduce((s, r) => s + r.busy, 0), errors: results.reduce((s, r) => s + r.errors, 0) })); +for (const s of ["", "-wal", "-shm"]) (await import("node:fs")).rmSync(env.BENCH_DB + s, { force: true }); diff --git a/bench/sqlite/lib/db.ts b/bench/sqlite/lib/db.ts new file mode 100644 index 00000000..b731a46b --- /dev/null +++ b/bench/sqlite/lib/db.ts @@ -0,0 +1,172 @@ +// Uniform async DB access for the benchmark: bun:sqlite, node:sqlite, better-sqlite3, +// Postgres (postgres.js) and a "writer" client that sends writes to one writer process. +// SQL is written in SQLite dialect with `?` params; the Postgres adapter renumbers them. +import { request } from "node:http"; + +export type Stmt = [sql: string, params?: unknown[]]; +export type Row = Record; + +export interface Db { + all(sql: string, params?: unknown[]): Promise; + /** Runs statements in one write transaction; returns each statement's rows. */ + tx(stmts: Stmt[]): Promise; + /** SQLITE_BUSY retries made by the last tx (0 for Postgres/writer). */ + lastBusy: number; + close(): Promise; + /** Postgres only: raw client for LISTEN/NOTIFY. */ + pg?: any; +} + +export type Backend = "bun" | "node" | "better" | "pg" | "writer"; + +export const BUSY_TIMEOUT_MS = Number(process.env.BENCH_BUSY_TIMEOUT_MS ?? 5000); + +// busy_timeout must come first: with 20 hook processes opening the file at once, any +// statement before it (even journal_mode) can fail at once with SQLITE_BUSY_RECOVERY. +// journal_mode=WAL is persistent, so it is set once when the file is created (run.ts). +const PRAGMAS = [ + `PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`, + "PRAGMA synchronous = NORMAL", + "PRAGMA foreign_keys = ON", +]; + +function isBusy(e: unknown) { + const s = String((e as any)?.code ?? "") + " " + String((e as any)?.message ?? e); + return /SQLITE_BUSY|database is locked/i.test(s); +} + +/** Wraps a synchronous SQLite driver: BEGIN IMMEDIATE + retry on SQLITE_BUSY. */ +function syncSqlite(exec: (sql: string) => void, all: (sql: string, p: unknown[]) => Row[], close: () => void): Db { + const db: Db = { + lastBusy: 0, + async all(sql, params = []) { + return all(sql, params); + }, + async tx(stmts) { + db.lastBusy = 0; + for (;;) { + try { + exec("BEGIN IMMEDIATE"); + try { + const out = stmts.map(([s, p]) => all(s, p ?? [])); + exec("COMMIT"); + return out; + } catch (e) { + try { exec("ROLLBACK"); } catch {} + throw e; + } + } catch (e) { + // busy_timeout already waited BUSY_TIMEOUT_MS; count it and give up after 3. + if (!isBusy(e) || ++db.lastBusy >= 3) throw e; + } + } + }, + async close() { + close(); + }, + }; + return db; +} + +export async function openSqlite(kind: "bun" | "node" | "better", path: string, readonly = false): Promise { + if (kind === "bun") { + const { Database } = await import("bun:sqlite" as string); + const d = new Database(path, readonly ? { readonly: true } : { create: true }); + for (const p of PRAGMAS) d.exec(p); + return syncSqlite((s) => d.exec(s), (s, p) => d.query(s).all(...p), () => d.close()); + } + if (kind === "node") { + const { DatabaseSync } = await import("node:sqlite"); + const d = new DatabaseSync(path, { readOnly: readonly }); + for (const p of PRAGMAS) d.exec(p); + const cache = new Map(); + const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); + return syncSqlite((s) => d.exec(s), (s, p) => prep(s).all(...(p as any[])) as Row[], () => d.close()); + } + const { default: Better } = await import("better-sqlite3"); + const d = new Better(path, { readonly }); + for (const p of PRAGMAS) d.exec(p); + const cache = new Map(); + const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); + return syncSqlite( + (s) => d.exec(s), + (s, p) => { + const st = prep(s); + return st.reader ? st.all(...p) : (st.run(...p), []); + }, + () => d.close(), + ); +} + +const toPg = (s: string) => { + let i = 0; + return s.replace(/\?/g, () => `$${++i}`); +}; + +export async function openPg(url: string, max = 1): Promise { + const { default: postgres } = await import("postgres"); + const sql = postgres(url, { max, onnotice: () => {} }); + return { + lastBusy: 0, + pg: sql, + async all(s, p = []) { + return (await sql.unsafe(toPg(s), p as any[])) as unknown as Row[]; + }, + async tx(stmts) { + return (await sql.begin(async (t: any) => { + const out: Row[][] = []; + for (const [s, p] of stmts) out.push(await t.unsafe(toPg(s), p ?? [])); + return out; + })) as Row[][]; + }, + async close() { + await sql.end({ timeout: 1 }); + }, + }; +} + +export async function httpUnix(socketPath: string, path: string, body: unknown): Promise { + // Bun's fetch speaks unix sockets natively and starts much faster than node:http there. + if (typeof (globalThis as any).Bun !== "undefined") { + const r = await fetch(`http://writer${path}`, { method: "POST", body: JSON.stringify(body), unix: socketPath } as RequestInit); + const j = await r.json(); + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j; + } + return new Promise((resolve, reject) => { + const data = JSON.stringify(body); + const req = request( + { socketPath, path, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data) } }, + (res) => { + let buf = ""; + res.setEncoding("utf8"); + res.on("data", (c) => (buf += c)); + res.on("end", () => { + const j = buf ? JSON.parse(buf) : null; + res.statusCode === 200 ? resolve(j) : reject(new Error(j?.error ?? `HTTP ${res.statusCode}`)); + }); + }, + ); + req.on("error", reject); + req.end(data); + }); +} + +/** Writes go to the writer process over a unix socket; reads go straight to the file (WAL readers never block). */ +export async function openWriterClient(socketPath: string, dbPath: string, readKind: "bun" | "node"): Promise { + const reader = await openSqlite(readKind, dbPath, true); + return { + lastBusy: 0, + all: (s, p) => reader.all(s, p), + async tx(stmts) { + return (await httpUnix(socketPath, "/tx", { stmts })).rows; + }, + close: () => reader.close(), + }; +} + +export async function openDb(backend: Backend, env = process.env): Promise { + if (backend === "pg") return openPg(env.BENCH_PG_URL!); + if (backend === "writer") return openWriterClient(env.BENCH_WRITER_SOCK!, env.BENCH_DB!, (env.BENCH_READ_KIND as any) ?? "bun"); + return openSqlite(backend, env.BENCH_DB!); +} diff --git a/bench/sqlite/lib/notify.ts b/bench/sqlite/lib/notify.ts new file mode 100644 index 00000000..13fafb66 --- /dev/null +++ b/bench/sqlite/lib/notify.ts @@ -0,0 +1,49 @@ +// Replacements for Postgres LISTEN/NOTIFY, all measured the same way: the consumer is +// woken up somehow, then reads new events after its cursor from the database. +// pg — LISTEN/NOTIFY (today's Peppa) +// poll:N — select events where id > cursor every N ms +// fswatch — fs.watch on the -wal file (+5 s safety poll) +// push — the writer (or a tiny hub) pushes event ids over a unix socket +import { watch } from "node:fs"; +import { request } from "node:http"; +import type { Db } from "./db.ts"; +import { httpUnix } from "./db.ts"; + +export const CHANNEL = "peppa_events"; + +/** Called by event producers after commit. */ +export async function publish(db: Db, mode: string, eventId: number, env = process.env) { + if (mode === "pg") await db.pg.unsafe(`select pg_notify('${CHANNEL}', $1)`, [JSON.stringify({ type: "progress", eventId })]); + else if (mode === "push" && env.BENCH_BACKEND !== "writer") await httpUnix(env.BENCH_HUB_SOCK!, "/publish", { ids: [eventId] }).catch(() => {}); + // writer backend publishes itself after commit; poll/fswatch need nothing. +} + +/** Subscribes `wake` to new events; returns a stop function. */ +export function subscribe(db: Db, mode: string, wake: () => void, env = process.env): () => void { + if (mode === "pg") { + let l: any; + db.pg.listen(CHANNEL, () => wake()).then((x: any) => (l = x)); + return () => l?.unlisten(); + } + if (mode.startsWith("poll:")) { + const t = setInterval(wake, Number(mode.slice(5))); + return () => clearInterval(t); + } + if (mode === "fswatch") { + const w = watch(env.BENCH_DB! + "-wal", () => wake()); + const t = setInterval(wake, 5000); + return () => (w.close(), clearInterval(t)); + } + if (mode === "push") { + const sock = env.BENCH_BACKEND === "writer" ? env.BENCH_WRITER_SOCK! : env.BENCH_HUB_SOCK!; + const req = request({ socketPath: sock, path: "/subscribe", method: "GET" }, (res) => { + res.setEncoding("utf8"); + res.on("data", () => wake()); + }); + req.on("error", () => {}); + req.end(); + const t = setInterval(wake, 5000); + return () => (req.destroy(), clearInterval(t)); + } + throw new Error(`unknown notify mode ${mode}`); +} diff --git a/bench/sqlite/lib/schema.ts b/bench/sqlite/lib/schema.ts new file mode 100644 index 00000000..a75dcac2 --- /dev/null +++ b/bench/sqlite/lib/schema.ts @@ -0,0 +1,34 @@ +// The hot part of Peppa's schema (packages/db/src/schema.ts), in both dialects. +// Timestamps are epoch milliseconds passed as params so the same SQL runs on both. + +const tables = (pg: boolean) => { + const id = pg ? "serial primary key" : "integer primary key autoincrement"; + const json = pg ? "jsonb" : "text"; + const ts = pg ? "bigint" : "integer"; + return [ + `create table projects (id ${id}, key text not null unique, name text not null, next_task_number integer not null default 1, updated_at ${ts})`, + `create table tasks (id ${id}, project_id integer not null references projects(id) on delete cascade, number integer not null, title text not null, status text not null default 'backlog', updated_at ${ts}, unique(project_id, number))`, + `create table sessions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete set null, tmux_name text not null unique, generation integer not null default 0, auto_nudges integer not null default 0, status text not null default 'starting', last_activity_at ${ts}, started_at ${ts})`, + `create table questions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, kind text not null, text text not null, options ${json}, answer text, answered_via text, telegram_message_id integer, awaiting_hook boolean not null default false, created_at ${ts}, answered_at ${ts})`, + `create table events (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, type text not null, payload ${json}, created_at ${ts})`, + `create index events_task on events(task_id, id)`, + `create table settings (key text primary key, value ${json} not null, updated_at ${ts})`, + `create table telegram_outbox (id ${id}, dedupe_key text not null unique, method text not null, params ${json} not null, question_id integer references questions(id) on delete set null, status text not null default 'pending', attempts integer not null default 0, next_attempt_at ${ts} not null, telegram_message_id integer, created_at ${ts}, sent_at ${ts})`, + `create index outbox_pending on telegram_outbox(status, next_attempt_at)`, + `create table telegram_updates (update_id integer primary key, status text not null, created_at ${ts})`, + ]; +}; + +export const sqliteSchema = tables(false); +export const pgSchema = tables(true); + +/** One project, `runners` tasks in progress, one live session per task. */ +export function seedStmts(runners: number): [string, unknown[]][] { + const now = Date.now(); + const out: [string, unknown[]][] = [["insert into projects (key, name, next_task_number, updated_at) values ('PEP', 'Peppa', ?, ?)", [runners + 1, now]]]; + for (let i = 1; i <= runners; i++) { + out.push(["insert into tasks (project_id, number, title, status, updated_at) values (1, ?, ?, 'in_progress', ?)", [i, `Task ${i}`, now]]); + out.push(["insert into sessions (project_id, task_id, tmux_name, generation, status, last_activity_at, started_at) values (1, ?, ?, 1, 'running', ?, ?)", [i, `peppa-PEP-${i}-s${i}`, now, now]]); + } + return out; +} diff --git a/bench/sqlite/matrix.sh b/bench/sqlite/matrix.sh new file mode 100755 index 00000000..efad8770 --- /dev/null +++ b/bench/sqlite/matrix.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Full PEP-36 matrix. BENCH_PG_URL must point at the throwaway peppa_bench database. +# BENCH_PG_URL=postgres://…/peppa_bench ./matrix.sh [smoke] +set -u +cd "$(dirname "$0")" +DUR1=${DUR1:-90}; DUR10=${DUR10:-60} +run() { node run.ts "$@" 2>&1 | grep -vE "^\[bench\]"; } +if [ "${1:-}" = smoke ]; then + for b in "--backend bun --notify push" "--backend writer --notify push" "--backend node --notify fswatch" "--backend pg"; do + run $b --runners 3 --load 5 --duration 12 --name smoke | grep -E "==|write ALL|deliver|rror" + done + exit +fi +# 1. Write contention: every backend at 10/20 runners, real load (x1) and x10. +for r in 10 20; do + for x in 1 10; do + d=$([ $x = 1 ] && echo $DUR1 || echo $DUR10) + run --backend bun --runners $r --load $x --duration $d --notify poll:1000 + run --backend node --runners $r --load $x --duration $d --notify poll:1000 + run --backend better --runners $r --load $x --duration $d --notify poll:1000 + run --backend writer --runners $r --load $x --duration $d --notify push + run --backend pg --runners $r --load $x --duration $d --notify pg + done +done +# 2. LISTEN/NOTIFY replacements on bun:sqlite, 20 runners x10. +for n in poll:200 poll:1000 fswatch push; do + run --backend bun --runners 20 --load 10 --duration $DUR10 --notify $n +done +# 3. Saturation: 20 runners at x50 (≈ 100 hook processes/s) — where does each one bend? +for b in "--backend bun --notify poll:1000" "--backend writer --notify push" "--backend pg --notify pg"; do + run $b --runners 20 --load 50 --duration 45 +done diff --git a/bench/sqlite/package.json b/bench/sqlite/package.json new file mode 100644 index 00000000..dd910a75 --- /dev/null +++ b/bench/sqlite/package.json @@ -0,0 +1,15 @@ +{ + "name": "peppa-bench-sqlite", + "private": true, + "type": "module", + "description": "PEP-36: SQLite vs Postgres write/notify benchmark under Peppa-like load. Not part of the product.", + "dependencies": { + "better-sqlite3": "13.1.1", + "postgres": "4.1.1" + }, + "pnpm": { + "onlyBuiltDependencies": [ + "better-sqlite3" + ] + } +} diff --git a/bench/sqlite/pnpm-lock.yaml b/bench/sqlite/pnpm-lock.yaml new file mode 100644 index 00000000..b12da76e --- /dev/null +++ b/bench/sqlite/pnpm-lock.yaml @@ -0,0 +1,40 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + better-sqlite3: + specifier: 13.1.1 + version: 13.1.1 + postgres: + specifier: 4.1.1 + version: 4.1.1 + +packages: + + better-sqlite3@13.1.1: + resolution: {integrity: sha512-JjyLCATp+VLxZVFyWkicyzKYwpEFLCrV4MmshW97xv3JXdhw5jBDcsbEWRGm2L/96E+k7rtjON8q9nml05h3Pw==} + engines: {node: '>=22'} + + node-addon-api@8.9.2: + resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==} + engines: {node: ^18 || ^20 || >= 21} + + postgres@4.1.1: + resolution: {integrity: sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug==} + engines: {node: '>=18'} + +snapshots: + + better-sqlite3@13.1.1: + dependencies: + node-addon-api: 8.9.2 + + node-addon-api@8.9.2: {} + + postgres@4.1.1: {} diff --git a/bench/sqlite/report.ts b/bench/sqlite/report.ts new file mode 100644 index 00000000..8328b37f --- /dev/null +++ b/bench/sqlite/report.ts @@ -0,0 +1,48 @@ +// Markdown tables from results/*/summary.json: `node report.ts > results/report.md`. +import { readdirSync, readFileSync, existsSync } from "node:fs"; + +const dir = new URL("results/", import.meta.url).pathname; +const runs = readdirSync(dir) + .filter((d) => existsSync(`${dir}${d}/summary.json`)) + .map((d) => JSON.parse(readFileSync(`${dir}${d}/summary.json`, "utf8"))); + +const order = ["bun", "node", "better", "writer", "pg"]; +const label: Record = { bun: "bun:sqlite", node: "node:sqlite", better: "better-sqlite3", writer: "один писатель (Bun)", pg: "Postgres (Node)" }; +const f = (v: number) => (Number.isFinite(v) ? (v >= 100 ? v.toFixed(0) : v.toFixed(2)) : "—"); +const row = (r: any, k: string) => r.rows[k] ?? { n: 0, p50: NaN, p95: NaN, p99: NaN, max: NaN, busy: 0, errors: 0 }; + +console.log("## Записи и доставка\n"); +console.log("| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 |"); +console.log("|---|---|---|---|---|---|---|---|---|---|---|---|---|"); +for (const r of runs.filter((r) => r.notify === "pg" || r.notify === "poll:1000" || (r.backend === "writer" && r.notify === "push")).sort((a, b) => a.runners - b.runners || a.load - b.load || order.indexOf(a.backend) - order.indexOf(b.backend))) { + if (r.backend === "bun" && r.notify !== "poll:1000") continue; + const w = { ...row(r, "write ALL") }; + // Runs before the fix counted hooks killed by the end-of-run SIGTERM as crashes. + if (r.errors.every((e: string) => e === "hook exited with null")) w.errors -= row(r, "write hook.crashed").errors; + const h = row(r, "total hook"); + const s = row(r, "startup hook"); + const d = row(r, "deliver bot"); + console.log(`| ${r.runners} | ×${r.load} | ${label[r.backend]} | ${w.n} | ${f(w.p50)} | ${f(w.p95)} | ${f(w.p99)} | ${f(w.max)} | ${w.busy} | ${w.errors} | ${f(h.p50)} / ${f(h.p95)} | ${f(s.p50)} | ${f(d.p50)} / ${f(d.p95)} / ${f(d.p99)} (${r.notify}) |`); +} + +console.log("\n## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10)\n"); +console.log("| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 |"); +console.log("|---|---|---|---|---|---|---|"); +for (const r of runs.filter((r) => r.backend === "bun" && r.runners === 20 && r.load === 10)) { + const b = row(r, "deliver bot"); + const w = row(r, "deliver web"); + console.log(`| ${r.notify} | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(w.p50)} | ${f(w.p95)} |`); +} +const pg = runs.find((r) => r.backend === "pg" && r.runners === 20 && r.load === 10); +if (pg) { + const b = row(pg, "deliver bot"); + console.log(`| Postgres LISTEN/NOTIFY (для сравнения) | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(row(pg, "deliver web").p50)} | ${f(row(pg, "deliver web").p95)} |`); +} + +console.log("\n## Самые медленные операции записи (p99, мс) при 20 раннерах ×10\n"); +console.log("| операция | " + order.map((b) => label[b]).join(" | ") + " |"); +console.log("|---|" + order.map(() => "---|").join("")); +const at = (b: string) => runs.find((r) => r.backend === b && r.runners === 20 && r.load === 10 && (b !== "bun" || r.notify === "poll:1000")); +const ops = new Set(); +for (const b of order) for (const k of Object.keys(at(b)?.rows ?? {})) if (k.startsWith("write ") && k !== "write ALL" && k !== "write hook.crashed") ops.add(k); +for (const k of [...ops].sort()) console.log(`| ${k.slice(6)} | ` + order.map((b) => f(at(b)?.rows[k]?.p99 ?? NaN)).join(" | ") + " |"); diff --git a/bench/sqlite/roles.ts b/bench/sqlite/roles.ts new file mode 100644 index 00000000..18dc0d67 --- /dev/null +++ b/bench/sqlite/roles.ts @@ -0,0 +1,336 @@ +// One process of the simulated Peppa: ` roles.ts `; 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((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 { + 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(); + 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((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(); + 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((r) => stops.push(r)); + server.close(); + for (const s of subs) s.end(); + await db?.close(); +} + +const roles: Record Promise> = { hook, runner, mcp, bot, web, watchdog, writer }; +roles[role]().then( + () => process.exit(0), + (e) => { + console.error(`[${role}]`, e); + flush(); + process.exit(1); + }, +); diff --git a/bench/sqlite/run.ts b/bench/sqlite/run.ts new file mode 100644 index 00000000..b63360ad --- /dev/null +++ b/bench/sqlite/run.ts @@ -0,0 +1,128 @@ +// 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//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 = { + ...(process.env as Record), + 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 = {}) => { + 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(); +for (const s of all) { + const k = `${s.kind} ${s.op}`; + groups.set(k, [...(groups.get(k) ?? []), s]); +} +const rows: Record> = {}; +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 }); diff --git a/bench/sqlite/schema-port/copy-from-pg.ts b/bench/sqlite/schema-port/copy-from-pg.ts new file mode 100644 index 00000000..60bf8a77 --- /dev/null +++ b/bench/sqlite/schema-port/copy-from-pg.ts @@ -0,0 +1,53 @@ +// PEP-36 prototype: copy a Peppa Postgres database into a fresh SQLite file using the +// ported schema, then read it back through drizzle and compare row counts. +// bun copy-from-pg.ts +// The Postgres session is read-only (default_transaction_read_only), so pointing it at +// the live database cannot change anything there. +import { Database } from "bun:sqlite"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import postgres from "postgres"; +import * as schema from "./schema.ts"; + +const [url, out] = process.argv.slice(2); +if (!url || !out) throw new Error("usage: bun copy-from-pg.ts "); + +const pg = postgres(url, { max: 1, connection: { default_transaction_read_only: "on" } as any }); +const file = new Database(out, { create: true }); +file.exec("PRAGMA busy_timeout = 5000"); +file.exec("PRAGMA journal_mode = WAL"); +const db = drizzle(file, { schema }); +migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname }); + +// Parents before children (foreign keys are enforced). +const order = [ + "users", "projects", "project_members", "project_invites", "goals", "tasks", "sessions", "questions", "events", + "settings", "telegram_outbox", "telegram_updates", "oauth_clients", "oauth_codes", "oauth_tokens", + "incident_settings", "error_sources", "incidents", +]; +const toSqlite = (v: unknown) => + v instanceof Date ? v.getTime() : typeof v === "boolean" ? (v ? 1 : 0) : v !== null && typeof v === "object" ? JSON.stringify(v) : typeof v === "bigint" ? Number(v) : v; + +file.exec("PRAGMA foreign_keys = ON"); +const t0 = performance.now(); +const counts: Record = {}; +for (const t of order) { + const rows = await pg.unsafe(`select * from ${t}`); + if (rows.length) { + const cols = Object.keys(rows[0]); + const ins = file.prepare(`insert into ${t} (${cols.map((c) => `"${c}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`); + file.transaction(() => { + for (const r of rows) ins.run(...(cols.map((c) => toSqlite(r[c])) as any[])); + })(); + } + const [{ n }] = file.query(`select count(*) n from ${t}`).all() as { n: number }[]; + counts[t] = [rows.length, n]; +} +const ms = performance.now() - t0; +await pg.end(); + +// Read back through drizzle: relations, timestamps as Date, json as objects, enums as text. +const tasks = await db.query.tasks.findMany({ with: { project: true, sessions: true }, limit: 3 }); +const q = await db.query.questions.findFirst({ where: (q, { isNotNull }) => isNotNull(q.options) }); +const fk = file.query("PRAGMA foreign_key_check").all(); +console.log(JSON.stringify({ ms: Math.round(ms), counts, mismatched: Object.entries(counts).filter(([, [a, b]]) => a !== b), fkViolations: fk.length, sample: { task: tasks[0] && { key: `${tasks[0].project.key}-${tasks[0].number}`, createdAt: tasks[0].createdAt, isDate: tasks[0].createdAt instanceof Date, sessions: tasks[0].sessions.length }, questionOptions: q?.options, optionsIsArray: Array.isArray(q?.options) } }, null, 2)); diff --git a/bench/sqlite/schema-port/drizzle-check.ts b/bench/sqlite/schema-port/drizzle-check.ts new file mode 100644 index 00000000..00ba80fb --- /dev/null +++ b/bench/sqlite/schema-port/drizzle-check.ts @@ -0,0 +1,96 @@ +// PEP-36 prototype: Peppa's ported schema through drizzle on node:sqlite (Node 26) or +// bun:sqlite (Bun) — migrations, typed round trips, transactions, and the cost of a +// hook-like write through the ORM. +// node drizzle-check.ts bun drizzle-check.ts +import { eq, sql } from "drizzle-orm"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as schema from "./schema.ts"; + +const isBun = typeof (globalThis as any).Bun !== "undefined"; +const dir = mkdtempSync(join(tmpdir(), "pep36-")); +const file = join(dir, "peppa.db"); +const migrationsFolder = new URL("migrations", import.meta.url).pathname; + +let db: any; +if (isBun) { + const { Database } = await import("bun:sqlite" as string); + const { drizzle } = await import("drizzle-orm/bun-sqlite"); + const { migrate } = await import("drizzle-orm/bun-sqlite/migrator"); + const d = new Database(file, { create: true }); + for (const p of ["PRAGMA busy_timeout = 5000", "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA foreign_keys = ON"]) d.exec(p); + db = drizzle(d, { schema }); + migrate(db, { migrationsFolder }); +} else { + const { drizzleNodeSqlite } = await import("./node-sqlite-driver.ts"); + const { migrate } = await import("drizzle-orm/better-sqlite3/migrator"); + db = drizzleNodeSqlite(file, schema); + migrate(db, { migrationsFolder }); +} +const ok = (name: string, cond: boolean, extra = "") => console.log(`${cond ? "ok " : "FAIL"} ${name}${extra ? ` — ${extra}` : ""}`); + +const [user] = db.insert(schema.users).values({ giteaId: 1, login: "mock-pm", telegramChatId: 9007199254740991 }).returning().all(); +const [project] = db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp", ownerId: user.id }).returning().all(); +ok("insert … returning", project.id === 1 && project.createdAt instanceof Date, `createdAt ${project.createdAt.toISOString()}`); +ok("bigint chat id round trip", db.select().from(schema.users).get().telegramChatId === 9007199254740991); + +// createTask as it has to look on SQLite: synchronous transaction, BEGIN IMMEDIATE. +const createTask = (title: string) => + db.transaction( + (tx: any) => { + const [p] = tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning().all(); + return tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title }).returning().get(); + }, + { behavior: "immediate" }, + ); +const t1 = createTask("Первая"); +const t2 = createTask("Вторая"); +ok("sync transaction", t1.number === 1 && t2.number === 2 && t2.status === "backlog"); + +try { + db.transaction((tx: any) => { + tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run(); + throw new Error("boom"); + }); +} catch {} +ok("rollback on throw", db.select().from(schema.projects).get().nextTaskNumber === 3); + +let asyncRefused = false; +try { + await db.transaction(async (tx: any) => { + await tx.update(schema.projects).set({ nextTaskNumber: 200 }).where(eq(schema.projects.id, 1)); + }); +} catch (e) { + asyncRefused = /synchronous/.test((e as Error).message); +} +ok("async transaction", isBun ? true : asyncRefused, isBun ? "bun-sqlite: commits after the first await (not refused) — see tx-check.ts" : "refused with a clear error"); + +const [sess] = db.insert(schema.sessions).values({ projectId: 1, taskId: t1.id, tmuxName: "peppa-P-1-s1" }).returning().all(); +db.insert(schema.questions).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, kind: "permission", text: "Удалить build?", options: ["Да", "Нет"], awaitingHook: true }).run(); +const q = db.query.questions.findFirst({ with: { session: true, task: true } }).sync(); +ok("json + boolean + relations", Array.isArray(q.options) && q.options[1] === "Нет" && q.awaitingHook === true && q.session.tmuxName === "peppa-P-1-s1" && q.task.title === "Первая"); +db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 1 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 2 } } }).run(); +db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 3 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 3 } } }).run(); +ok("upsert json", db.select().from(schema.settings).get().value.at === 3); +db.insert(schema.telegramOutbox).values({ dedupeKey: "q:1", method: "sendMessage", params: { chat_id: 42, text: "?" } }).run(); +// core/telegram.ts compares params->>'chat_id' with a string. Postgres ->> returns text; +// SQLite ->> returns the JSON number as a number, so the same SQL finds nothing. +const asText = db.select().from(schema.telegramOutbox).where(sql`${schema.telegramOutbox.params}->>'chat_id' = ${"42"}`).all(); +const asCast = db.select().from(schema.telegramOutbox).where(sql`cast(${schema.telegramOutbox.params}->>'chat_id' as text) = ${"42"}`).all(); +ok("json ->> as in core/telegram.ts differs from Postgres", asText.length === 0 && asCast.length === 1, "needs cast(… as text) on SQLite"); + +// Cost of the hook's write through the ORM (update session + insert event), one process. +const n = 20000; +const t0 = performance.now(); +for (let i = 0; i < n; i++) + db.transaction( + (tx: any) => { + tx.update(schema.sessions).set({ status: "running", lastActivityAt: new Date() }).where(eq(schema.sessions.id, sess.id)).run(); + tx.insert(schema.events).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, type: "turn_end", payload: { i } }).run(); + }, + { behavior: "immediate" }, + ); +const us = ((performance.now() - t0) / n) * 1000; +console.log(`${isBun ? "bun:sqlite" : "node:sqlite"} via drizzle: ${us.toFixed(1)} µs per hook transaction (${n} in one process)`); +rmSync(dir, { recursive: true, force: true }); diff --git a/bench/sqlite/schema-port/drizzle.config.ts b/bench/sqlite/schema-port/drizzle.config.ts new file mode 100644 index 00000000..308c2681 --- /dev/null +++ b/bench/sqlite/schema-port/drizzle.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "drizzle-kit"; +export default defineConfig({ dialect: "sqlite", schema: "./schema.ts", out: "./migrations" }); diff --git a/bench/sqlite/schema-port/migrations/0000_baseline.sql b/bench/sqlite/schema-port/migrations/0000_baseline.sql new file mode 100644 index 00000000..ab29ddb1 --- /dev/null +++ b/bench/sqlite/schema-port/migrations/0000_baseline.sql @@ -0,0 +1,271 @@ +CREATE TABLE `error_sources` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `kind` text NOT NULL, + `bugsink_project_id` integer NOT NULL, + `dsn` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_bugsink_project_id_unique` ON `error_sources` (`bugsink_project_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_project_kind` ON `error_sources` (`project_id`,`kind`);--> statement-breakpoint +CREATE TABLE `events` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `type` text NOT NULL, + `payload` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `goals` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'open' NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `incident_settings` ( + `project_id` integer PRIMARY KEY NOT NULL, + `hook_secret` text NOT NULL, + `policy` text DEFAULT 'backlog' NOT NULL, + `triage_prompt` text, + `environments` text DEFAULT '["prod","production"]' NOT NULL, + `daily_limit` integer DEFAULT 5 NOT NULL, + `ignore_pattern` text, + `goal_id` integer, + `webhook_auto` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incident_settings_hook_secret_unique` ON `incident_settings` (`hook_secret`);--> statement-breakpoint +CREATE TABLE `incidents` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `source` text NOT NULL, + `bugsink_issue_id` text NOT NULL, + `friendly_id` text, + `title` text NOT NULL, + `culprit` text, + `level` text, + `environment` text, + `first_release` text, + `last_release` text, + `events` integer DEFAULT 1 NOT NULL, + `first_seen` integer NOT NULL, + `last_seen` integer NOT NULL, + `url` text, + `stack` text, + `status` text DEFAULT 'new' NOT NULL, + `decision` text, + `decided_by` text, + `decision_reason` text, + `task_id` integer, + `task_created_at` integer, + `resolved_release` text, + `resolved_at` integer, + `regressions` integer DEFAULT 0 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incidents_bugsink_issue_id_unique` ON `incidents` (`bugsink_issue_id`);--> statement-breakpoint +CREATE TABLE `oauth_clients` ( + `id` text PRIMARY KEY NOT NULL, + `name` text NOT NULL, + `redirect_uris` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `oauth_codes` ( + `code_hash` text PRIMARY KEY NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `redirect_uri` text NOT NULL, + `code_challenge` text NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `oauth_tokens` ( + `token_hash` text PRIMARY KEY NOT NULL, + `kind` text NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `revoked_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `project_invites` ( + `project_id` integer NOT NULL, + `login` text NOT NULL, + `invited_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `login`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`invited_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `project_members` ( + `project_id` integer NOT NULL, + `user_id` integer NOT NULL, + `added_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `user_id`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`added_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `projects` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `slug` text NOT NULL, + `key` text NOT NULL, + `name` text NOT NULL, + `description` text, + `gitea_owner` text NOT NULL, + `gitea_repo` text NOT NULL, + `default_branch` text DEFAULT 'main' NOT NULL, + `workspace_path` text NOT NULL, + `owner_id` integer, + `next_task_number` integer DEFAULT 1 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `projects_slug_unique` ON `projects` (`slug`);--> statement-breakpoint +CREATE UNIQUE INDEX `projects_key_unique` ON `projects` (`key`);--> statement-breakpoint +CREATE TABLE `questions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `kind` text NOT NULL, + `text` text NOT NULL, + `options` text, + `answer` text, + `answered_via` text, + `telegram_message_id` integer, + `awaiting_hook` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `answered_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `sessions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `tmux_name` text NOT NULL, + `provider` text DEFAULT 'claude' NOT NULL, + `claude_session_id` text, + `generation` integer DEFAULT 0 NOT NULL, + `auto_nudges` integer DEFAULT 0 NOT NULL, + `resume_at` integer, + `limit_probe_min` integer, + `limit_resumes` integer DEFAULT 0 NOT NULL, + `limit_resumes_day` text, + `limit_resumed_at` integer, + `status` text DEFAULT 'starting' NOT NULL, + `last_activity_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `ended_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `sessions_tmux_name_unique` ON `sessions` (`tmux_name`);--> statement-breakpoint +CREATE TABLE `settings` ( + `key` text PRIMARY KEY NOT NULL, + `value` text NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `tasks` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `goal_id` integer, + `number` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'backlog' NOT NULL, + `openspec_change` text, + `pr_url` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `tasks_project_number` ON `tasks` (`project_id`,`number`);--> statement-breakpoint +CREATE TABLE `telegram_outbox` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `dedupe_key` text NOT NULL, + `method` text NOT NULL, + `params` text NOT NULL, + `question_id` integer, + `status` text DEFAULT 'pending' NOT NULL, + `attempts` integer DEFAULT 0 NOT NULL, + `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `telegram_message_id` integer, + `error` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `sent_at` integer, + FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `telegram_outbox_dedupe_key_unique` ON `telegram_outbox` (`dedupe_key`);--> statement-breakpoint +CREATE TABLE `telegram_updates` ( + `update_id` integer PRIMARY KEY NOT NULL, + `status` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `users` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `gitea_id` integer NOT NULL, + `login` text NOT NULL, + `name` text, + `email` text, + `avatar_url` text, + `access_token_enc` text, + `refresh_token_enc` text, + `token_expires_at` integer, + `claude_token_enc` text, + `claude_token_set_at` integer, + `telegram_chat_id` integer, + `telegram_user_id` integer, + `telegram_username` text, + `telegram_paired_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_login_at` integer +); +--> statement-breakpoint +CREATE UNIQUE INDEX `users_gitea_id_unique` ON `users` (`gitea_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_login_unique` ON `users` (`login`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_telegram_chat_id_unique` ON `users` (`telegram_chat_id`); \ No newline at end of file diff --git a/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json new file mode 100644 index 00000000..01d02036 --- /dev/null +++ b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json @@ -0,0 +1,1947 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "d623ae37-1edf-4383-bd4f-443a1954867e", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/bench/sqlite/schema-port/migrations/meta/_journal.json b/bench/sqlite/schema-port/migrations/meta/_journal.json new file mode 100644 index 00000000..82b04f9e --- /dev/null +++ b/bench/sqlite/schema-port/migrations/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1794565466624, + "tag": "0000_baseline", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/bench/sqlite/schema-port/node-sqlite-driver.ts b/bench/sqlite/schema-port/node-sqlite-driver.ts new file mode 100644 index 00000000..94a35c7e --- /dev/null +++ b/bench/sqlite/schema-port/node-sqlite-driver.ts @@ -0,0 +1,93 @@ +// PEP-36 prototype: drizzle on Node's built-in node:sqlite. drizzle-orm 0.45 has no +// node:sqlite driver (it exists only in 1.0 beta/rc), but node:sqlite's API is close to +// better-sqlite3's, so a thin client shim lets drizzle's better-sqlite3 *session* run on it: +// prepare() → run/all/get/raw(), transaction(fn) → .deferred/.immediate/.exclusive. +// drizzle-orm/better-sqlite3 itself is not imported: its driver.js imports the native +// better-sqlite3 package at load time. construct() below mirrors that driver. +import { DatabaseSync, type StatementSync } from "node:sqlite"; +import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session"; +import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations"; +import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db"; +import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect"; + +type Params = unknown[]; + +class Statement { + stmt: StatementSync; + rawStmt: StatementSync | null = null; + db: DatabaseSync; + sql: string; + constructor(db: DatabaseSync, sql: string) { + this.db = db; + this.sql = sql; + this.stmt = db.prepare(sql); + } + run(...p: Params) { + return this.stmt.run(...(p as any[])); + } + all(...p: Params) { + return this.stmt.all(...(p as any[])); + } + get(...p: Params) { + return this.stmt.get(...(p as any[])); + } + /** Rows as arrays (drizzle maps columns by position). */ + raw() { + if (!this.rawStmt) { + this.rawStmt = this.db.prepare(this.sql); + this.rawStmt.setReturnArrays(true); + } + return this.rawStmt; + } +} + +export class NodeSqliteClient { + db: DatabaseSync; + cache = new Map(); + constructor(path: string, opts: { busyTimeoutMs?: number } = {}) { + this.db = new DatabaseSync(path); + // busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY + // when many processes open the file together (see bench/sqlite/README.md). + this.db.exec(`PRAGMA busy_timeout = ${opts.busyTimeoutMs ?? 5000}`); + this.db.exec("PRAGMA journal_mode = WAL"); + this.db.exec("PRAGMA synchronous = NORMAL"); + this.db.exec("PRAGMA foreign_keys = ON"); + } + prepare(sql: string) { + let s = this.cache.get(sql); + if (!s) this.cache.set(sql, (s = new Statement(this.db, sql))); + return s; + } + exec(sql: string) { + this.db.exec(sql); + } + transaction(fn: (...a: any[]) => T) { + const run = (begin: string) => (...a: any[]) => { + this.db.exec(begin); + try { + const r = fn(...a); + if (r && typeof (r as any).then === "function") throw new Error("SQLite transactions must be synchronous (no async callback)"); + this.db.exec("COMMIT"); + return r; + } catch (e) { + if (this.db.isTransaction) this.db.exec("ROLLBACK"); + throw e; + } + }; + return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") }; + } + close() { + this.db.close(); + } +} + +export function drizzleNodeSqlite>(path: string, fullSchema: S) { + const client = new NodeSqliteClient(path); + const dialect = new SQLiteSyncDialect(); + const tables = extractTablesRelationalConfig(fullSchema, createTableRelationsHelpers); + const schema = { fullSchema, schema: tables.tables, tableNamesMap: tables.tableNamesMap }; + const session = new BetterSQLiteSession(client as any, dialect, schema as any); + const db = new BaseSQLiteDatabase("sync", dialect, session as any, schema as any) as any; + db.$client = client; + return db as BaseSQLiteDatabase<"sync", unknown, S>; +} diff --git a/bench/sqlite/schema-port/schema.ts b/bench/sqlite/schema-port/schema.ts new file mode 100644 index 00000000..4b36f55e --- /dev/null +++ b/bench/sqlite/schema-port/schema.ts @@ -0,0 +1,357 @@ +import { relations } from "drizzle-orm"; +import { sql } from "drizzle-orm"; +import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; + +// PEP-36 prototype: the Peppa schema mechanically ported to SQLite (not used by the product). +const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`; + +const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs); +const updatedAt = () => + integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date()); + +/** People who log into the web, one per Gitea account. */ +export const users = sqliteTable("users", { + id: integer("id").primaryKey({ autoIncrement: true }), + giteaId: integer("gitea_id").notNull().unique(), + login: text("login").notNull().unique(), + name: text("name"), + email: text("email"), + avatarUrl: text("avatar_url"), + // OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts). + accessTokenEnc: text("access_token_enc"), + refreshTokenEnc: text("refresh_token_enc"), + tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }), + // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the + // Claude sessions of this user's projects. + claudeTokenEnc: text("claude_token_enc"), + claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }), + // Telegram chat paired from Settings; agent questions of this user's projects go there. + telegramChatId: integer("telegram_chat_id").unique(), + telegramUserId: integer("telegram_user_id"), + telegramUsername: text("telegram_username"), + telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }), + createdAt: createdAt(), + lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), +}); + +export const projects = sqliteTable("projects", { + id: integer("id").primaryKey({ autoIncrement: true }), + slug: text("slug").notNull().unique(), + // Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2… + key: text("key").notNull().unique(), + name: text("name").notNull(), + description: text("description"), + giteaOwner: text("gitea_owner").notNull(), + giteaRepo: text("gitea_repo").notNull(), + defaultBranch: text("default_branch").notNull().default("main"), + workspacePath: text("workspace_path").notNull(), + // Null for projects created by the bot/CLI; only the owner sees a project in the web. + ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }), + // Next task number to hand out; bumped atomically on task creation. + nextTaskNumber: integer("next_task_number").notNull().default(1), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +/** People who work on a project besides its owner (projects.owner_id). */ +export const projectMembers = sqliteTable( + "project_members", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + addedBy: integer("added_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.userId] })], +); + +/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */ +export const projectInvites = sqliteTable( + "project_invites", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + login: text("login").notNull(), // lower-cased Gitea login + invitedBy: integer("invited_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.login] })], +); + +export const goalStatusValues = ["open", "done", "archived"] as const; + +/** Top-level objectives set by the PM; tasks are broken out of them. */ +export const goals = sqliteTable("goals", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + title: text("title").notNull(), + description: text("description"), + status: text("status", { enum: goalStatusValues }).notNull().default("open"), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +export const taskStatusValues = [ + "backlog", // created, nobody working on it + "proposing", // agent is writing the OpenSpec change + "awaiting_approval", // proposal ready, PM must approve + "in_progress", // agent applying the change + "review", // PR open in Gitea + "done", // change archived, merged + "blocked", +] as const; + +export const tasks = sqliteTable( + "tasks", + { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), + number: integer("number").notNull(), + title: text("title").notNull(), + description: text("description"), + status: text("status", { enum: taskStatusValues }).notNull().default("backlog"), + // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth" + openspecChange: text("openspec_change"), + prUrl: text("pr_url"), + createdAt: createdAt(), + updatedAt: updatedAt(), + }, + (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], +); + +export const sessionStatusValues = [ + "starting", + "running", + "waiting_input", // Claude asked something / needs permission + "idle", // turn finished, nothing pending + "stalled", // watchdog saw no activity + "rate_limited", // StopFailure with error=rate_limit, or limit banner on screen + "done", + "failed", +] as const; + +/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */ +export const sessions = sqliteTable("sessions", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + tmuxName: text("tmux_name").notNull().unique(), + provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"), + // Claude session id or Codex thread id — the resume target. + conversationId: text("claude_session_id"), + // Bumped on every launch/resume; hooks from an older generation are ignored. + generation: integer("generation").notNull().default(0), + // Consecutive "keep going" nudges from the Stop hook; reset when a human answers. + autoNudges: integer("auto_nudges").notNull().default(0), + // Usage limit recovery (PEP-56): when to continue, current probe interval if the reset + // time is unknown, auto-resumes today (cap), and when the last auto-resume happened. + resumeAt: integer("resume_at", { mode: "timestamp_ms" }), + limitProbeMin: integer("limit_probe_min"), + limitResumes: integer("limit_resumes").notNull().default(0), + limitResumesDay: text("limit_resumes_day"), + limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }), + status: text("status", { enum: sessionStatusValues }).notNull().default("starting"), + lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), + startedAt: createdAt(), + endedAt: integer("ended_at", { mode: "timestamp_ms" }), +}); + +/** Questions routed to the PM (Telegram / web) and their answers. */ +export const questions = sqliteTable("questions", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), + // Null when asked from a session Peppa did not start (manual `claude`). + sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), + kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(), + text: text("text").notNull(), + options: text("options", { mode: "json" }).$type(), + answer: text("answer"), + // "system": closed by Peppa itself (session stopped/resumed), not by a person. + answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }), + telegramMessageId: integer("telegram_message_id"), + // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer, + // so it must not also be typed into the terminal. + awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false), + createdAt: createdAt(), + answeredAt: integer("answered_at", { mode: "timestamp_ms" }), +}); + +/** Event log: hook / watchdog events, progress reports, status changes. */ +export const events = sqliteTable("events", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), + sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), + type: text("type").notNull(), + payload: text("payload", { mode: "json" }), + createdAt: createdAt(), +}); + +/** Small key/value store for service state (Telegram offset, pairing, binding). */ +export const settings = sqliteTable("settings", { + key: text("key").primaryKey(), + value: text("value", { mode: "json" }).notNull(), + updatedAt: updatedAt(), +}); + +/** + * Durable Telegram outbox: every message/edit is queued here first, then delivered with + * retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message). + */ +export const telegramOutbox = sqliteTable("telegram_outbox", { + id: integer("id").primaryKey({ autoIncrement: true }), + dedupeKey: text("dedupe_key").notNull().unique(), + method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(), + params: text("params", { mode: "json" }).$type>().notNull(), + questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), + status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"), + attempts: integer("attempts").notNull().default(0), + nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs), + telegramMessageId: integer("telegram_message_id"), + error: text("error"), + createdAt: createdAt(), + sentAt: integer("sent_at", { mode: "timestamp_ms" }), +}); + +/** Telegram updates already taken: recorded before acting, so a restart never replays one. */ +export const telegramUpdates = sqliteTable("telegram_updates", { + updateId: integer("update_id").primaryKey(), + status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(), + createdAt: createdAt(), +}); + +/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ +export const oauthClients = sqliteTable("oauth_clients", { + id: text("id").primaryKey(), + name: text("name").notNull(), + redirectUris: text("redirect_uris", { mode: "json" }).$type().notNull(), + createdAt: createdAt(), +}); + +/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */ +export const oauthCodes = sqliteTable("oauth_codes", { + codeHash: text("code_hash").primaryKey(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + redirectUri: text("redirect_uri").notNull(), + codeChallenge: text("code_challenge").notNull(), + scope: text("scope"), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + usedAt: integer("used_at", { mode: "timestamp_ms" }), +}); + +/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */ +export const oauthTokens = sqliteTable("oauth_tokens", { + tokenHash: text("token_hash").primaryKey(), + kind: text("kind", { enum: ["access", "refresh"] }).notNull(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + scope: text("scope"), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + revokedAt: integer("revoked_at", { mode: "timestamp_ms" }), + createdAt: createdAt(), + lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), +}); + +export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const; +export type IncidentPolicy = (typeof incidentPolicies)[number]; + +/** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */ +export const incidentSettings = sqliteTable("incident_settings", { + projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }), + // Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/. + hookSecret: text("hook_secret").notNull().unique(), + policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"), + // The PM's mini-prompt for the triage agent ("how to decide"). + triagePrompt: text("triage_prompt"), + environments: text("environments", { mode: "json" }).$type().notNull().default(["prod", "production"]), + dailyLimit: integer("daily_limit").notNull().default(5), + ignorePattern: text("ignore_pattern"), + goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), + // False: the alert webhook still has to be added in Bugsink by hand (polling covers it). + webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +/** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */ +export const errorSources = sqliteTable( + "error_sources", + { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + kind: text("kind", { enum: ["web", "api"] }).notNull(), + bugsinkProjectId: integer("bugsink_project_id").notNull().unique(), + dsn: text("dsn").notNull(), + createdAt: createdAt(), + }, + (t) => [uniqueIndex("error_sources_project_kind").on(t.projectId, t.kind)], +); + +export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const; + +/** A Bugsink issue seen in Peppa. Repeated events update the same row. */ +export const incidents = sqliteTable("incidents", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + source: text("source", { enum: ["web", "api"] }).notNull(), + bugsinkIssueId: text("bugsink_issue_id").notNull().unique(), + friendlyId: text("friendly_id"), + title: text("title").notNull(), + culprit: text("culprit"), + level: text("level"), + environment: text("environment"), + firstRelease: text("first_release"), + lastRelease: text("last_release"), + events: integer("events").notNull().default(1), + firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(), + lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(), + url: text("url"), + stack: text("stack"), + // new → open | pending | task | ignored; task → resolved → regressed (see design.md) + status: text("status", { enum: incidentStatuses }).notNull().default("new"), + decision: text("decision", { enum: ["notify", "backlog", "start", "ask", "ignore"] }), + decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }), + decisionReason: text("decision_reason"), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }), + resolvedRelease: text("resolved_release"), + resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }), + regressions: integer("regressions").notNull().default(0), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +export const projectsRelations = relations(projects, ({ many }) => ({ + goals: many(goals), + tasks: many(tasks), + sessions: many(sessions), +})); +export const goalsRelations = relations(goals, ({ one, many }) => ({ + project: one(projects, { fields: [goals.projectId], references: [projects.id] }), + tasks: many(tasks), +})); +export const tasksRelations = relations(tasks, ({ one, many }) => ({ + project: one(projects, { fields: [tasks.projectId], references: [projects.id] }), + goal: one(goals, { fields: [tasks.goalId], references: [goals.id] }), + sessions: many(sessions), + questions: many(questions), + events: many(events), +})); +export const sessionsRelations = relations(sessions, ({ one, many }) => ({ + project: one(projects, { fields: [sessions.projectId], references: [projects.id] }), + task: one(tasks, { fields: [sessions.taskId], references: [tasks.id] }), + questions: many(questions), + events: many(events), +})); +export const questionsRelations = relations(questions, ({ one }) => ({ + project: one(projects, { fields: [questions.projectId], references: [projects.id] }), + task: one(tasks, { fields: [questions.taskId], references: [tasks.id] }), + session: one(sessions, { fields: [questions.sessionId], references: [sessions.id] }), +})); +export const eventsRelations = relations(events, ({ one }) => ({ + project: one(projects, { fields: [events.projectId], references: [projects.id] }), + task: one(tasks, { fields: [events.taskId], references: [tasks.id] }), + session: one(sessions, { fields: [events.sessionId], references: [sessions.id] }), +})); diff --git a/bench/sqlite/schema-port/tx-check.ts b/bench/sqlite/schema-port/tx-check.ts new file mode 100644 index 00000000..2182f226 --- /dev/null +++ b/bench/sqlite/schema-port/tx-check.ts @@ -0,0 +1,35 @@ +// PEP-36 prototype: does drizzle's bun:sqlite driver keep `await` inside db.transaction()? +// core/tasks.ts (createTask) is written that way for postgres-js. +import { Database } from "bun:sqlite"; +import { eq, sql } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import * as schema from "./schema.ts"; + +const db = drizzle(new Database(":memory:"), { schema }); +migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname }); +await db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp" }); + +// 1. Async callback, as in core/tasks.ts. +try { + await db.transaction(async (tx) => { + const [p] = await tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning(); + await tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title: "t" }); + throw new Error("rollback please"); + }); +} catch (e) { + console.log("async tx threw:", (e as Error).message); +} +const [p1] = await db.select().from(schema.projects); +const t1 = await db.select().from(schema.tasks); +console.log("after async tx + throw: next_task_number =", p1.nextTaskNumber, "tasks =", t1.length, t1.length || p1.nextTaskNumber !== 1 ? "→ NOT rolled back" : "→ rolled back"); + +// 2. Sync callback (what the sqlite drivers expect). +try { + db.transaction((tx) => { + tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run(); + throw new Error("rollback please"); + }); +} catch {} +const [p2] = await db.select().from(schema.projects); +console.log("after sync tx + throw: next_task_number =", p2.nextTaskNumber, p2.nextTaskNumber === 100 ? "→ NOT rolled back" : "→ rolled back"); diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md new file mode 100644 index 00000000..b889c006 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/design.md @@ -0,0 +1,253 @@ +# Design: PEP-36 — Node 26 без сборки + SQLite + +## Контекст + +В базу Пеппы пишут одновременно: веб (server actions, OAuth, health), бот (outbox, +telegram_updates, ответы), вачдог (tick раз в 30 с, heartbeat, лимиты, Bugsink), **хук +каждого события Claude — отдельный короткий процесс**, MCP-сервер каждого раннера и CLI. +Бот узнаёт о новых событиях через Postgres LISTEN/NOTIFY (`core/notify.ts`, +`apps/bot/src/bot.ts`). Вопрос этапа: тянет ли это SQLite, чем заменить NOTIFY и что +сломается без tsx (замер делался для Bun и Node; PM выбрал Node 26, см. «Решение PM»). + +Всё ниже измерено на Mac Пеппы (Apple Silicon, Node 26.8, Bun 1.4.4, Postgres 17.11 в +docker) бенчмарком `bench/sqlite` (методика — `bench/sqlite/README.md`). + +## Реальная нагрузка (боевая БД, только чтение) + +- 107 событий за сутки на 5 сессиях; медианный промежуток между событиями одной сессии + 16 с, пик — 6 событий в минуту на сессию. +- Хуки срабатывают на prompt / notification / stop / permission, не на каждый tool use. +- База — 9 МБ. Самые «горячие» таблицы по числу изменений: sessions, oauth_tokens, tasks, + events, settings, telegram_outbox. + +Модель бенчмарка берёт это с запасом (хук раз в 10 с на раннер, 10 % — блокирующий вопрос +с опросом раз в 1,5 с, MCP progress раз в 30 с, get_task раз в 15 с, бот, 3 доски веба +раз в 5 с, вачдог), плюс стресс ×10 и ×50. + +## Результаты + +### Запись при параллельной работе раннеров + +p50/p95/p99/max — время транзакции записи в мс (включая ожидание блокировки); «хук» — +время старта процесса хука до первой строки кода (без tsx, см. ниже). + +| раннеры | нагрузка | вариант | записей | p50 | p95 | p99 | max | SQLITE_BUSY | ошибки | старт хука p50 | +|---|---|---|---|---|---|---|---|---|---|---| +| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 32 мс | +| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 96 мс | +| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 97 мс | +| 10 | ×1 | один писатель | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 23 мс | +| 10 | ×1 | **Postgres (сейчас)** | 177 | 9.60 | 18.11 | 36.05 | 38.15 | — | 0 | 92 мс | +| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 28 мс | +| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 72 мс | +| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 88 мс | +| 20 | ×1 | один писатель | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 25 мс | +| 20 | ×1 | **Postgres (сейчас)** | 306 | 8.06 | 17.16 | 29.14 | 36.39 | — | 0 | 85 мс | +| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 19 мс | +| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 69 мс | +| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 69 мс | +| 20 | ×10 | один писатель | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 20 мс | +| 20 | ×10 | **Postgres (сейчас)** | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | — | 0 | 68 мс | +| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 16 мс | +| 20 | ×50 | один писатель | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 16 мс | +| 20 | ×50 | **Postgres (сейчас)** | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | — | 0 | 68 мс | + +Полные таблицы по каждой операции — `node bench/sqlite/report.ts` после прогона. +Чтения: доска веба (4 запроса) p99 0,2 мс на SQLite против 5,8 мс на Postgres; опрос +ответа хуком p99 0,2 мс против 2,2 мс. + +**Вывод:** при реальной нагрузке и даже при ×50 (≈ 70 записей/с — больше упирается в +запуск процессов хука, чем в базу) SQLite в WAL не дал ни одного SQLITE_BUSY и ни одной +ошибки; запись в 25–50 раз быстрее Postgres по медиане и в 6–15 раз по p99. Причина — +нет сетевого хопа и соединения: процесс хука открывает файл за 2 мс против 8 мс на +соединение с Postgres. + +### Потолок: все процессы пишут без пауз + +`bench/sqlite/contention.ts`: N процессов пишут транзакцию хука (update + insert) подряд, +10 секунд. Это в ~1000 раз выше реальной нагрузки. + +| вариант | процессов | транзакций/с | p50 | p95 | p99 | max | BUSY-повторы | ошибки | +|---|---|---|---|---|---|---|---|---| +| bun:sqlite | 20 | 33 537 | 0.02 | 0.08 | 4.24 | 2711 | 0 | 0 | +| bun:sqlite | 40 | 27 223 | 0.03 | 0.31 | 21.96 | 2931 | 0 | 0 | +| node:sqlite | 20 | 48 578 | 0.02 | 0.03 | 0.05 | 5406 | 1 | 0 | +| node:sqlite | 40 | 47 694 | 0.02 | 0.03 | 0.06 | 6413 | 3 | 0 | +| better-sqlite3 | 20 | 47 456 | 0.02 | 0.03 | 0.05 | 5360 | 1 | 0 | +| better-sqlite3 | 40 | 45 076 | 0.02 | 0.03 | 0.06 | 5938 | 2 | 0 | +| Postgres | 20 | 4 890 | 3.88 | 6.82 | 9.01 | 97 | — | 0 | +| Postgres | 40 | 7 555 | 5.47 | 6.95 | 8.33 | 210 | — | 0 | + +**Вывод:** запас по пропускной способности — три-четыре порядка. Слабое место SQLite — +**хвост при насыщении**: блокировка записи не очередь FIFO, а повторные попытки с паузами, +поэтому единичные транзакции ждут секунды (max 3–6 с), а при `busy_timeout=5000` бывают +единичные SQLITE_BUSY (повтор спасает, ошибок 0). Postgres в насыщении предсказуемее +(max 0,1–0,2 с). Для Пеппы это не актуально, пока запись — короткие транзакции раз в +секунды; это и есть граница, где Postgres «как дополнение» имеет смысл (см. ниже). + +Наблюдение: `bun:sqlite` на macOS использует системную SQLite 3.43 (Node 26 — встроенную +3.53, better-sqlite3 — 3.54), отсюда хуже p99 в насыщении. В Docker на Linux Bun несёт +свою свежую SQLite; на Mac можно подключить свежую через `Database.setCustomSQLite`. + +### Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10) + +Задержка от момента записи события до момента, когда бот/веб его прочитали. + +| способ | бот p50 | p95 | p99 | max | +|---|---|---|---|---| +| **push** (сигнал по unix-сокету) | 0.80 | 1.42 | 2.48 | 47 | +| fs.watch на `-wal` | 26 | 192 | 300 | 508 | +| опрос с курсором 200 мс | 100 | 192 | 200 | 204 | +| опрос с курсором 1000 мс | 503 | 945 | 991 | 1002 | +| Postgres LISTEN/NOTIFY (сейчас) | 9.76 | 15.06 | 17.73 | 28 | + +- **push** быстрее NOTIFY в 10 раз; при недоступном сокете подписчик не узнаёт о событии + до страховочного опроса. +- **fs.watch** на macOS склеивает и теряет уведомления (в смоуке единичные события + доходили только страховочным опросом через 3 с), в Docker с bind-mount с хоста Mac не + работает совсем (inotify не проходит через VM). Отвергнут. +- **опрос** надёжен и прост, 200 мс — дешёвый запрос по индексу (0,1 мс), но всегда + добавляет задержку. + +### Bun на текущем коде (проверено до решения PM; Node без tsx — этап 1) + +| что | результат | +|---|---| +| `peppa` CLI (`help`, `project add`, `goal add`, `task add/list`) | работает; старт 0,04 с против 0,47 с у tsx | +| `peppa-hook` | работает (запись события + `pg_notify`); старт **0,04 с против 0,44 с у tsx** | +| `peppa-mcp` (stdio, SDK MCP) | работает: `tools/list`, `list_goals`, `list_tasks`, `get_task` | +| drizzle + postgres.js, мигратор | работает: все 12 миграций применены под Bun | +| бот (`bot.test.ts`, LISTEN, mock-telegram) | 13/13 тестов под `bun test` | +| весь e2e под `bun test` (13 файлов, по одному) | **134 прошли, 0 упали** (1 пропущен, как и под tsx); бинари внутри тестов (mock-claude, peppa-mcp, peppa-hook) пока через tsx | +| `bun --bun next dev` (Next 16.4, Turbopack) | работает: готов за 0,2 с, `/api/health` 200, вход по login-link, доска `/p/BUN`, задача `/t/BUN-1`, раннеры, настройки, помощь — 200; `node_modules/.bin/next` — shell-шим pnpm, запускать `next/dist/bin/next` | +| node:test | `bun test` понимает `node:test` (`describe/it/before`); прямой запуск файла `bun x.test.ts` — нет, нужен `bun test` | +| tsx-специфика | не нужна: Bun исполняет `.ts` с импортами `.ts` как есть | + +Хук — главный выигрыш: Claude ждёт хук на каждом событии, а PermissionRequest/ +AskUserQuestion — ещё и человека; 0,4 с на старт tsx сейчас — это 90 % времени хука. + +### Node 26 вместо Bun (решение PM) + +PM выбрал Node 26 со встроенным снятием типов и `node:sqlite`. По замеру это не хуже Bun +там, где важно: + +- **Запись** на той же нагрузке (таблица выше, строки `node:sqlite`): p50 0,13–0,20 мс, + p99 0,9–1,3 мс — не хуже `bun:sqlite` (0,20–0,32 / 1,2–2,3); в потолке — 48 тыс. + транзакций/с против 27–34 тыс. и p99 0,05 мс против 4–22 мс (у Node 26 встроенная + SQLite 3.53, у Bun на macOS — системная 3.43). +- **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert, + 20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс. +- **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против + 16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт + `peppa-hook` на Node без tsx замеряется в этапе 1. +- `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего + лишнего. + +**Драйвер drizzle.** В стабильном drizzle 0.45 драйвера `node:sqlite` нет (только в +1.0 beta/rc — мажорное обновление ради одного драйвера не берём). `sqlite-proxy` не +подходит: он асинхронный, транзакции через него не атомарны для нескольких процессов. +better-sqlite3 под Node 26 собирается из исходников (готовых бинарников нет, 12.x не +собирается вовсе). Решение — **тонкая прослойка** (`schema-port/node-sqlite-driver.ts`, +~80 строк): клиент `node:sqlite` с API better-sqlite3 (`prepare → run/all/get/raw`, +`transaction(fn).immediate`) под сессию drizzle `better-sqlite3/session`; сам +`drizzle-orm/better-sqlite3` не импортируется (его driver.js тянет нативный пакет). +Проверено: мигратор drizzle, `returning`, `Date`, JSON, boolean, bigint (id чата +9007199254740991), связи `db.query…with`, upsert, синхронная транзакция с откатом; +**async-колбэк транзакции прослойка отклоняет с понятной ошибкой** (вместо тихой потери +атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется +штатным `drizzle-orm/node-sqlite`. + +### Схема и данные на SQLite (`bench/sqlite/schema-port`) + +- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`, + `serial` → `integer primaryKey autoIncrement`, `timestamp withTimezone` → + `integer mode timestamp_ms` (drizzle отдаёт `Date`, как сейчас), `jsonb` → `text mode + json` (отдаёт объекты), `pgEnum` → `text enum` (типы в TS те же), `boolean` → + `integer mode boolean`, `bigint` → `integer` (64 бита), `defaultNow()` → + `unixepoch('subsec')*1000`. drizzle-kit генерирует одну базовую миграцию (18 таблиц, + 270 строк) вместо 12 миграций Postgres — историю миграций Postgres не переносим. +- **Перенос боевых данных** (Postgres только на чтение → новый файл): 57 мс, все 18 таблиц + совпали по числу строк, 0 нарушений внешних ключей; drizzle читает `Date`, массивы JSON, + связи (`db.query.tasks.findMany({ with: … })`). +- **Ловушка: асинхронные транзакции.** sqlite-драйверы drizzle (`bun-sqlite`, + `better-sqlite3`) синхронные: `db.transaction(async tx => { await …; await … })` + коммитит после первого `await`, остальное идёт вне транзакции, и **откат не работает** + (проверено: `tx-check.ts`, `next_task_number` и задача остались после исключения). + В коде такой одна — `createTask` (core/tasks.ts); переписать на синхронную и запретить + `transaction(async` проверкой. +- Прочая Postgres-специфика: `pg_notify` (core/notify.ts), `$client.listen` (бот), + `for update skip locked` (core/incidents.ts — не нужно, `BEGIN IMMEDIATE` и так + сериализует писателей), `count(*)::int` (monitor/incidents). `->>`, `lower()`, `like`, + `returning`, `on conflict` в SQLite есть. +- **Ловушка: `->>` возвращает число.** В Postgres `params->>'chat_id'` — текст, в SQLite — + значение JSON-типа (число). `core/telegram.ts` сравнивает его со строкой — на SQLite + такой фильтр ничего не найдёт; нужен `cast(… as text)` или сравнение с числом + (проверено в `drizzle-check.ts`). + +## Решения + +### 1. Переезжать целиком, Postgres не держать + +Замер не нашёл места, где Postgres нужен Пеппе: по задержке SQLite лучше на всех +режимах, ошибок блокировки нет, запас по пропускной способности — тысячи раз. Гибрид +(SQLite + Postgres для части таблиц) добавил бы два драйвера, два способа уведомлений и +распределённые транзакции между базами ради нагрузки, которой нет. Чаты PM решил долго не +хранить — их объём тоже не повод. Postgres «как дополнение» возвращаем точечно, если +появится поток записей на сотни в секунду длинными транзакциями (там, где у SQLite +хвост блокировок) — например, хранение логов терминалов раннеров (PEP-9). + +Отвергнуто: «не переезжать» — Postgres медленнее на нашей нагрузке и требует отдельного +контейнера; «гибрид сейчас» — сложность без измеренной причины. + +### 2. Каждый процесс пишет сам, без сервиса-писателя + +Вариант «один писатель» (все записи по HTTP через unix-сокет) медленнее прямой записи в +4–6 раз по медиане (1,1–1,3 мс против 0,2–0,3), добавляет точку отказа (упал писатель — +встали хуки всех раннеров) и процесс, который нужно поднимать раньше всех. Его плюс — +FIFO-очередь записи без хвостов — нужен только при насыщении, которого нет. + +Правила для всех процессов (обёртка в `packages/db`): +- `PRAGMA busy_timeout = 5000` **первой** командой — иначе при одновременном открытии + файла многими процессами бывает `SQLITE_BUSY_RECOVERY` без ожидания (поймано в смоуке); +- `journal_mode=WAL` один раз при создании файла; `synchronous=NORMAL`, `foreign_keys=ON`; +- запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY; +- база только на локальном диске (WAL не работает на сетевых ФС). + +### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос + +Источник правды — таблица `events` и курсор подписчика (`settings`, ключ +`cursor:`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY, +пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший +процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого +подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в +секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала. + +### 4. Поэтапно: Node без tsx → SQLite → Docker + +Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; ускоряет старт каждого +процесса (хук — в разы). Код должен проходить `erasableSyntaxOnly`: Node снимает только +типы, parameter properties, `enum`, `namespace` с кодом не поддерживаются. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме +только чтения как откатом. Этап 3 зависит от PEP-17/PEP-18: раннеры (tmux + claude + +рабочие копии) должны видеть тот же файл базы на локальном диске; самый простой вариант — +сервисы и раннеры в одном контейнере с томами хоста. + +## Риски + +- **Хвост блокировок при насыщении** (max секунды) — не проявился на нагрузке ×50; следим + метрикой «время записи p99» в heartbeat, порог алерта 1 с. +- **Повреждение/потеря файла** — WAL устойчив к падению процесса; ежедневная копия + `VACUUM INTO` (7 штук) и копия перед переносом. +- **Next.js** остаётся как есть (свой компилятор TS); `node:sqlite` работает в серверном + коде Next на Node 26 так же, как в остальных процессах. +- **Прослойка drizzle ↔ node:sqlite** — своя, хоть и маленькая; покрыта проверками + `drizzle-check.ts`, при переходе на drizzle 1.0 заменяется штатным драйвером. +- **Bugsink** держит свою базу в контейнере `peppa-postgres` — контейнер нельзя удалить, + пока Bugsink не переведён (отдельная задача; Bugsink умеет SQLite). +- `better-sqlite3` под Node 26 нет готовых бинарников (сборка node-gyp из исходников, + версия 12.x не собирается вовсе) — поэтому `node:sqlite`, он встроен. + +## Решение PM + +Одобрено 2026-11-13 (approval #41) с изменением рантайма: Node 26 + `node:sqlite` вместо +Bun; каждый процесс пишет сам; Postgres остаётся только для Bugsink (перевод — отдельная +задача). Этап 2 начинается после мержа PEP-38 (переделка `apps/web`). diff --git a/openspec/changes/pep-36-lightweight-stack/proposal.md b/openspec/changes/pep-36-lightweight-stack/proposal.md new file mode 100644 index 00000000..a4a91726 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/proposal.md @@ -0,0 +1,56 @@ +# Proposal: PEP-36 — легковесный стек: Node 26 без сборки + SQLite, запуск одной командой + +Задача Пеппы: **PEP-36** · Цель «Безопасность и эксплуатация». + +## Why + +Пеппу сейчас поднимают Node + tsx + pnpm + Postgres в docker + `next build`. Для одной +машины это тяжело: отдельный контейнер БД, медленный старт процессов (хук Claude — новый +процесс tsx на каждое событие, ~0,44 с только на старт). Перед переездом нужно было +ответить: выдержит ли один файл SQLite записи из многих процессов (веб, бот, вачдог, хуки +и MCP каждого раннера), чем заменить LISTEN/NOTIFY и что сломается без tsx. Замер сделан +(`bench/sqlite`, цифры в design.md). + +## Решение PM (2026-11-13, approval #41) + +- Вся Пеппа на **SQLite (WAL)**; **каждый процесс пишет сам** (WAL + `busy_timeout`), без + сервиса-писателя. +- Рантайм — **Node 26 со встроенным TypeScript** (снятие типов) и **`node:sqlite`**, не Bun. + От tsx уходим. Next.js остаётся как есть. +- Postgres остаётся **только для Bugsink**; перевод Bugsink — отдельная задача. + +## What Changes + +- **Этап 1 — Node без tsx** (без смены БД): `erasableSyntaxOnly` в tsconfig и правка кода, + который Node не может просто очистить от типов (parameter properties и т. п.); bin-обёртки, + скрипты, CI и `install-launchd.sh` — `node` вместо `tsx`; тесты — `node --test`. +- **Этап 2 — SQLite вместо Postgres**: схема на `sqlite-core` (одна базовая миграция + вместо 12), драйвер `node:sqlite` через тонкую прослойку под сессию drizzle (готового + драйвера в стабильном drizzle 0.45 нет, better-sqlite3 под Node 26 собирается из + исходников — не берём); каждый процесс открывает файл сам; LISTEN/NOTIFY → журнал + `events` с курсором + сигнал по unix-сокету + опрос раз в секунду; перенос данных + командой со сверкой; ежедневная копия. Начинается после мержа PEP-38 (переделка `apps/web`). +- **Этап 3 — `docker compose up`**: один образ `node:26` для веба, бота и вачдога; база и + рабочие копии в томах хоста. Связан с PEP-17 (песочница) и PEP-18 (деплой). + +Вне scope: перевод Bugsink с Postgres (PEP-63), хранение чатов (PM: долго не храним). + +## Capabilities + +### New Capabilities +- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Node без сборки, запуск одной командой. + +### Modified Capabilities +- `service-monitoring`: health-эндпоинт проверяет файл SQLite вместо Postgres. + +## Impact + +- Этап 1: `tsconfig.base.json`, классы с parameter properties, `packages/*/bin/*`, + `apps/bot/bin/*`, `package.json` (скрипты), `.gitea/workflows/ci.yml`, `scripts/ci.sh`, + `scripts/install-launchd.sh`. Перевыкатка launchd-агентов — PM. +- Этап 2: `packages/db` (схема, клиент, миграции), `core/notify.ts`, `core/tasks.ts` + (транзакция), `core/incidents.ts` (`for update skip locked`), `core/telegram.ts` + (`->>` возвращает число), `apps/bot` (подписка), `apps/web` (живые обновления, health), + `packages/testkit` (БД тестов). +- Зависимости: −`tsx` (этап 1), −`postgres` (этап 2); нужен Node ≥ 26. +- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос — доли секунды). diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md new file mode 100644 index 00000000..14bf7044 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md @@ -0,0 +1,100 @@ +# Spec Delta: platform-storage + +## Purpose + +Описывает, где Пеппа хранит свои данные после переезда на Node 26 + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой. + +## ADDED Requirements + +### Requirement: Одна база SQLite для всех процессов +Все процессы Пеппы (веб, бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI) SHALL хранить данные в одном файле SQLite в режиме WAL. Каждый процесс SHALL открывать файл сам, первой командой выставлять ожидание блокировки не меньше 5 секунд и писать короткими транзакциями с немедленным захватом записи. Запись, которая не получила блокировку за время ожидания, SHALL повторяться до 3 раз и только потом считаться ошибкой; ошибка SHALL попадать в лог процесса с именем операции. + +#### Scenario: 20 раннеров пишут одновременно +- **GIVEN** 20 раннеров в работе, у каждого свои процессы хуков и MCP, бот, веб и вачдог запущены +- **WHEN** за 10 минут хуки, MCP, бот и вачдог записывают 6000 событий, вопросов и обновлений сессий +- **THEN** в базе ровно 6000 новых записей, ни одна запись не завершилась ошибкой «database is locked», 99 % записей заняли меньше 20 мс + +#### Scenario: Много процессов открывают базу одновременно +- **GIVEN** файл базы существует и в нём идут записи +- **WHEN** 20 процессов хука стартуют в одну и ту же секунду +- **THEN** все 20 открывают базу и записывают свои события, ни один не завершается с кодом `SQLITE_BUSY_RECOVERY` + +#### Scenario: Блокировка держится дольше ожидания +- **GIVEN** посторонний процесс держит транзакцию записи 20 секунд +- **WHEN** хук раннера «PEP-42» пытается записать событие `turn_end` +- **THEN** хук делает 3 попытки, затем пишет в `~/.peppa/hook.log` строку с `hook.event` и `SQLITE_BUSY` и завершается без зависания Claude дольше 30 секунд + +### Requirement: Живые обновления без Postgres +Бот и веб SHALL узнавать о новых событиях, вопросах и изменениях задач, читая журнал `events` по курсору (id последнего прочитанного события). Процесс, записавший событие, SHALL будить подписчиков коротким сигналом по локальному сокету; если сигнал не дошёл, подписчик SHALL всё равно найти событие опросом не реже раза в секунду. + +#### Scenario: Вопрос агента доходит до PM +- **GIVEN** бот запущен, PM привязал Telegram +- **WHEN** агент раннера «PEP-42» задаёт вопрос «Удалить build?» +- **THEN** бот видит вопрос и ставит сообщение PM в очередь в среднем быстрее 50 мс и в 99 % случаев быстрее 1 секунды + +#### Scenario: Сокет подписки недоступен +- **GIVEN** бот запущен, сокет сигналов не создан или упал +- **WHEN** MCP раннера «PEP-42» пишет `report_progress` «Сделал шаг 3 из 7» +- **THEN** бот читает это событие не позже чем через 1 секунду после записи + +#### Scenario: Бот перезапустился +- **GIVEN** бот остановлен, курсор бота — событие 120, за время простоя записаны события 121–125 +- **WHEN** бот запускается +- **THEN** бот обрабатывает события 121–125 по одному разу и сохраняет курсор 125 + +### Requirement: Перенос данных из Postgres +Переезд SHALL выполняться командой, которая читает боевую базу Postgres только на чтение, создаёт новый файл SQLite по актуальной схеме, переносит все таблицы и сверяет число строк и внешние ключи. При любом расхождении команда SHALL удалять новый файл, оставлять Postgres без изменений и печатать, в какой таблице расхождение. + +#### Scenario: Успешный перенос +- **GIVEN** в Postgres 18 таблиц Пеппы, среди них 107 событий, 18 вопросов и 47 сообщений outbox +- **WHEN** администратор запускает `peppa db migrate-to-sqlite ~/.peppa/peppa.db` +- **THEN** создан файл `~/.peppa/peppa.db`, в нём 107 событий, 18 вопросов и 47 сообщений outbox, проверка внешних ключей без нарушений, команда печатает «перенесено, расхождений нет» + +#### Scenario: Расхождение при переносе +- **GIVEN** в таблице `questions` есть строка, ссылающаяся на несуществующую сессию +- **WHEN** администратор запускает перенос +- **THEN** файл SQLite не создан, Postgres не изменён, команда печатает «questions: нарушение внешнего ключа» и завершается с кодом 1 + +### Requirement: Резервная копия базы +Вачдог SHALL раз в сутки делать согласованную копию файла базы без остановки сервисов и хранить последние 7 копий; копия SHALL открываться как самостоятельная база. + +#### Scenario: Ночная копия +- **GIVEN** сервисы работают, раннеры пишут события +- **WHEN** наступает время ежедневной копии +- **THEN** в `~/.peppa/backups/` появляется файл с датой, он открывается и содержит все задачи на момент копии, копий не больше 7 + +#### Scenario: Нет места на диске +- **GIVEN** на диске меньше места, чем размер базы +- **WHEN** вачдог делает копию +- **THEN** неполная копия удалена, админы платформы получают сообщение «резервная копия не сделана: нет места», сервисы продолжают работать + +### Requirement: Сервисы Пеппы на Node без сборки +Бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI и тесты SHALL запускаться командой `node` (Node ≥ 26) прямо из исходников на TypeScript, без tsx и без шага сборки; веб SHALL работать на Next.js как раньше. Код SHALL проходить проверку типов с `erasableSyntaxOnly`. Хук SHALL стартовать и закончить запись события быстрее 300 мс. + +#### Scenario: Хук на каждое событие +- **GIVEN** раннер «PEP-42» работает, Claude вызывает хук Stop +- **WHEN** `peppa-hook stop` получает событие +- **THEN** событие `turn_end` записано, хук завершился быстрее 300 мс, в stderr хука нет предупреждений Node + +#### Scenario: Старый Node на машине +- **GIVEN** на машине Node 22 +- **WHEN** администратор запускает `peppa status` +- **THEN** команда печатает «нужен Node ≥ 26» и завершается с кодом 1 + +#### Scenario: Синтаксис, который Node не умеет снять +- **GIVEN** в `packages/core` добавлен класс с parameter property `constructor(private db: Db)` +- **WHEN** запускается проверка типов +- **THEN** проверка падает с ошибкой `erasableSyntaxOnly` на этой строке + +### Requirement: Запуск одной командой +Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Node 26: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске. + +#### Scenario: Первый запуск +- **GIVEN** чистая машина с Docker, заполненный `.env` +- **WHEN** администратор выполняет `docker compose up -d` +- **THEN** через минуту `GET /api/health` отвечает 200, `db.ok: true`, бот и вачдог в сводке «работает» + +#### Scenario: База на сетевом диске +- **GIVEN** том с базой смонтирован как сетевая папка (NFS/SMB) +- **WHEN** сервис Пеппы стартует +- **THEN** сервис не запускается и пишет «файл базы на сетевом диске: SQLite WAL требует локальный диск» diff --git a/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md new file mode 100644 index 00000000..6b7dd9d8 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md @@ -0,0 +1,16 @@ +# Spec Delta: service-monitoring + +## MODIFIED Requirements + +### Requirement: Health-эндпоинт +Веб SHALL отвечать на `GET /api/health` JSON-сводкой: доступность БД, версия и коммит, состояние сервисов; код ответа 200, если БД доступна, иначе 503. Сводка не содержит логинов и чатов пользователей. + +#### Scenario: Всё работает +- **GIVEN** БД доступна, версия Пеппы 0.15.0 +- **WHEN** запрошен `/api/health` +- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"` и списком сервисов web, bot, watchdog + +#### Scenario: БД недоступна +- **GIVEN** файл базы SQLite не открывается (удалён, нет прав или повреждён) +- **WHEN** запрошен `/api/health` +- **THEN** ответ 503 с `ok: false`, `db.ok: false` и текстом ошибки, не дольше чем за 3 секунды diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md new file mode 100644 index 00000000..50e05236 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/tasks.md @@ -0,0 +1,45 @@ +# Tasks: PEP-36 + +## 0. Замер и решение (этот этап) + +- [x] 0.1 Частоты записи из боевой БД (только чтение): события, вопросы, сессии, outbox +- [x] 0.2 Бенчмарк `bench/sqlite`: 10 и 20 раннеров, ×1 и ×10; bun:sqlite, node:sqlite, better-sqlite3, один писатель, Postgres +- [x] 0.3 Прототипы замены LISTEN/NOTIFY: опрос с курсором, fs.watch WAL, push по unix-сокету +- [x] 0.4 Текущий код под Bun: CLI, `peppa-hook`, `peppa-mcp`, бот, e2e (`bun test`), `next dev` +- [x] 0.5 Прототип схемы на sqlite (`bench/sqlite/schema-port`): базовая миграция, перенос боевых данных, проверка транзакций drizzle +- [x] 0.6 Решение PM (approval #41): SQLite, каждый процесс пишет сам; рантайм Node 26 + `node:sqlite` вместо Bun; Postgres только для Bugsink +- [x] 0.7 Драйвер drizzle ↔ `node:sqlite`: прослойка `schema-port/node-sqlite-driver.ts` + `drizzle-check.ts`; замер node:sqlite против bun:sqlite через drizzle +- [x] 0.8 Отдельная задача: перевод Bugsink с Postgres — PEP-63 + +## 1. Этап 1 — Node 26 без tsx (без смены БД) + +- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный +- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой +- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей +- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить +- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс) + +## 2. Этап 2 — SQLite вместо Postgres + +- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) +- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` +- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции +- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async` +- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть +- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме +- [ ] 2.6 `peppa db migrate-to-sqlite `: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении +- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл +- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude) +- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63) + +## 3. Этап 3 — запуск одной командой + +- [ ] 3.1 Образ на `node:26` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста +- [ ] 3.2 Согласовать с PEP-17 (песочница) и PEP-18 (деплой): где живут раннеры, как контейнер видит рабочие копии и токены +- [ ] 3.3 `docker compose up` на чистой машине → health 200 за минуту; документация в README и `/help` +- [ ] 3.4 Отказ запуска, если база на сетевом диске + +## 4. Завершение + +- [ ] 4.1 AGENTS.md, docs/HANDOFF.md, `/help` — новый стек и команды +- [ ] 4.2 Архив change, PR