// PEP-316: транзакция берёт блокировку записи первой. // 27.11.2026 11:27, «Ошибки из прода» №22 «database is locked»: отчёт шага проверки (веб) пришёл // в момент, когда в базу писал другой процесс. Транзакция начиналась как читающая (BEGIN), а // читающей транзакции SQLite не даёт ждать блокировку записи: отказ сразу, busy_timeout не // работает. Второй процесс здесь настоящий (mock-db-writer): в одном процессе гонку не поймать. import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, describe, test } from "node:test"; import { eq, sql } from "drizzle-orm"; import { core, db, project, teardown } from "./helpers.ts"; const { checkRuns, projects } = await import("@peppa/db"); const WRITER = resolve(fileURLToPath(import.meta.url), "../../src/mock-db-writer.ts"); const HOLD_MS = 600; after(teardown); /** Another process takes the write lock and keeps it for `holdMs`; resolves once the lock is held. */ function otherWriter(holdMs: number): Promise<{ done: Promise }> { const child = spawn(process.execPath, [WRITER, process.env.PEPPA_DB!, String(holdMs)], { stdio: ["ignore", "pipe", "inherit"] }); const done = new Promise((r) => child.on("exit", (code) => r(code))); return new Promise((ok, fail) => { child.stdout.once("data", () => ok({ done })); child.once("error", fail); void done.then((code) => fail(new Error(`mock-db-writer exited with ${code} before taking the lock`))); }); } describe("PEP-316: транзакция берёт блокировку записи первой", () => { test("Отчёт проверки приходит, пока пишет другой процесс: отчёт ждёт и сохраняется", async () => { const p = await core.getProject(db, (await project({ turns: [] })).key); const sha = "e".repeat(40); const other = await otherWriter(HOLD_MS); const t0 = Date.now(); const r = await core.upsertCheckRun(db, p, null, { sha, check: "test", state: "failure", logTail: "✖ упал один тест", source: "report" }); assert.ok(Date.now() - t0 >= HOLD_MS / 3, "the report waited for the other writer instead of failing"); assert.equal(r.run.logTail, "✖ упал один тест", "the log of the report is kept"); assert.equal(await other.done, 0, "the other writer committed"); assert.equal(db.select().from(checkRuns).where(eq(checkRuns.sha, sha)).all().length, 1); }); test("Любая транзакция «прочитал — записал» ждёт чужую запись, а не падает", async () => { const p = await core.getProject(db, (await project({ turns: [] })).key); const other = await otherWriter(HOLD_MS); const name = db.transaction((tx) => { const row = tx.select().from(projects).where(eq(projects.id, p.id)).get()!; tx.update(projects).set({ name: sql`${projects.name} || ' ✓'` }).where(eq(projects.id, p.id)).run(); return row.name; }); assert.equal(await other.done, 0); assert.equal((await core.getProject(db, p.key)).name, `${name} ✓`); }); });