opencode-self-improvement 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store/lock.ts CHANGED
@@ -8,28 +8,97 @@
8
8
  // before this module existed: 40 concurrent appends against 40 supersedes left
9
9
  // 40 rows on disk; four processes writing one store kept 20 of 120.
10
10
  //
11
- // One lock per store file, held across the whole read-modify-write. Appends take
12
- // the same lock so they cannot land inside an RMW window. Two layers, sharing
13
- // one timeout budget:
14
- // - a FIFO hand-off between async tasks in THIS process, so contending
15
- // writers take their turn instead of spinning;
16
- // - a lock FILE created with O_EXCL, which is atomic across processes (and
17
- // exclusive against our own tasks too, since the check is in the kernel).
18
- // A killed holder is recovered by age. A writer that waits past the budget
19
- // gives up waiting — see onTimeout (default: fail closed, #216).
11
+ // Two layers, sharing one timeout budget:
12
+ // - a FIFO hand-off between async tasks in THIS process, one queue per lock,
13
+ // so contending writers take their turn instead of spinning;
14
+ // - one SQLite database per lock, claimed with BEGIN IMMEDIATE and given back
15
+ // with ROLLBACK. SQLite's lock is a kernel byte-range lock — LockFileEx on
16
+ // Windows, fcntl F_SETLK on POSIX — so the lock lives in the kernel's
17
+ // handle table, not in a directory entry.
18
+ //
19
+ // Why this is not a lock file (#407). The previous protocol put the state of
20
+ // the lock in the EXISTENCE of a file and released it with unlink. On Windows
21
+ // that entry's lifetime is not ours to decide: DeleteFile marks a file for
22
+ // deletion on close and the name stays in the directory until the last handle
23
+ // closes, and a third-party handle (Defender real-time protection, the search
24
+ // indexer) opened without FILE_SHARE_DELETE makes the unlink fail outright.
25
+ // Either way an entry that means "held" can outlive the holder, and every later
26
+ // writer then waits out its budget and fails while nobody holds anything —
27
+ // reproduced on macOS by refusing unlink() alone, which POSIX cannot do. The
28
+ // handle-based alternatives are closed too: Bun ignores both UV_FS_O_EXLOCK and
29
+ // UV_FS_O_TEMPORARY on Windows (measured: a second open of the same path
30
+ // succeeds), and calling kernel32 LockFileEx through bun:ffi segfaulted Bun
31
+ // 1.4.4 on the CI runner, which settles that option by itself.
32
+ //
33
+ // SQLite removes the dependency instead of retrying around it. Nothing is
34
+ // created and nothing is deleted per acquisition: the lock transaction writes
35
+ // no page — BEGIN IMMEDIATE, then ROLLBACK — and SQLite only journals a
36
+ // transaction that dirties one, so the kernel byte-range lock on the database
37
+ // file IS the mutex. Measured: 50 lock cycles on a rollback-mode database
38
+ // leave exactly one file on disk and refuse a second connection SQLITE_BUSY;
39
+ // a killed holder is released by the kernel with its handles.
20
40
  //
21
41
  // Readers take NO lock: publishers hand over the new file with a rename
22
42
  // (writeAtomic in logfmt.ts), so a reader always sees a complete store, never
23
43
  // the middle of a rewrite.
24
- import { open, stat, unlink } from "node:fs/promises";
25
- import { basename, dirname } from "node:path";
44
+ //
45
+ // Supported storage. SQLite's locking is byte-range locks plus a journal it
46
+ // renames into place, and neither is dependable on network filesystems. A
47
+ // memory root on SMB, NFS or a OneDrive-mounted folder is therefore
48
+ // unsupported (#407): writes there can report a disk I/O error rather than
49
+ // serialise. That is a deliberate cut, not an oversight — the lock is the
50
+ // correctness mechanism for the whole store, so a silently unserialised store
51
+ // on a share was the worse option.
52
+ import { AsyncLocalStorage } from "node:async_hooks";
53
+ import { chmod, unlink } from "node:fs/promises";
54
+ import { basename, dirname, join } from "node:path";
55
+ import { Database } from "bun:sqlite";
26
56
  import { ensureDir } from "../core/logfmt/publish.ts";
27
57
  import { record } from "../evidence/record.ts";
28
58
 
29
- const LOCK_SUFFIX = ".lock";
30
- // A lock older than this belongs to a process that died holding it.
31
- const STALE_MS = 10_000;
32
- const DEFAULT_TIMEOUT_MS = 5_000;
59
+ /**
60
+ * The lock database for ONE store file: `.store-lock.<file>.sqlite`, beside it.
61
+ * It holds no rows and can be deleted whenever no session is writing: it is
62
+ * coordination state, not data. The name never matches the `*.logfmt` glob the
63
+ * store is scanned with, nor the `*.tmp` or `*.lock` shapes older releases left
64
+ * behind.
65
+ *
66
+ * Per file, not per directory. The directory shape was tried first and cost more
67
+ * than it saved. It makes every write in a store one queue — measured on macOS,
68
+ * eight concurrent sections on eight different files with a 150 ms hold: 153 ms
69
+ * under the old per-file lock file, 1218 ms under a per-directory SQLite lock —
70
+ * and `handoverRename` waits up to 2 s inside its section for a Windows reader
71
+ * to let go of the destination. Per file that wait blocks only that file's
72
+ * writers, which is what the handover's premise needs: while it waits, no other
73
+ * locked writer may move the destination. A lock that let one do so turned a
74
+ * stall into a lost write — measured on hosted Windows, where releasing the
75
+ * directory for the wait threw `EPERM` from the rename in 2 of 12 runs and made
76
+ * the suite red in 6 of 12.
77
+ *
78
+ * The cost is one database file per locked file, and nothing else: the lock
79
+ * transaction dirties no page, so a rollback-mode database never grows a
80
+ * journal, and it never runs in WAL mode where `-wal` and `-shm` would sit
81
+ * beside it for the life of every connection. `MAX_CACHED_LOCKS` bounds how
82
+ * many stay open.
83
+ *
84
+ * A writer never holds two store locks at once: the day-move loop in
85
+ * `store/files/append.ts` releases before it re-acquires, and sections run flat
86
+ * everywhere else. That is what keeps per-file locks from deadlocking. Batches
87
+ * take a distinct `.store-batch.<name>.sqlite`, always BEFORE the file locks
88
+ * their inner steps take, never after.
89
+ */
90
+ const lockDatabaseName = (file: string): string =>
91
+ `.store-lock.${basename(file)}.sqlite`;
92
+ const DEFAULT_TIMEOUT_MS = 10_000;
93
+ // The budget must exceed the worst LEGITIMATE wait, not just an idle section.
94
+ // A whole-file publish inside a section can spend 2000 ms in `handoverRename`
95
+ // retrying a rename Windows refuses while a reader holds the destination
96
+ // (src/core/logfmt/publish.ts) — and it holds the lock doing it, because the
97
+ // handover's premise is exclusion. Two such sections queued ahead of a writer
98
+ // are 4 s plus real work: measured on hosted Windows, a racing test's writer
99
+ // reported "locked for 5001ms" while the holder was mid-handover-retry, not
100
+ // wedged. 10 s still fails closed and reports, but stops refusing writes that
101
+ // were simply behind two honest retries.
33
102
  // #216: the default policy is fail-closed, the policy #196 moved every
34
103
  // production writer to. A writer that omits opts must refuse at the deadline,
35
104
  // not silently reintroduce the unlocked-proceed row loss the LOCK_WRITE
@@ -37,24 +106,23 @@ const DEFAULT_TIMEOUT_MS = 5_000;
37
106
  const DEFAULT_ON_TIMEOUT = "fail";
38
107
  const MIN_BACKOFF_MS = 1;
39
108
  const MAX_BACKOFF_MS = 25;
40
- // How many consecutive create-failures with a proven-absent lock file mean
41
- // "this filesystem is not letting us create it" rather than "we are losing a
42
- // race with a live holder". The wait is a fast, bounded spin, not a budget.
43
- const ABSENT_THROW_STRIKES = 8;
44
-
45
- // The single source of the timeout policy (#216): both give-up paths — the
46
- // direct budget and the queue hand-off — resolve through here, so the
47
- // fail-closed default cannot drift between them.
109
+ // Leaving a legacy WAL journal is a once-per-process-per-lock setup step, not
110
+ // the hot path, so it gets its own bound rather than the caller's budget.
111
+ const JOURNAL_CONVERT_BUDGET_MS = 5_000;
112
+
113
+ // The one source of the timeout policy (#216): both give-up paths — the FIFO
114
+ // hand-off and the SQLite wait — resolve through here, so the fail-closed
115
+ // default cannot drift between them.
48
116
  function timeoutPolicy(opts: LockOptions): "proceed" | "fail" {
49
117
  return opts.onTimeout === "proceed" ? "proceed" : DEFAULT_ON_TIMEOUT;
50
118
  }
51
119
 
52
- export function lockFileFor(file: string): string {
53
- return file + LOCK_SUFFIX;
54
- }
55
-
56
- /** Waiting past the timeout, or taking over a dead holder's lock. */
57
- export type LockEvent = "steal" | "timeout";
120
+ /**
121
+ * `timeout`: waited past the budget. `reset`: a release was refused, so the
122
+ * connection was thrown away. SQLite should never refuse a ROLLBACK, and if it
123
+ * does, the next writer must not inherit a half-open transaction from us.
124
+ */
125
+ export type LockEvent = "timeout" | "reset";
58
126
 
59
127
  export interface LockOptions {
60
128
  timeoutMs?: number;
@@ -89,6 +157,9 @@ export const LOCK_RESTORE: LockOptions = {
89
157
 
90
158
  const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
91
159
 
160
+ const busyMessage = (file: string, waitedMs: number): string =>
161
+ `memory store is busy: ${basename(file)} has been locked for ${waitedMs}ms — retry`;
162
+
92
163
  // Resolves when the task stored as this key has finished, handing the turn to
93
164
  // whoever queued after it.
94
165
  const turns = new Map<string, Promise<void>>();
@@ -103,188 +174,396 @@ async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
103
174
  return gained;
104
175
  }
105
176
 
106
- // The one probe that can answer "there is no holder" without itself being a
107
- // creation attempt: stat reports a held file happily (Windows shares metadata
108
- // reads with the handle owner), ENOENT — uniquely — proves absence, and any
109
- // other answer (an ACL that lets us neither create nor see, say) is no answer
110
- // at all: it must count as neither.
111
- type LockProbe = "present" | "absent" | "unknown";
177
+ /**
178
+ * Cached connections, least-recently-used first (Map iteration order is
179
+ * insertion order, so a touch is a delete plus a set).
180
+ *
181
+ * The cache exists because opening a connection is the expensive half of an
182
+ * acquisition, and a real process talks to one or two store directories. It must
183
+ * not grow without bound though: each connection holds file descriptors on the
184
+ * database, and a test suite that makes a temp store per test reaches hundreds.
185
+ * A long-lived opencode process never gets near that, but a CI runner with the
186
+ * common `ulimit -n 1024` would fail with EMFILE rather than with a useful
187
+ * assertion.
188
+ *
189
+ * So: evict only connections that are NOT holding a section, oldest first, and
190
+ * only past the cap. The cap counts LOCKED FILES now, not directories: a
191
+ * long-lived session touches today's day file, the ledger and canonical, while a
192
+ * prune sweeps the month. Sweeping past the cap costs a reopen per file, never
193
+ * correctness, because eviction skips anything in use. Closing is also what
194
+ * lets a test delete a store on Windows — a held handle keeps the file alive —
195
+ * and that is exactly why it happens on eviction and teardown, never per
196
+ * acquisition (#407 is about Windows refusing a delete we do not need to
197
+ * attempt).
198
+ */
199
+ interface Pinned {
200
+ db: Database;
201
+ /** Sections currently open on this connection; never evict while non-zero. */
202
+ inUse: number;
203
+ }
112
204
 
113
- async function probeLock(lockPath: string): Promise<LockProbe> {
114
- try {
115
- await stat(lockPath);
116
- return "present";
117
- } catch (probe) {
118
- return (probe as NodeJS.ErrnoException).code === "ENOENT"
119
- ? "absent"
120
- : "unknown";
205
+ const lockDbs = new Map<string, Pinned>();
206
+ const MAX_CACHED_LOCKS = 64;
207
+
208
+ function cacheLock(dbPath: string, db: Database): void {
209
+ lockDbs.set(dbPath, { db, inUse: 0 });
210
+ if (lockDbs.size <= MAX_CACHED_LOCKS) return;
211
+ for (const [path, pinned] of lockDbs) {
212
+ if (path === dbPath || pinned.inUse > 0) continue;
213
+ dropLockDatabase(path);
214
+ if (lockDbs.size <= MAX_CACHED_LOCKS) return;
121
215
  }
122
216
  }
123
217
 
124
- async function stealIfStale(lockPath: string, now: number): Promise<boolean> {
125
- let age = -1;
126
- try {
127
- age = now - (await stat(lockPath)).mtimeMs;
128
- } catch {
129
- // Age undeterminable — typically the holder finished and removed the
130
- // file a moment before this stat. "Not stealable" is the safe answer:
131
- // the caller backs off within the budget and the next create wins.
132
- // The old "retry the create immediately" here turned a stat that keeps
133
- // failing into a hot spin that never consulted the budget at all.
134
- return false;
218
+ /**
219
+ * Close every connection that is not holding a section.
220
+ *
221
+ * A cached connection is an open file, and Windows will not delete a directory
222
+ * that contains one. Deleting a store is a supported operation — the README
223
+ * tells a user to reset their memories that way, and every test fixture tears
224
+ * its store down that way — so the process needs a way to say "I am done with
225
+ * stores". A real caller stops its sessions first; the test helper
226
+ * `removeStore` calls this before `rmSync`.
227
+ *
228
+ * Connections inside a section are left alone: closing one would give up a lock
229
+ * its writer still believes it holds.
230
+ */
231
+ export function closeAllLockDatabases(): void {
232
+ for (const [dbPath, pinned] of [...lockDbs]) {
233
+ if (pinned.inUse > 0) continue;
234
+ dropLockDatabase(dbPath);
135
235
  }
136
- if (age < STALE_MS) return false;
137
- try {
138
- await unlink(lockPath);
139
- } catch {
140
- return false; // another stealer won; its create decides
236
+ }
237
+
238
+ process.on("exit", closeAllLockDatabases);
239
+
240
+ /**
241
+ * The locks THIS CALL CHAIN already holds. Nesting a section inside one it
242
+ * already holds joins the outer transaction instead of starting a second one on
243
+ * the same connection, which SQLite refuses.
244
+ *
245
+ * It has to be an async-context set, not a Map keyed by lock. A Map is
246
+ * process-wide, so a task that merely happens to run while an UNRELATED task
247
+ * holds a lock reads "already held" and writes with no lock at all — measured:
248
+ * the sibling-holder test in test/lock-narrowing.test.ts resolved instead of
249
+ * refusing, which is silent data loss and worse than the bug this module fixes.
250
+ * AsyncLocalStorage scopes the set to the chain that acquired it, so a nested
251
+ * call inherits and a sibling does not. Verified on Bun 1.4.3 across deep await
252
+ * chains, Promise.all siblings, Promise.race and unwinding.
253
+ */
254
+ const heldLocks = new AsyncLocalStorage<ReadonlySet<string>>();
255
+
256
+ /**
257
+ * Is this error "someone else holds it, ask again"? The distinction is
258
+ * load-bearing: contention is waited for, anything else is thrown, because
259
+ * waiting on a broken lock wastes five seconds and then refuses a write that
260
+ * was never going to succeed.
261
+ *
262
+ * Match the whole busy FAMILY, not just SQLITE_BUSY. SQLite reports extended
263
+ * codes for the specific kinds of wait — BUSY_RECOVERY when another connection
264
+ * is recovering a write-ahead log (a legacy WAL lock database mid-conversion
265
+ * can still surface it), BUSY_SNAPSHOT when a read transaction has to restart,
266
+ * BUSY_TIMEOUT — and Bun puts the EXTENDED number on `errno` (261, not 5) with
267
+ * the extended NAME on `code`. Comparing against plain SQLITE_BUSY therefore
268
+ * made the one situation this lock is supposed to survive — a wait that names
269
+ * itself an extension of busy — fatal: a writer got "store lock unavailable:
270
+ * database is locked" instead of waiting the few hundred microseconds the other
271
+ * side needs. Measured on test/scenarios-consistency.test.ts, which kills
272
+ * racers mid-write.
273
+ *
274
+ * SQLITE_BUSY is 5 and every extension is 5 | (kind << 8), so the low byte is
275
+ * the class.
276
+ */
277
+ function contention(err: unknown): boolean {
278
+ const e = err as { code?: string; errno?: number } | null;
279
+ if (typeof e?.code === "string") {
280
+ return e.code === "SQLITE_BUSY" || e.code.startsWith("SQLITE_BUSY_");
141
281
  }
142
- return true;
282
+ return typeof e?.errno === "number" && (e.errno & 0xff) === 5;
143
283
  }
144
284
 
145
285
  /**
146
- * Cross-process half: hold the lock file while `fn` runs. `now` is a seam for
147
- * tests that must land the budget deadline inside a specific probe iteration;
148
- * production callers never pass it and the real clock is used.
286
+ * The class that means "the file this connection holds is gone or was replaced
287
+ * underneath us", rather than "the disk is refusing writes".
288
+ *
289
+ * SQLite detects the case exactly: SQLITE_IOERR_VNODE is reported when the inode
290
+ * behind an open handle changes. It is reachable without a defect — the store
291
+ * directory is not ours to protect. A user can wipe and rebuild a memory root
292
+ * while a session is alive, and test/hits.test.ts does it on purpose. The right
293
+ * answer is to throw the stale connection away and open a fresh one, which is
294
+ * what a handle against a replaced file needs; the wrong answer is to wait, and
295
+ * the other wrong answer is to keep the poisoned connection and fail every later
296
+ * write in the store.
297
+ *
298
+ * Repair is attempted ONCE per acquisition. A disk that genuinely cannot do I/O
299
+ * fails the second time and the error surfaces, so this never turns a real
300
+ * storage failure into a loop.
149
301
  */
302
+ function staleHandle(err: unknown): boolean {
303
+ const e = err as { code?: string; errno?: number } | null;
304
+ if (typeof e?.code === "string") return e.code.startsWith("SQLITE_IOERR");
305
+ // SQLITE_IOERR is 10 and its extensions keep the class in the low byte.
306
+ return typeof e?.errno === "number" && (e.errno & 0xff) === 10;
307
+ }
308
+
150
309
  /**
151
- * Test seam (#215): observe how many store files a write path locks.
310
+ * The classifier above, exposed for its pin in test/lock.test.ts.
152
311
  *
153
- * The narrowing this ticket asked for is invisible to a functional test — a
154
- * supersede that sweeps every day file and one that touches a single file both
155
- * leave the same store behind — so the assertion has to be about lock
156
- * acquisitions. Production never installs a hook and pays one undefined check
157
- * per acquisition; a test sets one, reads the counts, and clears it.
312
+ * Getting this one line wrong is what made a crashed holder fatal, and the
313
+ * integration test for it is probabilistic: whether a second opener arrives
314
+ * while recovery is still running depends on scheduling. The classification
315
+ * itself is not probabilistic, so it gets a table.
158
316
  */
159
- let acquiredHook: ((file: string) => void) | undefined;
317
+ export const isLockContention = contention;
318
+ /** Test seam for the stale-handle classification in test/lock.test.ts. */
319
+ export const isStaleLockHandle = staleHandle;
160
320
 
161
- export function setLockAcquiredHook(hook?: (file: string) => void): void {
162
- acquiredHook = hook;
321
+ /**
322
+ * The store's privacy contract is owner-only files (README: new files 0600).
323
+ * SQLite creates its own with the process umask, so it is tightened. A refused
324
+ * chmod is not worth failing a write over: it is the same concession the
325
+ * README already makes for a root that reports EPERM.
326
+ */
327
+ async function harden(dbPath: string): Promise<void> {
328
+ await chmod(dbPath, 0o600).catch(() => undefined);
163
329
  }
164
330
 
165
- export async function holdFileLock<T>(
166
- lockPath: string,
331
+ async function lockDatabase(dbPath: string): Promise<Database> {
332
+ const cached = lockDbs.get(dbPath);
333
+ if (cached) {
334
+ // Touch: this directory is in use, so it moves to the protected end of the
335
+ // eviction order.
336
+ lockDbs.delete(dbPath);
337
+ lockDbs.set(dbPath, cached);
338
+ return cached.db;
339
+ }
340
+ await ensureDir(dirname(dbPath));
341
+ let db: Database;
342
+ try {
343
+ db = new Database(dbPath);
344
+ } catch (err) {
345
+ // SQLite flattens a refused open to "unable to open database file" and
346
+ // drops the errno, so a store the user cannot write to — an ACL denial on
347
+ // Windows, a read-only mount, a full disk — would report a mystery instead
348
+ // of a cause. Name the file and the code; this is not contention, so it
349
+ // must surface at once rather than decay into the wait below.
350
+ const info = err as { code?: string };
351
+ throw new Error(
352
+ `[${info.code ?? "SQLITE_CANTOPEN"}] store lock cannot open ${dbPath}: ${(err as Error).message}`,
353
+ );
354
+ }
355
+ try {
356
+ // Before anything that can be refused: SQLite's own wait sleeps inside C
357
+ // and would park the host's event loop for up to busy_timeout. The wait
358
+ // policy stays ours — async, bounded, and sharing one budget with the FIFO
359
+ // hand-off above.
360
+ db.run("PRAGMA busy_timeout = 0");
361
+ await ensureLockJournal(db, dbPath);
362
+ } catch (err) {
363
+ db.close();
364
+ throw err;
365
+ }
366
+ cacheLock(dbPath, db);
367
+ await harden(dbPath);
368
+ return db;
369
+ }
370
+ const journalMode = (db: Database): string =>
371
+ String(
372
+ (db.query("PRAGMA journal_mode").get() as { journal_mode?: string } | null)
373
+ ?.journal_mode ?? "",
374
+ ).toLowerCase();
375
+
376
+ /**
377
+ * Keep the lock database in rollback journal mode, converting a legacy WAL one,
378
+ * and refuse a database that will not convert.
379
+ *
380
+ * The lock transaction dirties no page — BEGIN IMMEDIATE then ROLLBACK — and
381
+ * SQLite only creates a journal when a transaction has something to undo. So
382
+ * rollback mode is the quiet shape: one file per lock, created once, never
383
+ * journalled, never sidecar'd. WAL was the original choice on the theory that
384
+ * a journal file per acquisition is the exact Windows churn this module exists
385
+ * to avoid; the theory is wrong for a zero-write transaction, and WAL pays for
386
+ * nothing: `-wal` and `-shm` appear beside every lock while a connection is
387
+ * open, three Defender-visible files per lock on Windows instead of one, plus a
388
+ * first-open conversion race that needs its own retry budget.
389
+ *
390
+ * Converting a legacy WAL database takes the exclusive lock for a moment, and
391
+ * a metadata read against a database another connection holds can be refused
392
+ * with SQLITE_BUSY, so this setup step keeps the retry. A database that cannot
393
+ * LEAVE WAL is refused rather than run that way: the sidecar churn would come
394
+ * back per store, silently.
395
+ */
396
+ async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
397
+ let backoff = MIN_BACKOFF_MS;
398
+ let waited = 0;
399
+ for (;;) {
400
+ const step = Date.now();
401
+ try {
402
+ const mode = journalMode(db);
403
+ if (mode === "delete") return;
404
+ db.run("PRAGMA journal_mode = DELETE");
405
+ if (journalMode(db) === "delete") {
406
+ // The conversion checkpoints and removes `-wal`, but `-shm` only goes
407
+ // when the LAST WAL connection closes — and this connection, converted
408
+ // in place, does not close. Remove the orphan here: the exclusive lock
409
+ // the conversion just took means nobody is inside the WAL system, and a
410
+ // connection opened after it reads delete mode and never maps `-shm`.
411
+ // Best-effort: a refused unlink leaves a harmless orphan, and forcing
412
+ // the issue is the Windows delete this module exists to avoid.
413
+ await unlink(`${dbPath}-wal`).catch(() => undefined);
414
+ await unlink(`${dbPath}-shm`).catch(() => undefined);
415
+ return;
416
+ }
417
+ } catch (err) {
418
+ if (!contention(err)) {
419
+ const info = err as { code?: string; errno?: number };
420
+ throw new Error(
421
+ `[code=${info.code ?? "-"} errno=${info.errno ?? "-"}] store lock cannot set rollback journal mode for ${dbPath}: ${(err as Error).message}`,
422
+ );
423
+ }
424
+ }
425
+ await sleep(backoff);
426
+ waited += Date.now() - step;
427
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
428
+ if (waited >= JOURNAL_CONVERT_BUDGET_MS) {
429
+ throw new Error(
430
+ `store lock could not leave write-ahead journal mode for ${dbPath} after ${waited}ms — another process is holding the lock database in a state that refuses it`,
431
+ );
432
+ }
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Drop the connection for a lock. Used when a release fails: a connection that
438
+ * refused ROLLBACK may still hold SQLite's write lock, and the next writer must
439
+ * get a fresh one rather than inherit our transaction.
440
+ */
441
+ function dropLockDatabase(dbPath: string): void {
442
+ const pinned = lockDbs.get(dbPath);
443
+ if (!pinned) return;
444
+ lockDbs.delete(dbPath);
445
+ try {
446
+ pinned.db.close();
447
+ } catch {
448
+ // Already gone. A leaked handle is strictly better than a stuck one.
449
+ }
450
+ }
451
+
452
+ /**
453
+ * Cross-process half: hold the lock while `fn` runs. `now` is a seam for tests
454
+ * that must land the deadline inside a specific wait iteration; production
455
+ * callers never pass it and the real clock is used.
456
+ */
457
+ async function holdLock<T>(
458
+ dbPath: string,
167
459
  file: string,
168
460
  fn: () => Promise<T>,
169
461
  opts: LockOptions,
170
462
  budgetMs: number,
171
463
  now: () => number = Date.now,
172
464
  ): Promise<T> {
173
- await ensureDir(dirname(lockPath));
174
- const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
465
+ let db = await lockDatabase(dbPath);
175
466
  const started = now();
176
467
  let backoff = MIN_BACKOFF_MS;
177
- let firstErr: unknown;
178
- let absentStrikes = 0;
179
- // #107: did ANY probe see a lock file during this wait? The rethrow at the
180
- // deadline promises we never proceed as a stranger to the lock file — but
181
- // `absentStrikes > 0` only remembers the LAST probe, so a holder that
182
- // legitimately finished and unlinked just as the budget expired was
183
- // throwing away ordinary writes instead of taking the contention
184
- // concession it describes. An EEXIST from a failed create counts as such a
185
- // sighting too (a create that returns EEXIST saw the file).
186
- let everSawHolder = false;
468
+ let reconnected = false;
187
469
  for (;;) {
188
470
  try {
189
- const handle = await open(lockPath, "wx", 0o600);
190
- try {
191
- await handle.write(token);
192
- } finally {
193
- await handle.close();
194
- }
195
- acquiredHook?.(file);
471
+ db.run("BEGIN IMMEDIATE");
196
472
  break;
197
473
  } catch (err) {
198
- // Any creation failure means: wait for the current holder, whatever
199
- // label it carries (POSIX EEXIST; Windows sharing violations EPERM/
200
- // EACCES; or the file vanishing between this open and any later probe
201
- // — the holder simply finished). Policies that trusted a label or a
202
- // one-shot probe were tried and lost rows: throwing on non-EEXIST
203
- // aborted writers on mislabelled contention, and throwing on a
204
- // stat-probe ENOENT aborted them in the vanish race.
205
- // The filesystem still gets the last word: if creation keeps failing
206
- // while stat keeps proving NO lock file exists, there is no holder to
207
- // wait for — our own ability to create files is what is broken, and
208
- // the original error must surface instead of rotting into a timeout.
209
- firstErr ??= err;
210
- // An EEXIST from the create is a sighting in its own right: on POSIX it
211
- // proves the lock file WAS there at the attempt, even if the probe
212
- // below then proves the holder unlinked in between (the vanish race).
213
- // Without this, that race reached the deadline with everSawHolder false
214
- // and surfaced the stale creation error instead of the busy refusal.
215
- // Ambiguous labels (the Windows EPERM/EACCES family) stay non-sightings
216
- // — blindness is blindness (#107) — and a create-yes/stat-no filesystem
217
- // still dies on the strike rule long before the budget.
218
- if ((err as NodeJS.ErrnoException).code === "EEXIST")
219
- everSawHolder = true;
220
- const seen = await probeLock(lockPath);
221
- if (seen === "absent") {
222
- if (++absentStrikes >= ABSENT_THROW_STRIKES) throw firstErr;
223
- } else {
224
- absentStrikes = 0;
225
- if (seen === "present") everSawHolder = true;
226
- }
227
- if (await stealIfStale(lockPath, now())) {
228
- opts.onEvent?.("steal", now() - started);
229
- continue;
474
+ if (!contention(err)) {
475
+ if (staleHandle(err) && !reconnected) {
476
+ // The store directory was rebuilt under this handle. Repair once and
477
+ // try again on a fresh connection; a second failure surfaces.
478
+ reconnected = true;
479
+ dropLockDatabase(dbPath);
480
+ db = await lockDatabase(dbPath);
481
+ continue;
482
+ }
483
+ const info = err as { code?: string; errno?: number };
484
+ throw new Error(
485
+ `[code=${info.code ?? "-"} errno=${info.errno ?? "-"}] store lock unavailable for ${basename(file)}: ${(err as Error).message}`,
486
+ );
230
487
  }
231
488
  if (now() - started >= budgetMs) {
232
489
  opts.onEvent?.("timeout", now() - started);
233
- // Blindness outranks policy (#107): a wait that never once saw a lock
234
- // file has no holder to wait for — our own ability to create files is
235
- // what is broken, and the original error must surface, never a busy
236
- // refusal and never an unguarded write.
237
- if (!everSawHolder) throw firstErr;
238
490
  if (timeoutPolicy(opts) === "fail") {
239
- throw new Error(
240
- `memory store is busy: ${basename(file)} has been locked for ${now() - started}ms — retry`,
241
- );
491
+ throw new Error(busyMessage(file, now() - started));
242
492
  }
243
493
  // Proceeding without the lock is the explicit "proceed" opt-in
244
- // (#216: no longer the default). A holder we DID see and then lost is
245
- // ordinary contention, and belongs to the opt-in (#107 —
246
- // `absentStrikes > 0` remembered only the last probe, not the wait).
247
- return fn();
494
+ // (#216: no longer the default). heldLocks is deliberately NOT touched
495
+ // here: a writer that never held the lock must not let a nested call
496
+ // believe it did.
497
+ return await fn();
248
498
  }
249
499
  await sleep(backoff);
250
500
  backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
251
501
  }
252
502
  }
503
+ await harden(dbPath);
504
+ acquiredHook?.(file);
505
+ // Protected from eviction for as long as the section runs: closing a
506
+ // connection here would hand the next writer a different transaction and
507
+ // silently drop the exclusion this section exists to provide.
508
+ const pinned = lockDbs.get(dbPath);
509
+ if (pinned) pinned.inUse++;
510
+ const parent = heldLocks.getStore();
511
+ const held = new Set(parent ?? []);
512
+ held.add(dbPath);
253
513
  try {
254
- return await fn();
514
+ return await heldLocks.run(held, fn);
255
515
  } finally {
256
- // Never release a lock that is no longer ours: if we ran long and someone
257
- // stole it, unlinking would clobber the new holder.
516
+ if (pinned) pinned.inUse--;
258
517
  try {
259
- if ((await Bun.file(lockPath).text()) === token) await unlink(lockPath);
260
- } catch {
261
- // already gone
518
+ db.run("ROLLBACK");
519
+ } catch (err) {
520
+ dropLockDatabase(dbPath);
521
+ opts.onEvent?.("reset", now() - started);
522
+ void err;
262
523
  }
263
524
  }
264
525
  }
265
526
 
266
527
  /**
267
- * Run `fn` as the only writer of `file`, in this process and every other one.
268
- * Sections run flat: calling this again for the same file from inside `fn`
269
- * waits for its own lock.
528
+ * The shared shape of both public entry points: wait our turn in this process,
529
+ * then take the cross-process lock, on one budget.
270
530
  */
271
- export async function withStoreLock<T>(
531
+ async function acquire<T>(
532
+ dbPath: string,
272
533
  file: string,
273
534
  fn: () => Promise<T>,
274
- opts: LockOptions = {},
535
+ opts: LockOptions,
275
536
  ): Promise<T> {
276
537
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
277
538
  const started = Date.now();
278
- const lockPath = lockFileFor(file);
539
+
540
+ if (busyInjector?.(file)) {
541
+ // Reported exactly as a waited-out budget would report it, so a test that
542
+ // injects a refusal exercises the same policy and message as a real one.
543
+ opts.onEvent?.("timeout", 0);
544
+ if (timeoutPolicy(opts) === "fail") {
545
+ throw new Error(busyMessage(file, 0));
546
+ }
547
+ return fn();
548
+ }
549
+
550
+ if (heldLocks.getStore()?.has(dbPath)) {
551
+ // Same call chain, same lock: the outer section already excludes everyone
552
+ // else, so re-entering neither starts a second transaction nor queues
553
+ // behind the FIFO the outer section owns. The hook still fires — it counts
554
+ // which store files a write path touches (#215), and this path touched one.
555
+ acquiredHook?.(file);
556
+ return await fn();
557
+ }
279
558
 
280
559
  let releaseTurn!: () => void;
281
560
  const myTurnEnded = new Promise<void>((res) => (releaseTurn = res));
282
- const queuedBehind = turns.get(file);
283
- turns.set(file, myTurnEnded);
561
+ const queuedBehind = turns.get(dbPath);
562
+ turns.set(dbPath, myTurnEnded);
284
563
 
285
564
  const finish = () => {
286
565
  releaseTurn();
287
- if (turns.get(file) === myTurnEnded) turns.delete(file);
566
+ if (turns.get(dbPath) === myTurnEnded) turns.delete(dbPath);
288
567
  };
289
568
 
290
569
  if (queuedBehind) {
@@ -295,17 +574,15 @@ export async function withStoreLock<T>(
295
574
  finish();
296
575
  opts.onEvent?.("timeout", Date.now() - started);
297
576
  if (timeoutPolicy(opts) === "fail") {
298
- throw new Error(
299
- `memory store is busy: ${basename(file)} has been locked for ${Date.now() - started}ms — retry`,
300
- );
577
+ throw new Error(busyMessage(file, Date.now() - started));
301
578
  }
302
579
  return fn();
303
580
  }
304
581
  }
305
582
 
306
583
  try {
307
- return await holdFileLock(
308
- lockPath,
584
+ return await holdLock(
585
+ dbPath,
309
586
  file,
310
587
  fn,
311
588
  opts,
@@ -315,3 +592,100 @@ export async function withStoreLock<T>(
315
592
  finish();
316
593
  }
317
594
  }
595
+
596
+ /**
597
+ * Test seam (#197): refuse the acquisition of chosen files.
598
+ *
599
+ * The tests that pin "a batch that published file 1 and then lost file 2 must
600
+ * report file 1 as durable" need a refusal at a chosen point in a sequence.
601
+ * Under the lock file a test could hold one day file and let the batch reach
602
+ * the next one. The lock is per file again (#407 round two), so that driver
603
+ * exists again; this seam remains for the cases that need a refusal at a chosen
604
+ * step rather than a rival that holds a file.
605
+ *
606
+ * The refusal is injected where a real one surfaces — the acquisition of the
607
+ * named file, through the same timeout policy and the same busy message a
608
+ * cross-process holder produces — so the reporting path under test is the real
609
+ * one. Real cross-process refusal is pinned separately in lock.test.ts and
610
+ * lock-write-timeout.test.ts, which is what keeps this seam honest.
611
+ *
612
+ * Production never installs an injector and pays one undefined check.
613
+ */
614
+ let busyInjector: ((file: string) => boolean) | undefined;
615
+
616
+ export function setLockBusyInjector(
617
+ injector?: (file: string) => boolean,
618
+ ): void {
619
+ busyInjector = injector;
620
+ }
621
+
622
+ /**
623
+ * Run `fn` as the only writer of `file`, in this process and every other one.
624
+ *
625
+ * The lock covers that one file, so writers of different day files in the same
626
+ * store do not wait on each other. A call nested inside a section this chain
627
+ * already holds joins it.
628
+ */
629
+ export async function withStoreLock<T>(
630
+ file: string,
631
+ fn: () => Promise<T>,
632
+ opts: LockOptions = {},
633
+ ): Promise<T> {
634
+ return acquire(lockDatabaseFor(file), file, fn, opts);
635
+ }
636
+
637
+ /**
638
+ * Run `fn` under a lock of its own, named for a batch operation, WITHOUT
639
+ * excluding the store's day-file writers.
640
+ *
641
+ * This exists because memory_update and memory_merge_review serialize a whole
642
+ * read-gate-supersede sequence, and the inner steps take the day-file lock
643
+ * themselves. Their modules state the contract: the outer lock is "a DISTINCT
644
+ * file from anything runWriteGate or markSuperseded take (sections run flat)".
645
+ * Folding the batch into the file lock would hold the store-wide
646
+ * transaction for the entire gate and make every other session wait it out, so
647
+ * the batch keeps its own database. The acquisition order stays batch-then-file,
648
+ * never the reverse, which is what keeps the two from deadlocking.
649
+ */
650
+ export async function withStoreBatch<T>(
651
+ root: string,
652
+ name: string,
653
+ fn: () => Promise<T>,
654
+ opts: LockOptions = {},
655
+ ): Promise<T> {
656
+ return acquire(join(root, `.store-batch.${name}.sqlite`), name, fn, opts);
657
+ }
658
+
659
+ /**
660
+ * Test seam (#215): observe how many store files a write path locks.
661
+ *
662
+ * The narrowing this ticket asked for is invisible to a functional test — a
663
+ * supersede that sweeps every day file and one that touches a single file both
664
+ * leave the same store behind — so the assertion has to be about lock
665
+ * acquisitions. Production never installs a hook and pays one undefined check
666
+ * per acquisition; a test sets one, reads the counts, and clears it.
667
+ */
668
+ let acquiredHook: ((file: string) => void) | undefined;
669
+
670
+ export function setLockAcquiredHook(hook?: (file: string) => void): void {
671
+ acquiredHook = hook;
672
+ }
673
+
674
+ /** The lock database path for a store file. For diagnostics and tests. */
675
+ export function lockDatabaseFor(file: string): string {
676
+ return join(dirname(file), lockDatabaseName(file));
677
+ }
678
+
679
+ /**
680
+ * Test seam: the lock databases this process holds a handle to right now.
681
+ *
682
+ * The handle is the Windows-visible part of this design. Windows will not
683
+ * delete a directory containing an open file, so a connection kept after the
684
+ * last writer finishes turns "delete your store to reset it" into EBUSY, and
685
+ * the test suite's temp directories into failures. That cannot be observed
686
+ * portably by trying to delete the file — POSIX allows it either way — so the
687
+ * seam reports the handle set directly.
688
+ */
689
+ export function heldLockDatabases(): string[] {
690
+ return [...lockDbs.keys()];
691
+ }