Public: anyone can read this; the crew can change it.

The desk sweep takes the write lock first, so another connection's commit is a wait, not "database is locked" #17639

opened this

Merged 12h 51m ago, live in production

fix/desk-sweep-immediate → main 0 commits

  • Merged. fix/desk-sweep-immediate was merged into main as e052b8d.

Review

Sign in to review this change.
2 files changed +94 −2
src/actions/desk.ts +6 −2
@@ -6,6 +6,7 @@
66 * the `desk.noted` / `desk.cleared` events that carry a note to everyone
77 * watching the repository, so two agents see each other's notes at once.
88 */
9 import { transact } from "../kernel/db.ts";
910 import type { App } from "../app.ts";
1011 import { err, ok, type Result } from "../kernel/result.ts";
1112 import { canRead, canWrite, getRepoById, onCrew, type Repo } from "../core/repos.ts";
@@ -103,8 +104,11 @@ export function readableNotes(app: App, actor: User | undefined, now: Date = new
103104
104105 /** Drop the notes whose time is up; each repository that lost one says so to its readers. */
105106 export function sweepDesk(app: App, now: Date = new Date()): number {
106 // Read and drop in one transaction, so each count is of the notes dropped.
107 const { lapsed, gone } = app.db.transaction(() => ({ lapsed: lapsedRepos(app.db, now), gone: expireNotes(app.db, now) }))();
107 // Read and drop in one transaction, so each count is of the notes dropped. Immediate
108 // (`transact`): a deferred one that has read cannot wait for the write lock, and another
109 // connection's commit in between made it fail at once ("database is locked"; production stopped
110 // on it at 20:14:35 on 2026-12-02).
111 const { lapsed, gone } = transact(app.db, () => ({ lapsed: lapsedRepos(app.db, now), gone: expireNotes(app.db, now) }));
108112 for (const { repoId, count } of lapsed) app.bus.append({ kind: "desk.expired", repoId, payload: { count } });
109113 return gone;
110114 }
test/desk-sweep-lock.test.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * The desk sweep beside another writer (production stopped at 20:14:35 on 2026-12-02 on "database
3 * is locked" in it): its transaction reads the lapsed notes before it drops them, and another
4 * connection's commit in between made a deferred transaction's delete fail at once. It now takes
5 * the write lock first (`transact`), so the other writer is the one that meets the lock, and the
6 * sweep drops every lapsed note.
7 */
8 import { Database } from "bun:sqlite";
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { sweepDesk } from "../src/actions/desk.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { addNote } from "../src/core/desk.ts";
17 import { createUser } from "../src/core/users.ts";
18 import { isBusy } from "../src/kernel/db.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 let dir = "";
24 let app: App;
25 let aliceId = "";
26 let repoId = "";
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "desk-sweep-lock-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 const u = await createUser(app.db, {
32 origin: "seed",
33 trusted: true,
34 username: "alice",
35 email: "[email protected]",
36 password: "a-good-passphrase",
37 adminIfFirst: true,
38 });
39 if (!u.ok) throw new Error(u.error);
40 aliceId = u.value.id;
41 const r = await createRepo(app, u.value, { name: "lib", visibility: "public" });
42 if (!r.ok) throw new Error(String(r.error));
43 repoId = r.value.id;
44 });
45 afterAll(async () => {
46 app.close();
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 test("a write another connection commits between the sweep's read and its delete meets the lock; the sweep drops every lapsed note", () => {
51 const then = new Date("2026-12-02T20:00:00Z");
52 for (const body of ["one", "two"])
53 expect(addNote(app.db, { repoId, authorId: aliceId, kind: "doing", body, now: then, ttlMs: 60_000 }).ok).toBe(true);
54 // A second connection to the same file, as the engine's is to the serving thread's.
55 const other = new Database(join(dir, "forge.db"));
56 other.exec("PRAGMA busy_timeout = 0");
57 let met = false;
58 const query = app.db.query.bind(app.db);
59 // Right after the sweep reads the lapsed notes, the other connection writes a note.
60 app.db.query = ((sql: string) => {
61 const statement = query(sql);
62 if (!sql.startsWith("SELECT repo_id, COUNT(*)")) return statement;
63 const all = statement.all.bind(statement);
64 return Object.assign(Object.create(statement), {
65 all: (...args: unknown[]) => {
66 const rows = (all as (...a: unknown[]) => unknown)(...args);
67 try {
68 other
69 .query(
70 "INSERT INTO desk_note (id, author_id, kind, body, created_at, expires_at, repo_id) VALUES ('other', ?1, 'doing', 'x', ?2, ?3, ?4)",
71 )
72 .run(aliceId, then.toISOString(), "2099-01-01T00:00:00Z", repoId);
73 } catch (error) {
74 if (!isBusy(error)) throw error;
75 met = true;
76 }
77 return rows;
78 },
79 });
80 }) as typeof app.db.query;
81 try {
82 expect(sweepDesk(app, new Date("2026-12-02T21:00:00Z"))).toBe(2);
83 } finally {
84 app.db.query = query;
85 other.close();
86 }
87 expect(met).toBe(true);
88 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs