my-durable 0.0.116 → 0.0.118

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.
@@ -113,6 +113,25 @@ export const defaultBackupIo = (): BackupIo => ({
113
113
  now: () => Date.now(),
114
114
  });
115
115
 
116
+ // ---------------------------------------------------------------- mutex
117
+
118
+ // run-11 h2-3: create and restore share ONE advisory, per-process gate.
119
+ // Two backup flows racing inside one process (concurrent CLI invocations,
120
+ // tests, a create begun while a restore still walks) used to interleave their
121
+ // fs phases — a restore's renameAside could swallow files a half-finished
122
+ // create was still reading. Cross-process races remain the healthz probe's
123
+ // job; this gate only serializes what one process can actually race.
124
+ let backupGate: Promise<unknown> = Promise.resolve();
125
+
126
+ /** Run `op` holding the backup gate — every create/restore passes through
127
+ * here. FIFO by call order, advisory, failure-safe: a rejected predecessor
128
+ * still releases (the gate chains on a swallowed catch, never on `run`). */
129
+ function withBackupGate<T>(op: () => Promise<T>): Promise<T> {
130
+ const run = backupGate.then(op, op);
131
+ backupGate = run.catch(() => {});
132
+ return run;
133
+ }
134
+
116
135
  // ---------------------------------------------------------------- create
117
136
 
118
137
  /** Entry 0 of every backup zip: what was backed up, by which build. */
@@ -196,6 +215,11 @@ async function walkHome(io: BackupIo, home: string, out: string, maxBytes: numbe
196
215
  * module's.
197
216
  */
198
217
  export async function createBackup(io: BackupIo, opts: CreateBackupOptions): Promise<CreateBackupResult> {
218
+ // run-11 h2-3: serialized against restore (and other creates) per process.
219
+ return withBackupGate(() => createBackupLocked(io, opts));
220
+ }
221
+
222
+ async function createBackupLocked(io: BackupIo, opts: CreateBackupOptions): Promise<CreateBackupResult> {
199
223
  // R9 (run-8 u7): the probe restore already runs, mirrored verbatim — a
200
224
  // backup taken while the daemon answers captures catalog.sqlite,
201
225
  // agent.sqlite and -wal/-shm at different instants, i.e. a live "backup"
@@ -214,6 +238,18 @@ export async function createBackup(io: BackupIo, opts: CreateBackupOptions): Pro
214
238
  if (!homeStat.isDirectory()) throw invalid(`home is not a directory: ${home}`);
215
239
 
216
240
  const files = await walkHome(io, home, out, opts.maxBytes ?? MAX_BACKUP_BYTES);
241
+ // run-11 h2-3: the walk can take minutes on a real home, and a daemon
242
+ // started during it writes catalog.sqlite/agent.sqlite while we are about
243
+ // to read them — the archive would be torn exactly like the pre-probe case.
244
+ // Re-probe AFTER the walk and BEFORE the first entry byte is read: any
245
+ // answer aborts on the same surface as the refusal above, with nothing
246
+ // written (the zip build and io.writeFile have not run yet).
247
+ if (opts.healthzUrl && (await deviceIsRunning(io, opts.healthzUrl))) {
248
+ throw new BackupError(
249
+ "device_running",
250
+ "the device came online during the backup — a live sqlite handle would tear the archive; stop it (`dpi device stop`) and retry",
251
+ );
252
+ }
217
253
  const bytes = files.reduce((n, f) => n + f.size, 0);
218
254
  const manifest: BackupManifest = {
219
255
  createdAt: new Date(io.now()).toISOString(),
@@ -510,6 +546,11 @@ export async function deviceIsRunning(io: BackupIo, healthzUrl: string): Promise
510
546
  * manifest always comes first.
511
547
  */
512
548
  export async function restoreBackup(io: BackupIo, opts: RestoreBackupOptions): Promise<RestoreBackupResult> {
549
+ // run-11 h2-3: serialized against create (and other restores) per process.
550
+ return withBackupGate(() => restoreBackupLocked(io, opts));
551
+ }
552
+
553
+ async function restoreBackupLocked(io: BackupIo, opts: RestoreBackupOptions): Promise<RestoreBackupResult> {
513
554
  const home = resolve(opts.home);
514
555
  if (opts.healthzUrl && (await deviceIsRunning(io, opts.healthzUrl))) {
515
556
  throw new BackupError("device_running", "the device is running — stop it first (`dpi device stop`)");
@@ -216,33 +216,61 @@ export function isNotARepoError(e: unknown): boolean {
216
216
  * actually starts, so queueing never eats the timeout. */
217
217
  export const GIT_SPAWN_BUDGET = 12;
218
218
  let gitSpawnLive = 0;
219
- const gitSpawnQueue: (() => void)[] = [];
220
-
221
- /** Take a slot (or queue FIFO for one) — the caller owns the slot until
222
- * releaseGitSpawn(). No nesting: a slot is held across exactly ONE child,
223
- * so a queued git child can never be waiting on a spawn that needs this
224
- * queue to drain — no deadlock. */
225
- function acquireGitSpawn(): Promise<void> {
219
+ // run-11 h2-2: the single FIFO queue starved interactive ops — one
220
+ // 50-path status-batch parks ~650 low spawns, and the status panel the user
221
+ // is LOOKING at queued behind all of them. Two wake lanes now: high holds
222
+ // interactive single ops (a bare /git/status, the /git mutation route);
223
+ // low holds every fan-out (status-batch, the boot project-seed walk,
224
+ // git-files turns). FIFO within each lane; a freed slot wakes high first;
225
+ // nobody is ever refused and no spawn changes shape — only the wake order.
226
+ const gitSpawnQueueHigh: (() => void)[] = [];
227
+ const gitSpawnQueueLow: (() => void)[] = [];
228
+
229
+ /** Take a slot (or queue FIFO in your lane for one) — the caller owns the slot
230
+ * until releaseGitSpawn(). No nesting: a slot is held across exactly ONE
231
+ * child, so a queued git child can never be waiting on a spawn that needs
232
+ * this queue to drain — no deadlock. */
233
+ function acquireGitSpawn(priority?: "high" | "low"): Promise<void> {
226
234
  if (gitSpawnLive < GIT_SPAWN_BUDGET) {
227
235
  gitSpawnLive++;
228
236
  return Promise.resolve();
229
237
  }
230
- return new Promise<void>((wake) => gitSpawnQueue.push(wake));
238
+ return new Promise<void>((wake) => (priority === "high" ? gitSpawnQueueHigh : gitSpawnQueueLow).push(wake));
231
239
  }
232
240
 
233
- /** Free a slot — handed straight to the longest-waiting caller when one
234
- * exists (the live count already covers the handover), else returned. */
241
+ /** Free a slot — handed straight to the longest-waiting HIGH caller first
242
+ * (run-11 h2-2), then the longest-waiting low one, when either exists (the
243
+ * live count already covers the handover), else returned. */
235
244
  function releaseGitSpawn() {
236
- const next = gitSpawnQueue.shift();
245
+ const next = gitSpawnQueueHigh.shift() ?? gitSpawnQueueLow.shift();
237
246
  if (next) next();
238
247
  else gitSpawnLive--;
239
248
  }
240
249
 
250
+ /** run-11 h2-2: the semaphore's state for deviceVitals — live children,
251
+ * waiting callers, and how many of those waiters are interactive ("high")
252
+ * ops parked behind a fan-out. Pure read, no side effects. */
253
+ export function gitSpawnStats(): { live: number; queued: number; queuedHigh: number } {
254
+ return {
255
+ live: gitSpawnLive,
256
+ queued: gitSpawnQueueHigh.length + gitSpawnQueueLow.length,
257
+ queuedHigh: gitSpawnQueueHigh.length,
258
+ };
259
+ }
260
+
241
261
  /** One git call; rejects on non-zero exit with stderr in the message. Every
242
262
  * spawn runs under the budget above — see GIT_SPAWN_BUDGET. (gh() stays
243
- * outside: forge calls are single, user-initiated, and never fan out.) */
244
- export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
245
- return acquireGitSpawn()
263
+ * outside: forge calls are single, user-initiated, and never fan out.)
264
+ * `priority: "high"` (run-11 h2-2) only changes the WAKE order while the
265
+ * budget is saturated — the per-op timeout still starts at child start. */
266
+ export function git(
267
+ cwd: string,
268
+ args: string[],
269
+ timeout = GIT_TIMEOUT,
270
+ pin?: RepoPin,
271
+ priority?: "high" | "low",
272
+ ): Promise<string> {
273
+ return acquireGitSpawn(priority)
246
274
  .then(
247
275
  () =>
248
276
  new Promise<string>((ok, fail) => {
@@ -320,7 +348,7 @@ export async function gitStatusBatch(paths: string[]): Promise<Record<string, Gi
320
348
  const entries = await Promise.all(
321
349
  unique.map(async (p): Promise<[string, GitStatus | { error: string }]> => {
322
350
  try {
323
- return [p, await gitStatus(p)];
351
+ return [p, await gitStatus(p, Date.now(), "low")];
324
352
  } catch (e) {
325
353
  return [p, { error: String((e as Error)?.message ?? e).slice(0, 120) }];
326
354
  }
@@ -415,11 +443,11 @@ function ensureWatcher(root: string) {
415
443
  * never served). The absolute git dir is NOT confined: redirects and linked
416
444
  * worktrees whose gitdir lives elsewhere are operator territory and are
417
445
  * followed via the returned pin (the agent itself is unsandboxed by design). */
418
- export async function resolveRepoPin(path: string): Promise<RepoPin | undefined> {
446
+ export async function resolveRepoPin(path: string, priority?: "high" | "low"): Promise<RepoPin | undefined> {
419
447
  if (!repoRootAllowed) return undefined;
420
448
  const [topLevel, gitDir] = await Promise.all([
421
- git(path, ["rev-parse", "--show-toplevel"]),
422
- git(path, ["rev-parse", "--absolute-git-dir"]),
449
+ git(path, ["rev-parse", "--show-toplevel"], GIT_TIMEOUT, undefined, priority),
450
+ git(path, ["rev-parse", "--absolute-git-dir"], GIT_TIMEOUT, undefined, priority),
423
451
  ]);
424
452
  const pin: RepoPin = { gitDir: gitDir.trim(), workTree: topLevel.trim() };
425
453
  // R23 (operator decision): durable-pi WRAPS pi/pi-durable — the agent is
@@ -451,8 +479,11 @@ export function clearGitStatusCache() {
451
479
  }
452
480
 
453
481
  /** Structured status for a folder: everything the UIs show, one call.
454
- * `now` is injectable so a test can age the caches without sleeping. */
455
- export async function gitStatus(path: string, now = Date.now()): Promise<GitStatus> {
482
+ * `now` is injectable so a test can age the caches without sleeping.
483
+ * run-11 h2-2: a bare call (the /git/status route, session create) is an
484
+ * INTERACTIVE single op and rides the high spawn lane; fan-out callers
485
+ * (gitStatusBatch, the store's boot seed) pass "low" explicitly. */
486
+ export async function gitStatus(path: string, now = Date.now(), priority: "high" | "low" = "high"): Promise<GitStatus> {
456
487
  // One key per repo, not per spelling: `D:\\x`, `d:/x/` and `D:/x` land on
457
488
  // the SAME entry (cacheKey), so single-flight dedupes every spelling.
458
489
  const key = cacheKey(path);
@@ -463,14 +494,14 @@ export async function gitStatus(path: string, now = Date.now()): Promise<GitStat
463
494
  if (failed && now - failed.at < STATUS_FAIL_TTL) throw new Error(failed.msg);
464
495
  const running = statusInFlight.get(key);
465
496
  if (running) return running;
466
- const p = statusOnce(path, key).finally(() => {
497
+ const p = statusOnce(path, key, priority).finally(() => {
467
498
  if (statusInFlight.get(key) === p) statusInFlight.delete(key);
468
499
  });
469
500
  statusInFlight.set(key, p);
470
501
  return p;
471
502
  }
472
503
 
473
- async function statusOnce(path: string, key: string): Promise<GitStatus> {
504
+ async function statusOnce(path: string, key: string, priority: "high" | "low"): Promise<GitStatus> {
474
505
  const out: GitStatus = { repo: false };
475
506
  try {
476
507
  // Reach git at all before trusting any "empty" answer: git missing from
@@ -484,7 +515,7 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
484
515
  // The pin rides GIT_DIR/GIT_WORK_TREE into every later spawn regardless.
485
516
  let pin: RepoPin | undefined;
486
517
  try {
487
- pin = await resolveRepoPin(path);
518
+ pin = await resolveRepoPin(path, priority);
488
519
  } catch (e) {
489
520
  if (!String((e as Error).message).includes("start dirs")) throw e;
490
521
  out.repo = true; // repo presence only — no root, files, branches,
@@ -493,8 +524,8 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
493
524
  statusFailCache.delete(key);
494
525
  return out;
495
526
  }
496
- const g = (args: string[], t?: number) => git(path, args, t, pin);
497
- const root = pin?.workTree ?? (await git(path, ["rev-parse", "--show-toplevel"])).trim();
527
+ const g = (args: string[], t?: number) => git(path, args, t, pin, priority);
528
+ const root = pin?.workTree ?? (await git(path, ["rev-parse", "--show-toplevel"], GIT_TIMEOUT, pin, priority)).trim();
498
529
  out.repo = true;
499
530
  out.root = root;
500
531
  // Everything after toplevel runs in PARALLEL — status is the long pole
@@ -768,8 +799,10 @@ export async function gitOp(
768
799
  // operator territory — see resolveRepoPin); the resolved pin rides
769
800
  // GIT_DIR/GIT_WORK_TREE into EVERY spawn below, so per-spawn .git discovery
770
801
  // never re-runs and the check cannot be raced.
771
- const pin = await resolveRepoPin(path);
772
- const g = (args: string[], t?: number) => git(path, args, t, pin);
802
+ const pin = await resolveRepoPin(path, "high");
803
+ // run-11 h2-2: gitOp IS the mutation route — every op here is one click a
804
+ // user is waiting on, so all of its spawns (guard + data) ride the high lane.
805
+ const g = (args: string[], t?: number) => git(path, args, t, pin, "high");
773
806
  const ghP = (args: string[], t?: number) => gh(path, args, t, pin);
774
807
  switch (op) {
775
808
  case "diff":
@@ -212,6 +212,22 @@ const TRANSCRIPT_HITS_PER_AGENT = 3;
212
212
  * total cardinality (leader-probe: 2 conversations → 5 hits, linear in forks). */
213
213
  const TRANSCRIPT_HITS_PER_SESSION = 12;
214
214
 
215
+ /** run-11 h2-4: the missing-dir memo's TTL. An operator who manually copies a
216
+ * zombie row's sessions/<id> dir back has NO API touch to clear the memo, so
217
+ * a Set<string> hid the session from scope=all search for the process
218
+ * lifetime. Memoize-at timestamp + lazy expiry on read: the row re-enters
219
+ * search ≤5 min later; a re-probe that still ENOENTs re-memoizes with a fresh
220
+ * stamp, so nothing polls more often than one open attempt per 5 min. */
221
+ const MISSING_DIR_TTL_MS = 5 * 60_000;
222
+
223
+ /** run-11 h2-4 test seam: the missing-dir memo's clock, injectable like
224
+ * git.ts's setGitExecForTests so the 5-min TTL is testable without sleeping
225
+ * (only this memo reads this clock — the store's own Date.now stays real). */
226
+ let missingDirNow: () => number = Date.now;
227
+ export function setMissingDirClockForTests(fn?: () => number) {
228
+ missingDirNow = fn ?? Date.now;
229
+ }
230
+
215
231
  /** Scheduler granularity. Schedules are minute-granular, so 30 s is enough and
216
232
  * the timer is unref'd: it never holds the process open. */
217
233
  const SCHEDULE_TICK_MS = 30_000;
@@ -838,8 +854,11 @@ export class Store {
838
854
  });
839
855
  // Seed the registry from history: a device that predates projects still
840
856
  // shows every root its sessions already live in (idempotent by rootPath).
857
+ // run-11 h2-2: this boot loop is a status FAN-OUT over every row — it
858
+ // rides the low spawn lane so one interactive status never queues
859
+ // behind the whole boot walk.
841
860
  for (const row of store.list()) {
842
- const status = await gitStatus(row.cwd).catch(() => undefined);
861
+ const status = await gitStatus(row.cwd, Date.now(), "low").catch(() => undefined);
843
862
  await store.projects
844
863
  .ensure({ rootPath: status?.repo ? (status.root ?? row.cwd) : row.cwd, kind: status?.repo ? "git" : "plain" })
845
864
  .catch(() => undefined);
@@ -2003,8 +2022,10 @@ export class Store {
2003
2022
  // run-9 G (run-8 u1): the pre-open stat failed ENOENT — the session dir
2004
2023
  // is gone (zombie row). Memo it so scope=all search stops paying for it;
2005
2024
  // any later SUCCESSFUL open un-memos (the dir may come back: restore,
2006
- // manual copy-back — crash-window variant B).
2007
- if (!create && (e as NodeJS.ErrnoException)?.code === "ENOENT") this.missingDirSessions.add(row.id);
2025
+ // manual copy-back — crash-window variant B). run-11 h2-4: the memo now
2026
+ // carries Date.now() so isMissingDirMemoized can expire it (5 min) —
2027
+ // the manual copy-back case has no open to clear it with.
2028
+ if (!create && (e as NodeJS.ErrnoException)?.code === "ENOENT") this.missingDirSessions.set(row.id, missingDirNow());
2008
2029
  throw e;
2009
2030
  }
2010
2031
  try {
@@ -3001,7 +3022,9 @@ export class Store {
3001
3022
  // or on the first failed open) never burns a TRANSCRIPT_SESSION_LIMIT
3002
3023
  // slot — skipped BEFORE the budget check, so the slots go to sessions
3003
3024
  // whose data is actually present. Un-memoed when the dir comes back.
3004
- if (this.missingDirSessions.has(row.id)) continue;
3025
+ // run-11 h2-4: TTL-bounded — the skip lasts at most 5 min per memo,
3026
+ // so a manually restored dir re-enters search on its own.
3027
+ if (this.isMissingDirMemoized(row.id)) continue;
3005
3028
  if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
3006
3029
  truncated = true;
3007
3030
  break;
@@ -3262,8 +3285,25 @@ export class Store {
3262
3285
  * them WITHOUT burning one of the 100 TRANSCRIPT_SESSION_LIMIT slots per
3263
3286
  * query (they used to cost a harness-throw + reopen stat attempt AND a
3264
3287
  * slot, newest-first). Mirrors the salvage memo's lifecycle: cleared when
3265
- * the dir is back — any successful open, a completed archive, a restore. */
3266
- private missingDirSessions = new Set<string>();
3288
+ * the dir is back — any successful open, a completed archive, a restore.
3289
+ * run-11 h2-4: Set → Map<id, memoized-at> and TTL-bounded (5 min, lazy
3290
+ * expiry in isMissingDirMemoized) — a manual dir restore re-enters search
3291
+ * without needing an API touch to clear the memo. */
3292
+ private missingDirSessions = new Map<string, number>();
3293
+
3294
+ /** run-11 h2-4: TTL-bounded read of the missing-dir memo. An entry older
3295
+ * than MISSING_DIR_TTL_MS is dropped on read — the next search re-probes
3296
+ * the row (a still-missing dir ENOENTs and re-memoizes with a fresh
3297
+ * stamp; a restored dir opens and the :2136 delete clears it for good). */
3298
+ private isMissingDirMemoized(id: string): boolean {
3299
+ const at = this.missingDirSessions.get(id);
3300
+ if (at === undefined) return false;
3301
+ if (missingDirNow() - at > MISSING_DIR_TTL_MS) {
3302
+ this.missingDirSessions.delete(id);
3303
+ return false;
3304
+ }
3305
+ return true;
3306
+ }
3267
3307
 
3268
3308
  /**
3269
3309
  * R19 (run-5 h1): the salvage memo is per-process so a corrupt session is not
@@ -10,6 +10,7 @@
10
10
  import { statfsSync } from "node:fs";
11
11
  import { cpus, loadavg, uptime as osUptime, freemem, totalmem } from "node:os";
12
12
  import { monitorEventLoopDelay } from "node:perf_hooks";
13
+ import { gitSpawnStats } from "./git.js";
13
14
 
14
15
  // --- Event-loop lag (R7 perf lane) -----------------------------------------
15
16
  //
@@ -99,6 +100,10 @@ export interface DeviceVitals {
99
100
  disk: DiskVitals;
100
101
  /** Event-loop lag — the number `loadavg` cannot express: how long ready JS waited to run. */
101
102
  eventLoop: EventLoopLagVitals;
103
+ /** Git spawn semaphore (run-11 h2-2): children live now, callers waiting
104
+ * for a slot, and how many waiters sit in the interactive "high" lane —
105
+ * the number that says "a status-batch fan-out is stalling the panel". */
106
+ gitSpawns: { live: number; queued: number; queuedHigh: number };
102
107
  pid: number;
103
108
  at: number;
104
109
  }
@@ -137,6 +142,7 @@ export function deviceVitals(diskPath: string, startedAt: number, now = Date.now
137
142
  },
138
143
  disk: diskVitals(diskPath),
139
144
  eventLoop: eventLoopLag(),
145
+ gitSpawns: gitSpawnStats(),
140
146
  pid: process.pid,
141
147
  at: now,
142
148
  };