PEP-316: любая транзакция берёт блокировку записи первой — «database is locked» при записи из другого процесса
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1639с
peppa-ci / ci (pull_request) Successful in 29m27s

27.11.2026 в 11:27 веб потерял отчёт шага проверки с ошибкой «database is locked»: в этот момент
в базу писал другой процесс. `db.transaction` по умолчанию начиналась как читающая (BEGIN), а
читающей транзакции SQLite не даёт ждать блокировку записи: первая запись получает отказ сразу,
busy_timeout не работает. Утренняя правка результата проверок обернула чтение и запись в такую
транзакцию и гонку не убрала; так же были устроены ещё 15 транзакций ядра (команда агентов,
подписки, чаты, журнал подключений).

- db/client.ts: транзакция всегда начинается с BEGIN IMMEDIATE — ждёт свою очередь и видит то,
  что сохранили другие.
- Тест db-write-lock.test.ts с настоящим вторым процессом (mock-db-writer держит блокировку
  записи): отчёт проверки и транзакция «прочитал — записал» ждут и сохраняются. До исправления
  оба случая падали той же ошибкой, что на проде, сразу и без ожидания.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-27 13:02:47 +05:00
parent cb604d7a41
commit ae7400e4f1
6 changed files with 83 additions and 3 deletions

5
.peppa/memory/pep-316.md Normal file
View File

@ -0,0 +1,5 @@
# Память: PEP-316
## Грабли
- Гонку двух процессов за базу тест в одном процессе не ловит: `node:sqlite` синхронный, два вызова идут по очереди. Нужен настоящий второй процесс — `packages/testkit/src/mock-db-writer.ts` держит блокировку записи (PEP-313 «починил» гонку тестом в одном процессе, на проде она осталась).
- Транзакция, начатая как читающая (`BEGIN`), получает «database is locked» на первой записи сразу, без ожидания `busy_timeout`. Поэтому `db.transaction` всегда `BEGIN IMMEDIATE` (PEP-316).

File diff suppressed because one or more lines are too long

View File

@ -72,7 +72,7 @@ export function summarizeChecks(configured: string[], runs: RunLike[], sha: stri
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
// PEP-313: one transaction (the write lock is taken first). The CI step's report (web) and the
// PEP-313: one transaction (it takes the write lock first — PEP-316, db/client.ts). The CI step's report (web) and the
// watchdog's poll write the same check of the same commit at the same moment: read apart from the
// write, both saw no row, the second insert failed on the unique index, and the report with the
// log was lost with a 500 (27.11.2026). In turn each sees what the other stored.

View File

@ -112,7 +112,13 @@ export class SqliteClient {
throw e;
}
};
return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
// PEP-316: every transaction takes the write lock first. Many processes write to this file, and
// SQLite refuses a transaction that began as a reader (plain BEGIN) at its first write — at
// once, busy_timeout does not wait for it — whenever another process is writing: «database is
// locked» (27.11.2026, a CI report lost). drizzle asks for `deferred` unless told otherwise,
// so `deferred` is immediate here too: a transaction waits for its turn and then sees
// what the others stored.
return { deferred: run("BEGIN IMMEDIATE"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
}
/** Changes committed by other connections since the last call (PRAGMA data_version). */
dataVersion(): number {

View File

@ -0,0 +1,14 @@
// PEP-316: a second process that holds SQLite's write lock for a while — like the watchdog or an
// agent's hook writing at the moment the web is inside a transaction. Tests only.
// Usage: node mock-db-writer.ts <db file> <hold ms> — prints «locked» once the lock is held.
import { DatabaseSync } from "node:sqlite";
const [file, hold] = process.argv.slice(2);
const db = new DatabaseSync(file!);
db.exec("PRAGMA busy_timeout = 5000");
db.exec("BEGIN IMMEDIATE");
db.exec("UPDATE projects SET name = name");
process.stdout.write("locked\n");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(hold) || 300);
db.exec("COMMIT");
db.close();

View File

@ -0,0 +1,55 @@
// 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<number | null> }> {
const child = spawn(process.execPath, [WRITER, process.env.PEPPA_DB!, String(holdMs)], { stdio: ["ignore", "pipe", "inherit"] });
const done = new Promise<number | null>((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} ✓`);
});
});