Compare commits
4 Commits
task/pep-3
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bb474b2a0a | |||
| ae7400e4f1 | |||
| 57191981a2 | |||
| 7e84bfd9eb |
5
.peppa/memory/pep-316.md
Normal file
5
.peppa/memory/pep-316.md
Normal 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).
|
||||||
@ -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. */
|
/** 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 }> {
|
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
|
// 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
|
// 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.
|
// log was lost with a 500 (27.11.2026). In turn each sees what the other stored.
|
||||||
|
|||||||
@ -112,7 +112,13 @@ export class SqliteClient {
|
|||||||
throw e;
|
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). */
|
/** Changes committed by other connections since the last call (PRAGMA data_version). */
|
||||||
dataVersion(): number {
|
dataVersion(): number {
|
||||||
|
|||||||
14
packages/testkit/src/mock-db-writer.ts
Normal file
14
packages/testkit/src/mock-db-writer.ts
Normal 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();
|
||||||
55
packages/testkit/test/db-write-lock.test.ts
Normal file
55
packages/testkit/test/db-write-lock.test.ts
Normal 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} ✓`);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user