opencode-model-router 1.14.0 → 2.0.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.
@@ -0,0 +1,1603 @@
1
+ /**
2
+ * Machine-wide verification slot (S3): a cross-process counting semaphore.
3
+ *
4
+ * At most `max` verification commands run at a time across every opencode
5
+ * process on the machine. Each held slot is a lock file
6
+ * `<tmp>/opencode-model-router/verify-slots/slot-<i>.lock`, created with
7
+ * `open(path, "wx")` (atomic create-or-fail on NTFS and ext4, see the Phase 1.4
8
+ * pre-flight) and holding `{pid, hostname, token, startedAt, cwd, command}`.
9
+ * The creator re-reads the file after writing it and holds the slot only if its
10
+ * own token is there (a creator stalled between the create and the write may
11
+ * have been reaped as an empty file).
12
+ *
13
+ * Clock. Every duration is measured on `mono`, a machine clock in ms. The one
14
+ * counter that every process of a boot reads alike, on every runtime, is the OS
15
+ * uptime (`os.uptime()`): GetTickCount64 on Windows (15.6 ms steps; Node 24 and
16
+ * Bun 1.3 read the same `wall - uptime` within 15 ms), CLOCK_BOOTTIME on Linux,
17
+ * the wall clock minus the boot time on macOS. Some runtimes round it to whole
18
+ * seconds. `process.hrtime` is not such a counter everywhere: Node reads a boot
19
+ * clock (QueryPerformanceCounter, CLOCK_MONOTONIC, mach time), but Bun, the
20
+ * runtime that loads opencode plugins, counts from the process start (a fresh Bun
21
+ * process reads about 0.4 s). So at its first use each process takes `hrtime` as
22
+ * is when it reads within 2 s of the uptime, and otherwise anchors it to the
23
+ * uptime: `mono = hrtime + max(uptime - hrtime)` over its reads. That never goes
24
+ * back, is as fine as `hrtime` within the process, and agrees with the other
25
+ * processes within the uptime's resolution; after a suspend that the uptime counts
26
+ * and `hrtime` does not, it jumps ahead with the uptime. Whether the clocks count
27
+ * a Windows sleep is not documented, and Modern Standby pauses desktop processes
28
+ * while every clock runs, so no rule assumes that the clock stops while the
29
+ * processes are frozen (see "witnessed"). The wall clock is compared with file
30
+ * mtimes, and it tells clock origins apart (below); nothing else.
31
+ *
32
+ * Shared observation. Staleness needs a file to be seen unchanged over time, and
33
+ * one call may be too short for that (`slotWaitMs: 0`). So every look is
34
+ * recorded in a sidecar `slot-<i>.lock.seen-<hash(file, identity, host)>` holding
35
+ * the file's `key` (identity@mtime) and one view per clock origin, `{boot, bootAt,
36
+ * slack, first, from, last}`, with stamps on that origin's `mono`. A look's origin
37
+ * is its boot (the Linux boot id) and its boot instant `bootAt = wall - mono`, read
38
+ * together. A look uses the view of its boot whose `bootAt` is within its slack
39
+ * (1 s, the uptime's resolution budget; a fifth of the heartbeat when that is
40
+ * shorter, in tests) of its own, or starts a new view, and compares its `mono`
41
+ * with that view's stamps only. So clocks with different
42
+ * origins never mix: Bun's per-process `hrtime` if it were used, a process whose
43
+ * `hrtime` stopped during a suspend, a wall-clock step. Two stamps of one view
44
+ * disagree by at most the two slacks (the look's and the largest of the view's
45
+ * writers', 2 s), and every `mono` threshold below adds that, so it never shortens
46
+ * a margin. `first` is the view's first sighting of the key, `last` its latest
47
+ * look, and `from` the first look after the latest gap between two looks of more
48
+ * than 2 heartbeats minus this look's slack and the view's (8 s in production:
49
+ * 2 x 5 s - 2 x 1 s). So `span = now - first` is how long the file has been
50
+ * unchanged, and `witnessed = now - from` how long it has been watched without a
51
+ * gap. A new key drops every view; a stamp from the future (another boot's clock)
52
+ * restarts one. The host is part of the name, so hosts sharing a dir never mix
53
+ * clocks. A stamp that survives a reboot can only be for a file whose holder died
54
+ * with the reboot (tokens are never reused). Sidecar I/O is advisory: a failure
55
+ * only loses evidence, which delays a reclaim and never causes one.
56
+ *
57
+ * Staleness. The holder refreshes its file's mtime every `heartbeatMs` (5 s,
58
+ * unref'd timer). A lock is stale when
59
+ * (a) its host is this host and its PID is dead (immediately), or this process
60
+ * created it and never held it (below, "Errors"), or
61
+ * (b) it is old (its heartbeat is older than `staleMs`, 30 s, by the wall
62
+ * clock, or its span is at least `staleMs`) AND it has been witnessed
63
+ * unchanged for 2 heartbeats (both plus the view's slack).
64
+ * A suspend, a freeze or a clock step makes a live holder's file look old. But
65
+ * the holder heartbeats within one interval once it runs again, which changes the
66
+ * key, and a gap in the looks (everyone was frozen, or nobody looked) restarts
67
+ * the witness, so the holder always gets 2 heartbeats of running time first. A
68
+ * foreign host is never judged by PID. A corrupt/empty lock uses the short
69
+ * `corruptGraceMs` for both the age and the witness, because a creator writes the
70
+ * JSON right after the exclusive create.
71
+ *
72
+ * Watch. A call that gives up at its deadline while a lock is old but not yet
73
+ * witnessed long enough keeps looking at it in the background, every heartbeat
74
+ * (unref'd timer), until the lock is reaped or changes, or for at most
75
+ * `staleMs + 2 x (heartbeatMs + claimHoldMaxMs)`. So a process calling with
76
+ * `waitMs: 0` once a minute still reclaims a lock whose owner is not provably
77
+ * dead (a reused PID, another host, a hung holder). Short-lived processes that
78
+ * each look once do it through the sidecar when their looks are less than 2
79
+ * heartbeats minus this look's slack and the view's apart (8 s in production: 2 x 5 s - 2 x 1 s),
80
+ * and their clocks share a view.
81
+ *
82
+ * Residual (accepted in QA-1.4-21): looks further apart than that (8 s) cannot
83
+ * tell a dead holder from a frozen machine. So a lock whose owner is not provably
84
+ * dead is reclaimed only by a caller that waits, or stays alive, for 2 heartbeats
85
+ * after its look (10 s plus the slack), or by callers that look often enough
86
+ * together. Until then every caller is told busy. The Phase 2.x callers are
87
+ * opencode plugin processes, alive for a whole session, so their watches do it.
88
+ *
89
+ * Deletion. Every delete of a lock file whose identity is K (its token; for a
90
+ * corrupt file its mtime and size) runs under the claim file
91
+ * `slot-<i>.lock.reap-<hash(K)>`, created with `wx` and holding `{pid, hostname,
92
+ * token, target, victim: K}`. That includes the owner's own release and the exit
93
+ * hook. A claimer holds its claim only after a readable re-read shows its own
94
+ * token; an unconfirmed claim is never used and is left to the rules below. The
95
+ * claim holder re-reads the target before every unlink attempt and deletes it
96
+ * only while it is still K. K is never reused and only a K-claim holder deletes
97
+ * K's file, so the file cannot be deleted and re-created between the re-read and
98
+ * the unlink (no ABA). A claim is removed by its owner. A crashed claimer's claim
99
+ * is removed the same way, under the claim for *its* token, when its owner is
100
+ * provably dead (same host, dead PID) or when it is inert: span >= `staleMs` AND
101
+ * witnessed >= 2 x `claimHoldMaxMs` (both plus the view's slack). The wall clock
102
+ * plays no part, because claims are never refreshed. A claimer deletes its target
103
+ * only within `claimHoldMaxMs` (5 s) of `mono`, counted from just before it
104
+ * created the claim, and checked again right before each unlink, and drops its
105
+ * own claim only within 1.5 x that (7.5 s). That includes a claim it created but
106
+ * could not confirm (a scanner held the re-read): the process remembers its token
107
+ * and drops it at its next readable look within those 7.5 s, and at exit only within them too (QA-1.4-32); after
108
+ * that it is left to the rules above. So a claimer acts on a claim judged inert
109
+ * only if it freezes for more than 25 s (target) or 22.5 s (drop) between that
110
+ * last check and the unlink syscall; when every process was frozen together, the
111
+ * witness gives it 10 s of running time after the thaw. Transient
112
+ * antivirus/indexer errors (EBUSY/EPERM/EACCES) are retried, and a failed delete
113
+ * is never reported as success.
114
+ *
115
+ * Fairness. A caller that waits files a ticket `wait-<startedAt>-<uuid>.ticket`
116
+ * (`{pid, hostname, token}`), refreshes it every heartbeat (unref'd timer) and on
117
+ * every wake-up, and tries the slots only while fewer than `max` live tickets are
118
+ * older than its own. That is strict FIFO for max=1; for max>1 the `max` oldest
119
+ * waiters compete. A caller that does not wait defers while `max` live tickets
120
+ * exist, so a releaser that re-acquires at once queues behind the waiters. A
121
+ * ticket is dead when its PID is dead (same host), or when it has not been
122
+ * refreshed for 2 heartbeats (by its mtime, or seen unchanged that long by this
123
+ * process). A live PID proves nothing, because PIDs are reused. A live waiter
124
+ * misjudged dead re-creates its ticket under its old name at its next refresh.
125
+ * Tickets only order the attempts: exclusion never depends on them, and a ticket
126
+ * I/O failure lets the caller try.
127
+ *
128
+ * Housekeeping. At most every 10 minutes per dir, a caller deletes orphaned files
129
+ * older than 1 hour. Probes, observation sidecars and the legacy `.reap` and
130
+ * `.reap.dead-*` files go by path, since they are unique or advisory. Claims go
131
+ * under the claim protocol when their target no longer holds their victim or when
132
+ * they are empty/corrupt. A claim without `target`/`victim` is left alone.
133
+ *
134
+ * Loss. When the heartbeat finds the holder's file gone or owned by another token,
135
+ * the handle's `lost` becomes true, `onLost` is called and a warning is logged,
136
+ * once. A failing `utimes` is retried like an unlink.
137
+ *
138
+ * Errors. `acquireSlot` never rejects. If the slot dir has disappeared (a temp
139
+ * cleaner), it is re-created once and the attempt repeated; if that fails, the
140
+ * dir verdict is dropped. Any other unexpected file-system error (EMFILE, ENOSPC,
141
+ * EIO, ...) resolves `{busy:true}` with one warning per dir and code, and drops
142
+ * the dir verdict, so the next call probes again. A slot is never granted
143
+ * without its lock file, so exclusion holds. A lock that the call created before
144
+ * such an error is removed under its claim (own token) before the busy result; if
145
+ * that fails too, the process remembers it, and its next look at the slot reaps
146
+ * it at once, as does the exit hook. A non-finite `waitMs` counts as 0.
147
+ *
148
+ * Residual risk: every check-then-act on a file system has a window between the
149
+ * last check and the syscall; its bounds are above. A single process frozen there
150
+ * (SIGSTOP, a debugger) for longer can still act late. A holder that stops
151
+ * heartbeating for 2 intervals while its lock looks old is reaped; that is the
152
+ * plan's heartbeat contract, and the holder is told through `lost`.
153
+ *
154
+ * If the temp dir is unwritable the module degrades to an in-process semaphore
155
+ * with the same API and logs that once per slot dir. No process is spawned here.
156
+ */
157
+ import { createHash, randomUUID } from "node:crypto";
158
+ import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
159
+ import { mkdir, open, readdir, readFile, stat, unlink, utimes, writeFile, type FileHandle } from "node:fs/promises";
160
+ import { hostname as osHostname, tmpdir, uptime as osUptime } from "node:os";
161
+ import { basename, join } from "node:path";
162
+ import type { PluginLogger } from "../router/logger";
163
+
164
+ export interface SlotMeta {
165
+ cwd: string;
166
+ command: string;
167
+ }
168
+
169
+ export interface SlotOptions {
170
+ max: number;
171
+ waitMs: number;
172
+ signal?: AbortSignal;
173
+ meta: SlotMeta;
174
+ /**
175
+ * Called once if the heartbeat finds this holder's lock file gone or owned by
176
+ * another token (the slot was reclaimed while held: two holders may be running).
177
+ */
178
+ onLost?: () => void;
179
+ }
180
+
181
+ export interface SlotHandle {
182
+ /** Deletes this holder's lock file. Idempotent; never rejects. */
183
+ release(): Promise<void>;
184
+ /** True once the heartbeat found that another process reclaimed this slot. */
185
+ readonly lost: boolean;
186
+ }
187
+
188
+ export type SlotResult = SlotHandle | { busy: true };
189
+
190
+ /** One consistent read of a lock file: content and stat from the same open file. */
191
+ export interface FileSnapshot {
192
+ text: string;
193
+ mtimeMs: number;
194
+ size: number;
195
+ }
196
+
197
+ /** Test seams. Defaults are the production values of plan 1.4.1. */
198
+ export interface SlotDeps {
199
+ /** Slot directory. Default: `<os.tmpdir()>/opencode-model-router/verify-slots`. */
200
+ dir?: string;
201
+ logger?: Pick<PluginLogger, "warn">;
202
+ /** Wall clock (ms). Compared with file mtimes and written into new files, nothing else. */
203
+ now?: () => number;
204
+ /**
205
+ * Machine clock (ms): wait deadlines, shared observations and claim fencing.
206
+ * The default is `process.hrtime`, anchored to `os.uptime()` where it counts
207
+ * from the process start (Bun), see `machineClockFrom`. Observations compare
208
+ * only stamps of one clock origin (`now() - mono()`, see the header).
209
+ */
210
+ mono?: () => number;
211
+ random?: () => number;
212
+ hostname?: string;
213
+ pid?: number;
214
+ isPidAlive?: (pid: number) => boolean;
215
+ heartbeatMs?: number;
216
+ staleMs?: number;
217
+ corruptGraceMs?: number;
218
+ /** A claimer stops deleting after holding its claim this long (self-fencing). */
219
+ claimHoldMaxMs?: number;
220
+ backoffMinMs?: number;
221
+ backoffMaxMs?: number;
222
+ unlink?: (path: string) => Promise<void>;
223
+ read?: (path: string) => Promise<FileSnapshot>;
224
+ utimes?: (path: string, time: Date) => Promise<void>;
225
+ unlinkRetries?: number;
226
+ unlinkRetryMs?: number;
227
+ /** Called on every wake-up of the wait loop (attempt), for busy-wait assertions. */
228
+ onAttempt?: () => void;
229
+ }
230
+
231
+ export const SLOT_DEFAULTS = {
232
+ heartbeatMs: 5_000,
233
+ staleMs: 30_000,
234
+ corruptGraceMs: 2_000,
235
+ claimHoldMaxMs: 5_000,
236
+ backoffMinMs: 250,
237
+ backoffMaxMs: 2_000,
238
+ unlinkRetries: 6,
239
+ unlinkRetryMs: 50,
240
+ } as const;
241
+
242
+ /** Housekeeping: files older than this (wall clock) may be collected when orphaned. */
243
+ const ORPHAN_AGE_MS = 3_600_000;
244
+ /** Housekeeping runs at most this often per dir and process (monotonic). */
245
+ const HOUSEKEEPING_EVERY_MS = 600_000;
246
+ /**
247
+ * Clocks whose boot instants (`wall - mono`) agree within this share an observation
248
+ * view: the uptime's resolution (up to 1 s) plus read jitter. Scaled down with the
249
+ * heartbeat (a fifth of it), so that tests with short heartbeats keep short pads.
250
+ */
251
+ const ORIGIN_SLACK_MS = 1_000;
252
+ /** `hrtime` within this of the uptime reads the boot clock; else it is anchored to the uptime. */
253
+ const HRTIME_IS_UPTIME_MS = 2_000;
254
+ /** Views kept per sidecar; the oldest goes first. */
255
+ const MAX_VIEWS = 4;
256
+
257
+ export function defaultSlotDir(): string {
258
+ return join(tmpdir(), "opencode-model-router", "verify-slots");
259
+ }
260
+
261
+ function hrtimeMs(): number {
262
+ return Number(process.hrtime.bigint() / 1_000n) / 1_000;
263
+ }
264
+ function uptimeMs(): number {
265
+ return osUptime() * 1_000;
266
+ }
267
+
268
+ /**
269
+ * The machine clock of one process, from its `hrtime` and the OS uptime (both in
270
+ * ms, see the header). An `hrtime` within 2 s of the uptime at the first read is
271
+ * the boot clock and is returned as is (Node). Otherwise (Bun: it counts from the
272
+ * process start) it is anchored to the uptime: `hr + max(uptime - hr)` over every
273
+ * read, the uptime read first, so each sample is a lower bound. Never goes back.
274
+ * Exported for tests.
275
+ */
276
+ export function machineClockFrom(hr: () => number, uptime: () => number): () => number {
277
+ const u0 = uptime();
278
+ const h0 = hr();
279
+ if (Math.abs(h0 - u0) <= HRTIME_IS_UPTIME_MS) return hr;
280
+ let offset = u0 - h0;
281
+ return () => {
282
+ const u = uptime();
283
+ const h = hr();
284
+ if (u - h > offset) offset = u - h;
285
+ return h + offset;
286
+ };
287
+ }
288
+
289
+ let machineClock: (() => number) | undefined;
290
+
291
+ /** The default `mono`: chosen once per process, at its first use. */
292
+ function machineMonoMs(): number {
293
+ machineClock ??= machineClockFrom(hrtimeMs, uptimeMs);
294
+ return machineClock();
295
+ }
296
+
297
+ interface LockInfo {
298
+ pid: number;
299
+ hostname: string;
300
+ token: string;
301
+ startedAt: number;
302
+ cwd: string;
303
+ command: string;
304
+ /** Claims only: the basename of the file this claim deletes, and that file's identity. */
305
+ target?: string;
306
+ victim?: string;
307
+ }
308
+
309
+ type LockState =
310
+ | { kind: "missing" }
311
+ | { kind: "unreadable"; code: string }
312
+ | { kind: "ok"; info: LockInfo; mtimeMs: number }
313
+ | { kind: "corrupt"; mtimeMs: number; size: number };
314
+ type Present = Extract<LockState, { kind: "ok" | "corrupt" }>;
315
+
316
+ type Cfg = Required<Omit<SlotDeps, "logger" | "onAttempt">> & Pick<SlotDeps, "logger" | "onAttempt">;
317
+
318
+ function errCode(e: unknown): string | undefined {
319
+ return typeof e === "object" && e !== null && "code" in e ? String((e as { code: unknown }).code) : undefined;
320
+ }
321
+
322
+ /** Sharing violations from antivirus/indexer handles: retried, never a verdict. */
323
+ const TRANSIENT = new Set(["EBUSY", "EPERM", "EACCES"]);
324
+ /** `mkdir`/create errors that can mean "unwritable dir"; only the final ones count at once. */
325
+ const UNWRITABLE = new Set(["EACCES", "EPERM", "EBUSY", "EROFS", "ENOTDIR", "ENOENT", "EEXIST"]);
326
+ const FINAL_UNWRITABLE = new Set(["EROFS", "ENOTDIR", "EEXIST"]);
327
+
328
+ function isTransient(e: unknown): boolean {
329
+ const code = errCode(e);
330
+ return code !== undefined && TRANSIENT.has(code);
331
+ }
332
+
333
+ /** Failures of the logger itself (a throwing logger must not break slot bookkeeping). */
334
+ export let loggerFailures = 0;
335
+
336
+ function warn(cfg: Cfg, msg: string, data: Record<string, unknown>): void {
337
+ try {
338
+ cfg.logger?.warn(msg, data);
339
+ } catch {
340
+ loggerFailures++;
341
+ }
342
+ }
343
+
344
+ const ioWarned = new Set<string>();
345
+
346
+ /** Advisory files (observations, housekeeping): a failure only loses evidence. Said once per dir and kind. */
347
+ function ioTrouble(cfg: Cfg, what: string, path: string, e: unknown): void {
348
+ const k = `${cfg.dir}\n${what}`;
349
+ if (ioWarned.has(k)) return;
350
+ ioWarned.add(k);
351
+ warn(cfg, `verification slot: ${what} I/O failed`, { path, code: errCode(e) ?? String(e) });
352
+ }
353
+
354
+ export function isPidAlive(pid: number): boolean {
355
+ try {
356
+ process.kill(pid, 0);
357
+ return true;
358
+ } catch (e) {
359
+ // EPERM: the process exists but belongs to someone else (verified on Windows
360
+ // and the documented POSIX behaviour). Anything but ESRCH is treated as alive.
361
+ return errCode(e) !== "ESRCH";
362
+ }
363
+ }
364
+
365
+ async function readSnapshot(path: string): Promise<FileSnapshot> {
366
+ const fh = await open(path, "r");
367
+ try {
368
+ const st = await fh.stat();
369
+ const text = await fh.readFile("utf8");
370
+ return { text, mtimeMs: st.mtimeMs, size: st.size };
371
+ } finally {
372
+ await fh.close();
373
+ }
374
+ }
375
+
376
+ function resolveCfg(deps: SlotDeps = {}): Cfg {
377
+ return {
378
+ dir: deps.dir ?? defaultSlotDir(),
379
+ now: deps.now ?? Date.now,
380
+ mono: deps.mono ?? machineMonoMs,
381
+ random: deps.random ?? Math.random,
382
+ hostname: deps.hostname ?? osHostname(),
383
+ pid: deps.pid ?? process.pid,
384
+ isPidAlive: deps.isPidAlive ?? isPidAlive,
385
+ heartbeatMs: deps.heartbeatMs ?? SLOT_DEFAULTS.heartbeatMs,
386
+ staleMs: deps.staleMs ?? SLOT_DEFAULTS.staleMs,
387
+ corruptGraceMs: deps.corruptGraceMs ?? SLOT_DEFAULTS.corruptGraceMs,
388
+ claimHoldMaxMs: deps.claimHoldMaxMs ?? SLOT_DEFAULTS.claimHoldMaxMs,
389
+ backoffMinMs: deps.backoffMinMs ?? SLOT_DEFAULTS.backoffMinMs,
390
+ backoffMaxMs: deps.backoffMaxMs ?? SLOT_DEFAULTS.backoffMaxMs,
391
+ unlink: deps.unlink ?? unlink,
392
+ read: deps.read ?? readSnapshot,
393
+ utimes: deps.utimes ?? ((p, t) => utimes(p, t, t)),
394
+ unlinkRetries: deps.unlinkRetries ?? SLOT_DEFAULTS.unlinkRetries,
395
+ unlinkRetryMs: deps.unlinkRetryMs ?? SLOT_DEFAULTS.unlinkRetryMs,
396
+ logger: deps.logger,
397
+ onAttempt: deps.onAttempt,
398
+ };
399
+ }
400
+
401
+ function parseLock(text: string): LockInfo | undefined {
402
+ try {
403
+ const v: unknown = JSON.parse(text);
404
+ if (typeof v !== "object" || v === null) return undefined;
405
+ const o = v as Record<string, unknown>;
406
+ if (typeof o.pid !== "number" || typeof o.hostname !== "string" || typeof o.token !== "string") return undefined;
407
+ return {
408
+ pid: o.pid,
409
+ hostname: o.hostname,
410
+ token: o.token,
411
+ startedAt: typeof o.startedAt === "number" ? o.startedAt : 0,
412
+ cwd: typeof o.cwd === "string" ? o.cwd : "",
413
+ command: typeof o.command === "string" ? o.command : "",
414
+ ...(typeof o.target === "string" ? { target: o.target } : {}),
415
+ ...(typeof o.victim === "string" ? { victim: o.victim } : {}),
416
+ };
417
+ } catch (e) {
418
+ if (e instanceof SyntaxError) return undefined;
419
+ throw e;
420
+ }
421
+ }
422
+
423
+ /** Missing, unreadable (a scanner holds it: unknown, never stale), or present. */
424
+ async function readLock(path: string, cfg: Cfg): Promise<LockState> {
425
+ let snap: FileSnapshot;
426
+ try {
427
+ snap = await cfg.read(path);
428
+ } catch (e) {
429
+ const code = errCode(e);
430
+ if (code === "ENOENT") return { kind: "missing" };
431
+ if (code !== undefined && TRANSIENT.has(code)) return { kind: "unreadable", code };
432
+ throw e;
433
+ }
434
+ const info = parseLock(snap.text);
435
+ return info ? { kind: "ok", info, mtimeMs: snap.mtimeMs } : { kind: "corrupt", mtimeMs: snap.mtimeMs, size: snap.size };
436
+ }
437
+
438
+ /** What a file is: its token, or for a corrupt file its mtime and size. Names its claim. */
439
+ function identity(s: Present): string {
440
+ return s.kind === "ok" ? s.info.token : `corrupt:${s.mtimeMs}:${s.size}`;
441
+ }
442
+ /** Identity plus mtime: what must stay unchanged for a staleness verdict to hold. */
443
+ function observedKey(s: Present): string {
444
+ return `${identity(s)}@${s.mtimeMs}`;
445
+ }
446
+
447
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
448
+
449
+ function hash32(s: string): string {
450
+ return createHash("sha256").update(s).digest("hex").slice(0, 32);
451
+ }
452
+
453
+ /** The claim file under which the file with identity `id` (in slot `slotPath`'s family) is deleted. */
454
+ export function reapClaimPath(slotPath: string, id: string): string {
455
+ return `${slotPath}.reap-${hash32(id)}`;
456
+ }
457
+
458
+ /** The shared observation sidecar of `target` (identity `id`) as seen from host `host`. */
459
+ function seenPath(slotPath: string, target: string, id: string, host: string): string {
460
+ return `${slotPath}.seen-${hash32(`${basename(target)}\n${id}\n${host}`)}`;
461
+ }
462
+
463
+ // ---- shared observation and staleness ----------------------------------------
464
+
465
+ let bootIdCache: string | undefined;
466
+
467
+ /** The Linux boot id; "" where there is none (the boot-instant check then stands alone). */
468
+ function bootId(): string {
469
+ if (bootIdCache === undefined) {
470
+ bootIdCache = "";
471
+ if (process.platform === "linux") {
472
+ try {
473
+ bootIdCache = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
474
+ } catch (e) {
475
+ // No procfs (a sandbox): every process of the host fails alike, so "" still
476
+ // matches between them, and the boot-instant check remains.
477
+ if (errCode(e) === undefined) throw e;
478
+ }
479
+ }
480
+ }
481
+ return bootIdCache;
482
+ }
483
+
484
+ /** The looks of one clock origin at one key. Stamps are on that origin's `mono`. */
485
+ interface SeenView {
486
+ boot: string;
487
+ /** `wall - mono` of the look that started the view: the origin of its clock. */
488
+ bootAt: number;
489
+ /** The largest slack of the looks that wrote the view. */
490
+ slack: number;
491
+ first: number;
492
+ from: number;
493
+ last: number;
494
+ }
495
+
496
+ interface SeenRecord {
497
+ key: string;
498
+ views: SeenView[];
499
+ }
500
+
501
+ const isNum = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n);
502
+
503
+ function parseView(v: unknown): SeenView | undefined {
504
+ if (typeof v !== "object" || v === null) return undefined;
505
+ const { boot, bootAt, slack, first, from, last } = v as Record<string, unknown>;
506
+ if (typeof boot !== "string" || !isNum(bootAt) || !isNum(slack) || !isNum(first) || !isNum(from) || !isNum(last)) return undefined;
507
+ return { boot, bootAt, slack, first, from, last };
508
+ }
509
+
510
+ function parseSeen(text: string): SeenRecord | undefined {
511
+ try {
512
+ const v: unknown = JSON.parse(text);
513
+ if (typeof v !== "object" || v === null) return undefined;
514
+ const { key, views } = v as Record<string, unknown>;
515
+ if (typeof key !== "string" || !Array.isArray(views)) return undefined;
516
+ return { key, views: views.map(parseView).filter((x): x is SeenView => x !== undefined) };
517
+ } catch (e) {
518
+ // A torn read of a concurrent write: no evidence, the record restarts.
519
+ if (e instanceof SyntaxError) return undefined;
520
+ throw e;
521
+ }
522
+ }
523
+
524
+ interface Look {
525
+ /** How long the file has had its current key (mono), since the view's first sighting. */
526
+ span: number;
527
+ /** How long it has been watched without a gap of more than 2 heartbeats minus this look's slack and the view's. */
528
+ witnessed: number;
529
+ /** How far two stamps of the view may disagree: every threshold adds it. */
530
+ errMs: number;
531
+ }
532
+ const NO_LOOK: Look = { span: 0, witnessed: 0, errMs: 0 };
533
+
534
+ /** This look's origin slack (see `ORIGIN_SLACK_MS`). */
535
+ function originSlackMs(cfg: Cfg): number {
536
+ return Math.min(ORIGIN_SLACK_MS, cfg.heartbeatMs / 5);
537
+ }
538
+
539
+ /**
540
+ * Record a look at `target` (state `s`, read at `at`, taken before the read) in
541
+ * its shared sidecar, in the view of this look's clock origin, and return what
542
+ * that view's looks establish. Stamps of other views are never read.
543
+ */
544
+ async function observe(slotPath: string, target: string, s: Present, at: number, cfg: Cfg): Promise<Look> {
545
+ const file = seenPath(slotPath, target, identity(s), cfg.hostname);
546
+ let prev: SeenRecord | undefined;
547
+ try {
548
+ prev = parseSeen(await readFile(file, "utf8"));
549
+ } catch (e) {
550
+ if (errCode(e) !== "ENOENT") {
551
+ if (!isTransient(e)) ioTrouble(cfg, "observation", file, e);
552
+ return NO_LOOK;
553
+ }
554
+ }
555
+ const key = observedKey(s);
556
+ const boot = bootId();
557
+ const bootAt = cfg.now() - cfg.mono(); // read together: the origin of this look's clock
558
+ const slack = originSlackMs(cfg);
559
+ const maxGap = 2 * cfg.heartbeatMs;
560
+ const views = prev?.key === key ? prev.views : []; // a new key: every view restarts
561
+ const i = views.findIndex((v) => v.boot === boot && Math.abs(v.bootAt - bootAt) <= slack);
562
+ const old = i >= 0 ? views[i] : undefined;
563
+ let view: SeenView;
564
+ // A stamp far in the future is another boot's clock: the view restarts.
565
+ if (old !== undefined && at >= old.last - maxGap) {
566
+ view = { ...old, slack: Math.max(old.slack, slack), from: at - old.last > maxGap - (slack + old.slack) ? at : old.from, last: Math.max(old.last, at) };
567
+ } else {
568
+ view = { boot, bootAt, slack, first: at, from: at, last: at };
569
+ }
570
+ const rec: SeenRecord = { key, views: [...views.filter((_, j) => j !== i).slice(-(MAX_VIEWS - 1)), view] };
571
+ try {
572
+ await writeFile(file, JSON.stringify(rec));
573
+ } catch (e) {
574
+ // The verdict of this look stands; only later looks lose it.
575
+ if (errCode(e) !== "ENOENT" && !isTransient(e)) ioTrouble(cfg, "observation", file, e);
576
+ }
577
+ return { span: Math.max(0, at - view.first), witnessed: Math.max(0, at - view.from), errMs: slack + view.slack };
578
+ }
579
+
580
+ /** Delete the sidecar of a file that is gone. Advisory: a leftover is collected by housekeeping. */
581
+ async function dropSeen(slotPath: string, target: string, id: string, cfg: Cfg): Promise<void> {
582
+ const file = seenPath(slotPath, target, id, cfg.hostname);
583
+ try {
584
+ await cfg.unlink(file);
585
+ } catch (e) {
586
+ if (errCode(e) !== "ENOENT" && !isTransient(e)) ioTrouble(cfg, "observation", file, e);
587
+ }
588
+ }
589
+
590
+ /** Same host and the PID is gone: provably dead, no confirmation needed. */
591
+ function ownerDead(s: Present, cfg: Cfg): boolean {
592
+ return s.kind === "ok" && s.info.hostname === cfg.hostname && !cfg.isPidAlive(s.info.pid);
593
+ }
594
+
595
+ /** stale: reap it; aged: old but not witnessed long enough yet; fresh: leave it. */
596
+ type Verdict = "stale" | "aged" | "fresh";
597
+
598
+ async function lockVerdict(slotPath: string, s: Present, at: number, cfg: Cfg): Promise<Verdict> {
599
+ if (ownerDead(s, cfg) || isStray(slotPath, s)) return "stale";
600
+ const corrupt = s.kind === "corrupt";
601
+ const oldMs = corrupt ? cfg.corruptGraceMs : cfg.staleMs;
602
+ const confirmMs = corrupt ? cfg.corruptGraceMs : 2 * cfg.heartbeatMs;
603
+ const look = await observe(slotPath, slotPath, s, at, cfg);
604
+ if (!(cfg.now() - s.mtimeMs > oldMs || look.span >= oldMs + look.errMs)) return "fresh";
605
+ return look.witnessed >= confirmMs + look.errMs ? "stale" : "aged";
606
+ }
607
+
608
+ /** A claim is inert by observation only (claims are never refreshed, so a wall age says nothing). */
609
+ async function claimInert(slotPath: string, claim: string, s: Present, at: number, cfg: Cfg): Promise<boolean> {
610
+ if (ownerDead(s, cfg)) return true;
611
+ const corrupt = s.kind === "corrupt";
612
+ const oldMs = corrupt ? cfg.corruptGraceMs : cfg.staleMs;
613
+ const confirmMs = corrupt ? cfg.corruptGraceMs : 2 * cfg.claimHoldMaxMs;
614
+ const look = await observe(slotPath, claim, s, at, cfg);
615
+ return look.span >= oldMs + look.errMs && look.witnessed >= confirmMs + look.errMs;
616
+ }
617
+
618
+ // ---- exclusive create and claimed delete --------------------------------------
619
+
620
+ /**
621
+ * Create `path` exclusively with `info`, then re-read it (an unreadable re-read,
622
+ * a scanner, is retried on the unlink schedule): true only when it holds
623
+ * `info.token`. A re-read that stays unreadable counts as ours only when
624
+ * `trustUnreadable` (a slot lock, whose heartbeat re-checks the token within one
625
+ * interval), never for a claim, which nothing re-checks. When the file was
626
+ * created but is not held, `stray` runs first: after an unexpected error (before
627
+ * it propagates, QA-1.4-28) and for an unconfirmed claim (QA-1.4-29).
628
+ */
629
+ async function createOwned(
630
+ path: string,
631
+ info: LockInfo,
632
+ cfg: Cfg,
633
+ trustUnreadable: boolean,
634
+ stray: () => Promise<void> | void,
635
+ ): Promise<boolean> {
636
+ let fh: FileHandle;
637
+ try {
638
+ fh = await open(path, "wx");
639
+ } catch (e) {
640
+ const code = errCode(e);
641
+ if (code === "EEXIST" || (code !== undefined && TRANSIENT.has(code))) return false;
642
+ throw e;
643
+ }
644
+ try {
645
+ try {
646
+ await fh.writeFile(JSON.stringify(info), "utf8");
647
+ } finally {
648
+ await fh.close();
649
+ }
650
+ for (let i = 0; ; i++) {
651
+ const s = await readLock(path, cfg);
652
+ if (s.kind !== "unreadable") return s.kind === "ok" && s.info.token === info.token;
653
+ if (i >= cfg.unlinkRetries) break;
654
+ await sleep(cfg.unlinkRetryMs * 2 ** i);
655
+ }
656
+ } catch (e) {
657
+ await stray();
658
+ throw e;
659
+ }
660
+ if (trustUnreadable) return true;
661
+ await stray();
662
+ return false;
663
+ }
664
+
665
+ /** Claims currently held by this process (claim path -> claim token), for the exit hook. */
666
+ const activeClaims = new Map<string, string>();
667
+ const MAX_CLAIM_DEPTH = 3;
668
+
669
+ /** A claim this process created but could not confirm (QA-1.4-29), until its drop fence (on its `mono`). */
670
+ interface Unconfirmed {
671
+ token: string;
672
+ dropBy: number;
673
+ /** The clock `dropBy` is on, so the exit hook can apply the same fence (QA-1.4-32). */
674
+ mono: () => number;
675
+ }
676
+ /** Claim path -> this process's unconfirmed claim there. Dropped at the next readable look, or at exit while within its fence. */
677
+ const unconfirmedClaims = new Map<string, Unconfirmed>();
678
+ const MAX_UNCONFIRMED = 64;
679
+
680
+ function noteUnconfirmed(claim: string, token: string, since: number, cfg: Cfg): void {
681
+ hookExit();
682
+ if (unconfirmedClaims.size >= MAX_UNCONFIRMED) {
683
+ const oldest = unconfirmedClaims.keys().next();
684
+ if (!oldest.done) unconfirmedClaims.delete(oldest.value);
685
+ }
686
+ unconfirmedClaims.set(claim, { token, dropBy: since + 1.5 * cfg.claimHoldMaxMs, mono: cfg.mono });
687
+ }
688
+
689
+ /**
690
+ * The claim at `claim` (seen as `s`) is this process's own unconfirmed one: drop
691
+ * it by its token, within the same fence as a held claim. Undefined when it is not
692
+ * ours (or no longer droppable); else whether the claim path is now free.
693
+ */
694
+ async function dropUnconfirmed(slotPath: string, claim: string, s: Present, cfg: Cfg): Promise<boolean | undefined> {
695
+ const own = unconfirmedClaims.get(claim);
696
+ if (own === undefined) return undefined;
697
+ if (s.kind !== "ok" || s.info.token !== own.token || cfg.mono() > own.dropBy) {
698
+ // Replaced (ours is gone), or past the fence: from now on the rules for any claim apply.
699
+ unconfirmedClaims.delete(claim);
700
+ return undefined;
701
+ }
702
+ const r = await unlinkWhile(claim, own.dropBy, cfg, (c) => c.kind === "ok" && c.info.token === own.token);
703
+ if (r !== "failed") unconfirmedClaims.delete(claim);
704
+ if (r === "removed") await dropSeen(slotPath, claim, own.token, cfg);
705
+ return r === "removed" || r === "gone";
706
+ }
707
+
708
+ type Removal = "removed" | "gone" | "changed" | "contended" | "failed";
709
+
710
+ /**
711
+ * Unlink `target` while `stillVictim` holds, re-reading it before every attempt.
712
+ * Gives up (without deleting) at the monotonic `deadline`, which is checked
713
+ * again after the re-read, right before the unlink.
714
+ */
715
+ async function unlinkWhile(target: string, deadline: number, cfg: Cfg, stillVictim: (s: Present) => boolean): Promise<Removal> {
716
+ let last = "";
717
+ const late = (): Removal => {
718
+ warn(cfg, "verification slot: claim held too long, delete abandoned", { path: target, code: last });
719
+ return "failed";
720
+ };
721
+ for (let i = 0; ; i++) {
722
+ if (cfg.mono() > deadline) return late();
723
+ const cur = await readLock(target, cfg);
724
+ if (cur.kind === "missing") return "gone";
725
+ if (cur.kind === "unreadable") last = cur.code;
726
+ else if (!stillVictim(cur)) return "changed";
727
+ else if (cfg.mono() > deadline) return late();
728
+ else {
729
+ try {
730
+ await cfg.unlink(target);
731
+ return "removed";
732
+ } catch (e) {
733
+ const code = errCode(e) ?? String(e);
734
+ if (code === "ENOENT") return "gone";
735
+ last = code;
736
+ if (!TRANSIENT.has(code)) break;
737
+ }
738
+ }
739
+ if (i >= cfg.unlinkRetries) break;
740
+ await sleep(cfg.unlinkRetryMs * 2 ** i);
741
+ }
742
+ warn(cfg, "verification slot: could not delete lock file", { path: target, code: last });
743
+ return "failed";
744
+ }
745
+
746
+ /**
747
+ * Delete `target` (identity `id`) under its claim, only while `stillVictim`
748
+ * holds. A dead claimer's leftover claim is cleared first (one level up).
749
+ */
750
+ async function removeUnderClaim(
751
+ slotPath: string,
752
+ target: string,
753
+ id: string,
754
+ stillVictim: (s: Present) => boolean,
755
+ cfg: Cfg,
756
+ depth = 0,
757
+ ): Promise<Removal> {
758
+ const claim = reapClaimPath(slotPath, id);
759
+ for (let round = 0; round < 2; round++) {
760
+ const token = randomUUID();
761
+ const info: LockInfo = {
762
+ pid: cfg.pid,
763
+ hostname: cfg.hostname,
764
+ token,
765
+ startedAt: cfg.now(),
766
+ cwd: "",
767
+ command: "reap",
768
+ target: basename(target),
769
+ victim: id,
770
+ };
771
+ // The fence starts before the create: other processes may see the claim from then on.
772
+ const since = cfg.mono();
773
+ let mine: boolean;
774
+ try {
775
+ mine = await createOwned(claim, info, cfg, false, () => noteUnconfirmed(claim, token, since, cfg));
776
+ } catch (e) {
777
+ if (errCode(e) === "ENOENT") return "gone"; // no dir: the target went with it
778
+ throw e;
779
+ }
780
+ if (mine) {
781
+ activeClaims.set(claim, token);
782
+ let r: Removal = "failed";
783
+ try {
784
+ r = await unlinkWhile(target, since + cfg.claimHoldMaxMs, cfg, stillVictim);
785
+ return r;
786
+ } finally {
787
+ activeClaims.delete(claim);
788
+ // Dropping the claim is safe well before anyone could judge it inert (staleMs).
789
+ const drop = await unlinkWhile(claim, since + 1.5 * cfg.claimHoldMaxMs, cfg, (c) => c.kind === "ok" && c.info.token === token);
790
+ if (drop === "removed") await dropSeen(slotPath, claim, token, cfg);
791
+ if (r === "removed" || r === "gone") await dropSeen(slotPath, target, id, cfg);
792
+ }
793
+ }
794
+ if (depth >= MAX_CLAIM_DEPTH || !(await reclaimClaim(slotPath, claim, cfg, depth + 1))) return "contended";
795
+ }
796
+ return "contended";
797
+ }
798
+
799
+ /** Remove a claim whose owner is dead or that is inert. True when the claim path is free. */
800
+ async function reclaimClaim(slotPath: string, claim: string, cfg: Cfg, depth: number): Promise<boolean> {
801
+ const at = cfg.mono();
802
+ const s = await readLock(claim, cfg);
803
+ if (s.kind === "missing") return true;
804
+ if (s.kind === "unreadable") return false;
805
+ const own = await dropUnconfirmed(slotPath, claim, s, cfg);
806
+ if (own !== undefined) return own;
807
+ if (!(await claimInert(slotPath, claim, s, at, cfg))) return false;
808
+ const key = observedKey(s);
809
+ const r = await removeUnderClaim(slotPath, claim, identity(s), (c) => observedKey(c) === key, cfg, depth);
810
+ return r === "removed" || r === "gone";
811
+ }
812
+
813
+ /** Reap the slot lock `path`, seen as `cur`, under its claim. */
814
+ function reap(path: string, cur: Present, cfg: Cfg): Promise<Removal> {
815
+ const key = observedKey(cur);
816
+ return removeUnderClaim(path, path, identity(cur), (c) => observedKey(c) === key, cfg);
817
+ }
818
+
819
+ // ---- held slots, released synchronously on process exit ----------------------
820
+
821
+ interface Held {
822
+ path: string;
823
+ token: string;
824
+ pid: number;
825
+ hostname: string;
826
+ }
827
+ const held = new Set<Held>();
828
+ /** Slot locks this process created but never held (an error after the create, QA-1.4-28): path -> lock. */
829
+ const strays = new Map<string, Held>();
830
+ let exitHooked = false;
831
+
832
+ /** This process's own stray at `path`: stale at once. A different file there means ours is gone. */
833
+ function isStray(path: string, s: Present): boolean {
834
+ const own = strays.get(path);
835
+ if (own === undefined) return false;
836
+ if (s.kind === "ok" && s.info.token === own.token) return true;
837
+ if (s.kind === "ok") strays.delete(path);
838
+ return false;
839
+ }
840
+
841
+ /** Remove a slot lock that this process created and does not hold, under its claim; else remember it. */
842
+ async function dropStray(path: string, token: string, cfg: Cfg): Promise<void> {
843
+ hookExit();
844
+ strays.set(path, { path, token, pid: cfg.pid, hostname: cfg.hostname });
845
+ const r = await removeUnderClaim(path, path, token, (s) => s.kind === "ok" && s.info.token === token, cfg).catch(
846
+ (): Removal => "failed", // the error being surfaced says why; the next look or the exit hook retries
847
+ );
848
+ // "contended": a reaper holds the claim and deletes it.
849
+ if (r !== "failed") strays.delete(path);
850
+ }
851
+ /** Exit-time release failures (observable in tests; nothing can log at exit). */
852
+ export let exitReleaseFailures = 0;
853
+ export let lastExitReleaseError: string | undefined;
854
+
855
+ function unlinkIfTokenSync(path: string, token: string): void {
856
+ let text: string;
857
+ try {
858
+ text = readFileSync(path, "utf8");
859
+ } catch (e) {
860
+ if (errCode(e) === "ENOENT") return;
861
+ throw e;
862
+ }
863
+ if (parseLock(text)?.token === token) unlinkSync(path);
864
+ }
865
+
866
+ /** The exit-time release follows the claim protocol, synchronously. */
867
+ function releaseOneSync(h: Held): void {
868
+ const claim = reapClaimPath(h.path, h.token);
869
+ if (activeClaims.has(claim)) {
870
+ // Our own async release holds the claim right now; the loop below drops it.
871
+ unlinkIfTokenSync(h.path, h.token);
872
+ return;
873
+ }
874
+ const token = randomUUID();
875
+ let fd: number;
876
+ try {
877
+ fd = openSync(claim, "wx");
878
+ } catch (e) {
879
+ if (errCode(e) === "EEXIST") return; // another process is reaping this lock and deletes it
880
+ throw e;
881
+ }
882
+ try {
883
+ try {
884
+ const info: LockInfo = { pid: h.pid, hostname: h.hostname, token, startedAt: Date.now(), cwd: "", command: "exit", target: basename(h.path), victim: h.token };
885
+ writeSync(fd, JSON.stringify(info));
886
+ } finally {
887
+ closeSync(fd);
888
+ }
889
+ unlinkIfTokenSync(h.path, h.token);
890
+ } finally {
891
+ unlinkIfTokenSync(claim, token);
892
+ }
893
+ }
894
+
895
+ function noteExitFailure(e: unknown): void {
896
+ exitReleaseFailures++;
897
+ lastExitReleaseError = errCode(e) ?? String(e);
898
+ }
899
+
900
+ function releaseAllSync(): void {
901
+ for (const h of [...held, ...strays.values()]) {
902
+ try {
903
+ releaseOneSync(h);
904
+ } catch (e) {
905
+ // Best effort at exit: the heartbeat stops with the process and the PID
906
+ // probe reclaims the slot. Nothing can be logged asynchronously here.
907
+ noteExitFailure(e);
908
+ }
909
+ }
910
+ held.clear();
911
+ strays.clear();
912
+ // An unconfirmed claim only within its drop fence, like the normal drop path: past it, another
913
+ // process may already be removing it as inert, and a late delete here could free a third reaper's claim (QA-1.4-32).
914
+ const unconfirmed = [...unconfirmedClaims].filter(([, u]) => u.mono() <= u.dropBy).map(([c, u]) => [c, u.token] as const);
915
+ for (const [claim, token] of [...activeClaims, ...unconfirmed]) {
916
+ try {
917
+ unlinkIfTokenSync(claim, token);
918
+ } catch (e) {
919
+ noteExitFailure(e);
920
+ }
921
+ }
922
+ activeClaims.clear();
923
+ unconfirmedClaims.clear();
924
+ for (const t of tickets) {
925
+ try {
926
+ unlinkSync(t);
927
+ } catch (e) {
928
+ if (errCode(e) !== "ENOENT") noteExitFailure(e);
929
+ }
930
+ }
931
+ tickets.clear();
932
+ }
933
+
934
+ function hookExit(): void {
935
+ if (exitHooked) return;
936
+ exitHooked = true;
937
+ process.on("exit", releaseAllSync);
938
+ }
939
+
940
+ // ---- in-process fallback ------------------------------------------------------
941
+
942
+ interface LocalSem {
943
+ count: number;
944
+ waiters: Array<() => void>;
945
+ }
946
+ const localSems = new Map<string, LocalSem>();
947
+ const degradedLogged = new Set<string>();
948
+
949
+ function acquireLocal(opts: SlotOptions, cfg: Cfg): Promise<SlotResult> {
950
+ let sem = localSems.get(cfg.dir);
951
+ if (!sem) {
952
+ sem = { count: 0, waiters: [] };
953
+ localSems.set(cfg.dir, sem);
954
+ }
955
+ const s = sem;
956
+ const makeHandle = (): SlotHandle => {
957
+ let done = false;
958
+ return {
959
+ release: async () => {
960
+ if (done) return;
961
+ done = true;
962
+ const next = s.waiters.shift();
963
+ if (next) next();
964
+ else s.count--;
965
+ },
966
+ lost: false,
967
+ };
968
+ };
969
+ if (s.count < opts.max) {
970
+ s.count++;
971
+ return Promise.resolve(makeHandle());
972
+ }
973
+ if (opts.waitMs <= 0 || opts.signal?.aborted) return Promise.resolve({ busy: true });
974
+ return new Promise((resolve) => {
975
+ const grant = () => {
976
+ cleanup();
977
+ resolve(makeHandle());
978
+ };
979
+ const giveUp = () => {
980
+ const i = s.waiters.indexOf(grant);
981
+ if (i >= 0) s.waiters.splice(i, 1);
982
+ cleanup();
983
+ resolve({ busy: true });
984
+ };
985
+ const timer = setTimeout(giveUp, opts.waitMs);
986
+ const cleanup = () => {
987
+ clearTimeout(timer);
988
+ opts.signal?.removeEventListener("abort", giveUp);
989
+ };
990
+ opts.signal?.addEventListener("abort", giveUp, { once: true });
991
+ s.waiters.push(grant);
992
+ });
993
+ }
994
+
995
+ /** Unlink a uniquely named file (no identity to check), retrying transient errors. */
996
+ async function unlinkRetry(path: string, cfg: Cfg): Promise<boolean> {
997
+ for (let i = 0; ; i++) {
998
+ try {
999
+ await cfg.unlink(path);
1000
+ return true;
1001
+ } catch (e) {
1002
+ const code = errCode(e) ?? String(e);
1003
+ if (code === "ENOENT") return true;
1004
+ if (!TRANSIENT.has(code) || i >= cfg.unlinkRetries) {
1005
+ warn(cfg, "verification slot: could not delete file", { path, code });
1006
+ return false;
1007
+ }
1008
+ }
1009
+ await sleep(cfg.unlinkRetryMs * 2 ** i);
1010
+ }
1011
+ }
1012
+
1013
+ /** Per slot dir: file slots and local slots never mix for one dir. Dropped on unexpected errors. */
1014
+ const dirVerdicts = new Map<string, Promise<boolean>>();
1015
+
1016
+ function dirWritable(cfg: Cfg): Promise<boolean> {
1017
+ const dir = cfg.dir;
1018
+ let verdict = dirVerdicts.get(dir);
1019
+ if (!verdict) {
1020
+ verdict = probeDir(cfg);
1021
+ dirVerdicts.set(dir, verdict);
1022
+ // An unexpected error is not a verdict: the next call probes again.
1023
+ verdict.catch(() => dirVerdicts.delete(dir));
1024
+ }
1025
+ return verdict;
1026
+ }
1027
+
1028
+ /**
1029
+ * Judge the dir only from `mkdir`/exclusive-create errors. Once the probe file
1030
+ * exists the dir is writable; removing the probe is housekeeping (retried, and a
1031
+ * residual failure is logged, never a verdict). EACCES/EPERM/EBUSY/ENOENT can be
1032
+ * transient (antivirus, a concurrent removal), so they are retried before they
1033
+ * count; EROFS/ENOTDIR/EEXIST are final.
1034
+ */
1035
+ async function probeDir(cfg: Cfg): Promise<boolean> {
1036
+ for (let i = 0; ; i++) {
1037
+ const probe = join(cfg.dir, `.probe-${randomUUID()}`);
1038
+ let code: string | undefined;
1039
+ try {
1040
+ await mkdir(cfg.dir, { recursive: true });
1041
+ await (await open(probe, "wx")).close();
1042
+ } catch (e) {
1043
+ code = errCode(e);
1044
+ if (code === undefined || !UNWRITABLE.has(code)) throw e;
1045
+ }
1046
+ if (code === undefined) {
1047
+ await unlinkRetry(probe, cfg);
1048
+ return true;
1049
+ }
1050
+ if (FINAL_UNWRITABLE.has(code) || i >= 2) return false;
1051
+ await sleep(cfg.unlinkRetryMs * 2 ** i);
1052
+ }
1053
+ }
1054
+
1055
+ /** The dir vanished at use time (a temp cleaner): re-create it once. On failure the verdict is dropped. */
1056
+ async function recreateDir(cfg: Cfg): Promise<boolean> {
1057
+ try {
1058
+ await mkdir(cfg.dir, { recursive: true });
1059
+ return true;
1060
+ } catch (e) {
1061
+ dirVerdicts.delete(cfg.dir);
1062
+ warn(cfg, "verification slot: could not re-create the slot dir", { dir: cfg.dir, code: errCode(e) ?? String(e) });
1063
+ return false;
1064
+ }
1065
+ }
1066
+
1067
+ const fsWarned = new Set<string>();
1068
+
1069
+ /** An unexpected file-system error: never a rejection, never a slot. Busy, one warning per dir and code. */
1070
+ function fsFailure(cfg: Cfg, e: unknown): SlotResult {
1071
+ dirVerdicts.delete(cfg.dir);
1072
+ const code = errCode(e) ?? String(e);
1073
+ const k = `${cfg.dir}\n${code}`;
1074
+ if (!fsWarned.has(k)) {
1075
+ fsWarned.add(k);
1076
+ warn(cfg, "verification slot: file-system error, reporting busy", { dir: cfg.dir, code });
1077
+ }
1078
+ return { busy: true };
1079
+ }
1080
+
1081
+ // ---- housekeeping -------------------------------------------------------------
1082
+
1083
+ const PROBE_NAME = /^\.probe-[0-9a-f-]{36}$/;
1084
+ const SEEN_NAME = /^slot-\d+\.lock\.seen-[0-9a-f]{32}$/;
1085
+ const LEGACY_NAME = /^slot-\d+\.lock\.reap(\.dead-.*)?$/;
1086
+ const CLAIM_NAME = /^(slot-\d+\.lock)\.reap-[0-9a-f]{32}$/;
1087
+ /** What a claim may target: a slot lock or another claim of its family. */
1088
+ const TARGET_NAME = /^slot-\d+\.lock(\.reap-[0-9a-f]{32})?$/;
1089
+ const housekeptAt = new Map<string, number>();
1090
+
1091
+ async function olderThanOrphanAge(path: string, cfg: Cfg): Promise<boolean> {
1092
+ try {
1093
+ return cfg.now() - (await stat(path)).mtimeMs > ORPHAN_AGE_MS;
1094
+ } catch (e) {
1095
+ if (errCode(e) === "ENOENT") return false;
1096
+ throw e;
1097
+ }
1098
+ }
1099
+
1100
+ /** One file of the dir listing: collected when orphaned and older than 1 hour. */
1101
+ async function collectOne(name: string, cfg: Cfg): Promise<void> {
1102
+ const path = join(cfg.dir, name);
1103
+ if (PROBE_NAME.test(name) || SEEN_NAME.test(name) || LEGACY_NAME.test(name)) {
1104
+ // Unique (probes) or advisory (sidecars, legacy files the protocol ignores): by path.
1105
+ if (!(await olderThanOrphanAge(path, cfg))) return;
1106
+ try {
1107
+ await cfg.unlink(path);
1108
+ } catch (e) {
1109
+ if (errCode(e) !== "ENOENT") throw e;
1110
+ }
1111
+ return;
1112
+ }
1113
+ const m = CLAIM_NAME.exec(name);
1114
+ if (!m?.[1] || !(await olderThanOrphanAge(path, cfg))) return;
1115
+ const s = await readLock(path, cfg);
1116
+ if (s.kind === "missing" || s.kind === "unreadable") return;
1117
+ if (s.kind === "ok") {
1118
+ const { target, victim } = s.info;
1119
+ if (target === undefined || victim === undefined || !TARGET_NAME.test(target)) return; // nothing says what it guards
1120
+ const t = await readLock(join(cfg.dir, target), cfg);
1121
+ // Still guarding its victim: that is the reaping path's business, not housekeeping's.
1122
+ if (t.kind === "unreadable" || (t.kind !== "missing" && identity(t) === victim)) return;
1123
+ }
1124
+ // The victim is gone for good (identities are never reused), or the claim is empty/corrupt
1125
+ // (never held: a claimer holds only after reading its token back). Removed under the protocol.
1126
+ const key = observedKey(s);
1127
+ await removeUnderClaim(join(cfg.dir, m[1]), path, identity(s), (c) => observedKey(c) === key, cfg);
1128
+ }
1129
+
1130
+ async function housekeep(names: string[], cfg: Cfg): Promise<void> {
1131
+ const t = cfg.mono();
1132
+ const lastRun = housekeptAt.get(cfg.dir);
1133
+ if (lastRun !== undefined && t >= lastRun && t - lastRun < HOUSEKEEPING_EVERY_MS) return;
1134
+ housekeptAt.set(cfg.dir, t);
1135
+ for (const name of names) {
1136
+ try {
1137
+ await collectOne(name, cfg);
1138
+ } catch (e) {
1139
+ if (!isTransient(e)) ioTrouble(cfg, "housekeeping", join(cfg.dir, name), e);
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+ // ---- fairness: FIFO waiter tickets ------------------------------------------
1145
+
1146
+ interface Ticket {
1147
+ path: string;
1148
+ name: string;
1149
+ body: string;
1150
+ /** Set once the wait is over: nothing may re-create the ticket after that. */
1151
+ dropped: boolean;
1152
+ /** The refresh in flight, if any (the heartbeat timer and the wake-ups share it). */
1153
+ refreshing?: Promise<void>;
1154
+ }
1155
+ const TICKET_NAME = /^wait-\d{15}-[0-9a-f-]{36}\.ticket$/;
1156
+ /** Tickets of the waits in progress in this process, for the exit hook. */
1157
+ const tickets = new Set<string>();
1158
+ const ticketWarned = new Set<string>();
1159
+
1160
+ /** Tickets only order the attempts; exclusion never depends on them. Say so once per dir. */
1161
+ function ticketTrouble(cfg: Cfg, path: string, e: unknown): void {
1162
+ if (ticketWarned.has(cfg.dir)) return;
1163
+ ticketWarned.add(cfg.dir);
1164
+ warn(cfg, "verification slot: waiter ticket I/O failed, fairness is best effort", { path, code: errCode(e) ?? String(e) });
1165
+ }
1166
+
1167
+ async function writeTicket(t: Ticket, cfg: Cfg): Promise<void> {
1168
+ for (let retried = false; ; retried = true) {
1169
+ try {
1170
+ await writeFile(t.path, t.body, { flag: "wx" });
1171
+ return;
1172
+ } catch (e) {
1173
+ const code = errCode(e);
1174
+ if (code === "EEXIST") return;
1175
+ if (code === "ENOENT" && !retried && (await recreateDir(cfg))) continue;
1176
+ ticketTrouble(cfg, t.path, e);
1177
+ return;
1178
+ }
1179
+ }
1180
+ }
1181
+
1182
+ async function createTicket(cfg: Cfg): Promise<Ticket> {
1183
+ const startedAt = Math.max(0, Math.floor(cfg.now()));
1184
+ const name = `wait-${String(startedAt).padStart(15, "0")}-${randomUUID()}.ticket`;
1185
+ const info: LockInfo = { pid: cfg.pid, hostname: cfg.hostname, token: randomUUID(), startedAt, cwd: "", command: "wait" };
1186
+ const t: Ticket = { path: join(cfg.dir, name), name, body: JSON.stringify(info), dropped: false };
1187
+ hookExit();
1188
+ tickets.add(t.path);
1189
+ await writeTicket(t, cfg);
1190
+ return t;
1191
+ }
1192
+
1193
+ /**
1194
+ * Refresh the ticket's mtime: every heartbeat and on every wake-up. A ticket
1195
+ * deleted by someone who judged it dead comes back under its old name (same place).
1196
+ */
1197
+ function refreshTicket(t: Ticket, cfg: Cfg): Promise<void> {
1198
+ t.refreshing ??= (async () => {
1199
+ try {
1200
+ await cfg.utimes(t.path, new Date(cfg.now()));
1201
+ } catch (e) {
1202
+ if (errCode(e) !== "ENOENT") ticketTrouble(cfg, t.path, e);
1203
+ else if (!t.dropped) await writeTicket(t, cfg);
1204
+ }
1205
+ })().finally(() => {
1206
+ t.refreshing = undefined;
1207
+ });
1208
+ return t.refreshing;
1209
+ }
1210
+
1211
+ async function dropTicket(t: Ticket, cfg: Cfg): Promise<void> {
1212
+ t.dropped = true;
1213
+ tickets.delete(t.path);
1214
+ if (t.refreshing) await t.refreshing;
1215
+ await unlinkRetry(t.path, cfg);
1216
+ }
1217
+
1218
+ /** Per process: since when (mono) each ticket has been seen with the same key. Tickets are advisory. */
1219
+ const ticketSeen = new Map<string, { key: string; first: number }>();
1220
+
1221
+ function ticketUnchangedMs(path: string, key: string, cfg: Cfg): number {
1222
+ const t = cfg.mono();
1223
+ const o = ticketSeen.get(path);
1224
+ if (o && o.key === key && t >= o.first) return t - o.first;
1225
+ if (ticketSeen.size > 256) ticketSeen.clear();
1226
+ ticketSeen.set(path, { key, first: t });
1227
+ return 0;
1228
+ }
1229
+
1230
+ /** Live while refreshed within 2 heartbeats, by its mtime and by this process's looks; a dead same-host PID ends it at once. */
1231
+ function ticketLive(path: string, s: LockState, cfg: Cfg): boolean {
1232
+ if (s.kind === "missing") return false;
1233
+ if (s.kind === "unreadable") return true;
1234
+ if (ownerDead(s, cfg)) return false;
1235
+ const ttl = s.kind === "corrupt" ? cfg.corruptGraceMs : 2 * cfg.heartbeatMs;
1236
+ // The second test catches an mtime that looks fresh because the clock stepped back.
1237
+ return cfg.now() - s.mtimeMs <= ttl && ticketUnchangedMs(path, observedKey(s), cfg) < ttl;
1238
+ }
1239
+
1240
+ /**
1241
+ * FIFO: true when fewer than `max` live tickets are older than `own` (than any
1242
+ * ticket, for a caller that does not wait). Dead tickets are deleted; their names
1243
+ * are unique, so a delete by path cannot hit another ticket. The same listing
1244
+ * drives the housekeeping.
1245
+ */
1246
+ async function eligible(own: Ticket | undefined, max: number, cfg: Cfg): Promise<boolean> {
1247
+ let names: string[];
1248
+ try {
1249
+ names = await readdir(cfg.dir);
1250
+ } catch (e) {
1251
+ const code = errCode(e);
1252
+ // No dir (a temp cleaner) means no tickets either; the attempt re-creates it.
1253
+ if (code !== "ENOENT" && code !== "ENOTDIR") ticketTrouble(cfg, cfg.dir, e);
1254
+ return true;
1255
+ }
1256
+ await housekeep(names, cfg);
1257
+ let ahead = 0;
1258
+ for (const name of names.filter((n) => TICKET_NAME.test(n)).sort()) {
1259
+ if (own && name >= own.name) break;
1260
+ const path = join(cfg.dir, name);
1261
+ let s: LockState;
1262
+ try {
1263
+ s = await readLock(path, cfg);
1264
+ } catch (e) {
1265
+ ticketTrouble(cfg, path, e);
1266
+ continue;
1267
+ }
1268
+ if (ticketLive(path, s, cfg)) {
1269
+ if (++ahead >= max) return false;
1270
+ } else if (s.kind !== "missing") {
1271
+ ticketSeen.delete(path);
1272
+ try {
1273
+ await cfg.unlink(path);
1274
+ } catch (e) {
1275
+ if (errCode(e) !== "ENOENT") ticketTrouble(cfg, path, e);
1276
+ }
1277
+ }
1278
+ }
1279
+ return true;
1280
+ }
1281
+
1282
+ // ---- file slots -------------------------------------------------------------
1283
+
1284
+ function slotPathOf(dir: string, i: number): string {
1285
+ return join(dir, `slot-${i}.lock`);
1286
+ }
1287
+
1288
+ /** One pass over the slots. `aged` collects the locks that are old but not yet confirmed stale. */
1289
+ async function tryAcquireOnce(opts: SlotOptions, cfg: Cfg, aged: Set<string>): Promise<SlotHandle | undefined> {
1290
+ for (let i = 0; i < opts.max; i++) {
1291
+ const path = slotPathOf(cfg.dir, i);
1292
+ for (let attempt = 0; attempt < 3; attempt++) {
1293
+ const token = randomUUID();
1294
+ const info: LockInfo = { pid: cfg.pid, hostname: cfg.hostname, token, startedAt: cfg.now(), cwd: opts.meta.cwd, command: opts.meta.command };
1295
+ if (await createOwned(path, info, cfg, true, () => dropStray(path, token, cfg))) return makeFileHandle(path, token, opts, cfg);
1296
+ const at = cfg.mono();
1297
+ const cur = await readLock(path, cfg);
1298
+ if (cur.kind === "missing") {
1299
+ strays.delete(path); // ours, if any, is gone too
1300
+ continue; // released meanwhile: create again
1301
+ }
1302
+ if (cur.kind === "unreadable") break;
1303
+ const v = await lockVerdict(path, cur, at, cfg);
1304
+ if (v !== "stale") {
1305
+ if (v === "aged") aged.add(path);
1306
+ break;
1307
+ }
1308
+ const r = await reap(path, cur, cfg);
1309
+ if (r !== "removed" && r !== "gone") {
1310
+ if (r === "contended") aged.add(path);
1311
+ break;
1312
+ }
1313
+ }
1314
+ }
1315
+ return undefined;
1316
+ }
1317
+
1318
+ /** Slot paths this process keeps watching after a call gave up on them (see the header). */
1319
+ const watched = new Set<string>();
1320
+
1321
+ /** One background look: reap the lock if it is stale. True while it is still worth watching. */
1322
+ async function watchPass(path: string, cfg: Cfg): Promise<boolean> {
1323
+ const at = cfg.mono();
1324
+ const cur = await readLock(path, cfg);
1325
+ if (cur.kind === "missing") return false;
1326
+ if (cur.kind === "unreadable") return true;
1327
+ const v = await lockVerdict(path, cur, at, cfg);
1328
+ if (v !== "stale") return v === "aged";
1329
+ return (await reap(path, cur, cfg)) === "contended";
1330
+ }
1331
+
1332
+ function watchAged(path: string, cfg: Cfg): void {
1333
+ if (watched.has(path)) return;
1334
+ watched.add(path);
1335
+ const until = cfg.mono() + cfg.staleMs + 2 * (cfg.heartbeatMs + cfg.claimHoldMaxMs);
1336
+ const schedule = (): void => {
1337
+ const t = setTimeout(() => {
1338
+ void watchPass(path, cfg)
1339
+ .catch((e: unknown) => {
1340
+ warn(cfg, "verification slot: background reclaim failed", { path, code: errCode(e) ?? String(e) });
1341
+ return false;
1342
+ })
1343
+ .then((again) => {
1344
+ if (again && cfg.mono() < until) schedule();
1345
+ else watched.delete(path);
1346
+ });
1347
+ }, cfg.heartbeatMs);
1348
+ t.unref();
1349
+ };
1350
+ schedule();
1351
+ }
1352
+
1353
+ function makeFileHandle(path: string, token: string, opts: SlotOptions, cfg: Cfg): SlotHandle {
1354
+ hookExit();
1355
+ const entry: Held = { path, token, pid: cfg.pid, hostname: cfg.hostname };
1356
+ held.add(entry);
1357
+ // held -> releasing (an attempt runs) -> done, or -> deferred (retried on a timer) -> ...
1358
+ let phase: "held" | "releasing" | "deferred" | "done" = "held";
1359
+ let lost = false;
1360
+ let tick: Promise<void> | undefined;
1361
+ let attempt: Promise<void> | undefined;
1362
+ let retryTimer: NodeJS.Timeout | undefined;
1363
+ let deferrals = 0;
1364
+ let beatWarned = false;
1365
+ const beating = () => phase === "held" || phase === "deferred";
1366
+ const maxDeferrals = Math.max(1, Math.ceil(cfg.staleMs / cfg.heartbeatMs));
1367
+
1368
+ const finish = () => {
1369
+ phase = "done";
1370
+ clearInterval(hb);
1371
+ clearTimeout(retryTimer);
1372
+ held.delete(entry);
1373
+ };
1374
+
1375
+ /** The file is gone or someone else's. While held, that is a loss; while a release is pending, it is done. */
1376
+ const notOurs = () => {
1377
+ const wasHeld = phase === "held";
1378
+ finish();
1379
+ if (!wasHeld) return;
1380
+ lost = true;
1381
+ warn(cfg, "verification slot lost: another process reclaimed it while it was held", { path });
1382
+ try {
1383
+ opts.onLost?.();
1384
+ } catch (e) {
1385
+ warn(cfg, "verification slot: onLost callback threw", { path, error: String(e) });
1386
+ }
1387
+ };
1388
+
1389
+ const beat = async (): Promise<void> => {
1390
+ const cur = await readLock(path, cfg);
1391
+ if (!beating() || cur.kind === "unreadable") return; // a scanner has it open: next tick
1392
+ if (cur.kind !== "ok" || cur.info.token !== token) return notOurs();
1393
+ for (let i = 0; ; i++) {
1394
+ if (!beating()) return; // a release began: never touch the file again
1395
+ try {
1396
+ await cfg.utimes(path, new Date(cfg.now()));
1397
+ beatWarned = false;
1398
+ return;
1399
+ } catch (e) {
1400
+ const code = errCode(e) ?? String(e);
1401
+ if (code === "ENOENT") {
1402
+ if (beating()) notOurs();
1403
+ return;
1404
+ }
1405
+ if (!TRANSIENT.has(code) || i >= cfg.unlinkRetries) {
1406
+ if (!beatWarned) warn(cfg, "verification slot: heartbeat failed", { path, code });
1407
+ beatWarned = true;
1408
+ return;
1409
+ }
1410
+ }
1411
+ await sleep(cfg.unlinkRetryMs * 2 ** i);
1412
+ }
1413
+ };
1414
+ const hb = setInterval(() => {
1415
+ if (tick || !beating()) return;
1416
+ tick = beat()
1417
+ .catch((e: unknown) => warn(cfg, "verification slot: heartbeat failed", { path, code: errCode(e) ?? String(e) }))
1418
+ .finally(() => {
1419
+ tick = undefined;
1420
+ });
1421
+ }, cfg.heartbeatMs);
1422
+ hb.unref();
1423
+
1424
+ /** One delete of our own file under its claim. True when the file is no longer ours. */
1425
+ const deleteOwn = async (): Promise<boolean> => {
1426
+ for (let n = 0; ; n++) {
1427
+ const r = await removeUnderClaim(path, path, token, (s) => s.kind === "ok" && s.info.token === token, cfg);
1428
+ // "contended": a process judging us stale holds the claim for a moment; it deletes our file.
1429
+ if (r === "contended" && n < cfg.unlinkRetries) {
1430
+ await sleep(cfg.unlinkRetryMs * 2 ** n);
1431
+ continue;
1432
+ }
1433
+ return r === "removed" || r === "gone" || r === "changed";
1434
+ }
1435
+ };
1436
+
1437
+ const runAttempt = async (): Promise<void> => {
1438
+ phase = "releasing";
1439
+ clearTimeout(retryTimer);
1440
+ if (tick) await tick;
1441
+ let settled = false;
1442
+ try {
1443
+ settled = await deleteOwn();
1444
+ } catch (e) {
1445
+ warn(cfg, "verification slot: release failed", { path, code: errCode(e) ?? String(e) });
1446
+ }
1447
+ if (settled) return finish();
1448
+ // Not confirmed: keep the file ours (heartbeat and exit hook) and retry in the background.
1449
+ phase = "deferred";
1450
+ if (++deferrals > maxDeferrals) {
1451
+ finish();
1452
+ warn(cfg, "verification slot: release gave up, slot left to stale detection", { path });
1453
+ return;
1454
+ }
1455
+ if (deferrals === 1) warn(cfg, "verification slot: release incomplete, retrying in the background", { path });
1456
+ retryTimer = setTimeout(() => void release(), cfg.heartbeatMs);
1457
+ retryTimer.unref();
1458
+ };
1459
+
1460
+ const release = (): Promise<void> => {
1461
+ if (phase === "done") return Promise.resolve();
1462
+ attempt ??= runAttempt().finally(() => {
1463
+ attempt = undefined;
1464
+ });
1465
+ return attempt;
1466
+ };
1467
+
1468
+ return {
1469
+ release,
1470
+ get lost() {
1471
+ return lost;
1472
+ },
1473
+ };
1474
+ }
1475
+
1476
+ /**
1477
+ * Delay before wake-up `attempt` (0-based): exponential from `minMs` to `maxMs`,
1478
+ * with upward-only jitter (x1 to x1.5) capped at `maxMs`, so never below `minMs`
1479
+ * (plan 1.4.1.d: 250 ms -> 2 s).
1480
+ */
1481
+ export function nextBackoffMs(attempt: number, random: number, minMs: number, maxMs: number): number {
1482
+ const base = Math.min(maxMs, minMs * 2 ** Math.min(attempt, 30));
1483
+ return Math.max(1, Math.round(Math.min(maxMs, base * (1 + random * 0.5))));
1484
+ }
1485
+
1486
+ /** The file-slot wait loop. Unexpected errors propagate to `acquireSlot`, which turns them into busy. */
1487
+ async function acquireFile(o: SlotOptions, cfg: Cfg): Promise<SlotResult> {
1488
+ const deadline = cfg.mono() + Math.max(0, o.waitMs);
1489
+ const ticket = o.waitMs > 0 ? await createTicket(cfg) : undefined;
1490
+ let ticketBeat: NodeJS.Timeout | undefined;
1491
+ let aged = new Set<string>();
1492
+ let recreated = false;
1493
+ try {
1494
+ if (ticket) {
1495
+ // Tickets are heartbeated while waiting, so a long attempt never lets them expire.
1496
+ ticketBeat = setInterval(() => void refreshTicket(ticket, cfg), cfg.heartbeatMs);
1497
+ ticketBeat.unref();
1498
+ }
1499
+ for (let k = 0; ; k++) {
1500
+ cfg.onAttempt?.();
1501
+ if (ticket && k > 0) await refreshTicket(ticket, cfg);
1502
+ if (await eligible(ticket, o.max, cfg)) {
1503
+ aged = new Set();
1504
+ let h: SlotHandle | undefined;
1505
+ try {
1506
+ h = await tryAcquireOnce(o, cfg, aged);
1507
+ } catch (e) {
1508
+ // The dir vanished (a temp cleaner): re-create it once and try again.
1509
+ if (errCode(e) !== "ENOENT" || recreated) throw e;
1510
+ recreated = true;
1511
+ if (!(await recreateDir(cfg))) throw e;
1512
+ h = await tryAcquireOnce(o, cfg, aged);
1513
+ }
1514
+ if (h) {
1515
+ if (o.signal?.aborted) {
1516
+ await h.release();
1517
+ return { busy: true };
1518
+ }
1519
+ return h;
1520
+ }
1521
+ }
1522
+ const remaining = deadline - cfg.mono();
1523
+ if (o.signal?.aborted) return { busy: true };
1524
+ if (remaining <= 0) {
1525
+ // Out of time with an old lock not yet confirmed: keep looking in the background.
1526
+ for (const path of aged) watchAged(path, cfg);
1527
+ return { busy: true };
1528
+ }
1529
+ // Observations need a wake-up at least every 2 heartbeats to stay unbroken;
1530
+ // the last wait is cut to the deadline.
1531
+ const delay = Math.min(remaining, cfg.heartbeatMs, nextBackoffMs(k, cfg.random(), cfg.backoffMinMs, cfg.backoffMaxMs));
1532
+ const aborted = await new Promise<boolean>((resolve) => {
1533
+ const onAbort = () => {
1534
+ clearTimeout(t);
1535
+ resolve(true);
1536
+ };
1537
+ const t = setTimeout(() => {
1538
+ o.signal?.removeEventListener("abort", onAbort);
1539
+ resolve(false);
1540
+ }, delay);
1541
+ o.signal?.addEventListener("abort", onAbort, { once: true });
1542
+ });
1543
+ if (aborted) return { busy: true };
1544
+ }
1545
+ } finally {
1546
+ clearInterval(ticketBeat);
1547
+ if (ticket) await dropTicket(ticket, cfg);
1548
+ }
1549
+ }
1550
+
1551
+ /**
1552
+ * Acquire one of `max` machine-wide verification slots, waiting up to `waitMs`
1553
+ * with exponential backoff and jitter. Resolves `{busy:true}` on timeout or
1554
+ * abort, and on an unexpected file-system error (logged); never rejects.
1555
+ */
1556
+ export async function acquireSlot(opts: SlotOptions, deps?: SlotDeps): Promise<SlotResult> {
1557
+ const cfg = resolveCfg(deps);
1558
+ if (opts.signal?.aborted) return { busy: true };
1559
+ const max = Math.max(1, Math.floor(opts.max));
1560
+ // QA-1.4-31 (validated by Phase 1.1): NaN would never reach the deadline.
1561
+ const waitMs = Number.isFinite(opts.waitMs) ? Math.max(0, opts.waitMs) : 0;
1562
+ const o = { ...opts, max, waitMs };
1563
+ let writable: boolean;
1564
+ try {
1565
+ writable = await dirWritable(cfg);
1566
+ } catch (e) {
1567
+ return fsFailure(cfg, e);
1568
+ }
1569
+ if (!writable) {
1570
+ if (!degradedLogged.has(cfg.dir)) {
1571
+ degradedLogged.add(cfg.dir);
1572
+ warn(cfg, "verification slot: temp dir unwritable, using an in-process semaphore", { dir: cfg.dir });
1573
+ }
1574
+ return acquireLocal(o, cfg);
1575
+ }
1576
+ try {
1577
+ return await acquireFile(o, cfg);
1578
+ } catch (e) {
1579
+ return fsFailure(cfg, e);
1580
+ }
1581
+ }
1582
+
1583
+ /** Run `fn` while holding a slot; the slot is released on every exit path. */
1584
+ export async function withSlot<T>(
1585
+ opts: SlotOptions,
1586
+ fn: () => Promise<T>,
1587
+ deps?: SlotDeps,
1588
+ ): Promise<{ busy: true } | { value: T }> {
1589
+ const s = await acquireSlot(opts, deps);
1590
+ if ("busy" in s) return s;
1591
+ let out: { value: T };
1592
+ try {
1593
+ out = { value: await fn() };
1594
+ } finally {
1595
+ // release() never rejects (a failed delete is retried in the background and
1596
+ // logged), so it can neither replace fn's error nor mask its value.
1597
+ await s.release();
1598
+ }
1599
+ return out;
1600
+ }
1601
+
1602
+ /** Synchronous variant of the exit hook, exported for tests. */
1603
+ export const releaseAllSlotsSync = releaseAllSync;