my-durable 0.0.121 → 0.0.122

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.
@@ -36,7 +36,7 @@ import { crc32 } from "./zip.js";
36
36
  import { humanBytes } from "./gc.js";
37
37
  import { PACKAGE_VERSION } from "./store.js";
38
38
 
39
- export type BackupErrorCode = "invalid" | "device_running" | "not_found";
39
+ export type BackupErrorCode = "invalid" | "device_running" | "not_found" | "gate_timeout" | "too_many_entries";
40
40
 
41
41
  /** Typed failure, same shape as `ProjectRegistryError`: a CLI picks its exit code from `code`, not from message matching. */
42
42
  export class BackupError extends Error {
@@ -61,6 +61,12 @@ const DIR_MODE = 0o700;
61
61
  const FILE_MODE = 0o600;
62
62
  /** A deeper tree is a symlink loop, not a device home. */
63
63
  const MAX_WALK_DEPTH = 64;
64
+ /** Run-15 (u2-3): a runaway home (a symlink explosion, a pathological
65
+ * sessions tree) can enumerate far past what any real device holds — cap
66
+ * the entries the walk will even LOOK at, so createBackup fails fast with
67
+ * a clear fault instead of grinding through millions of stat calls (and
68
+ * racing the 256 MiB byte cap, which only fires per-file). */
69
+ export const MAX_WALK_ENTRIES = 200_000;
64
70
 
65
71
  export interface BackupStat {
66
72
  isFile(): boolean;
@@ -123,13 +129,53 @@ export const defaultBackupIo = (): BackupIo => ({
123
129
  // job; this gate only serializes what one process can actually race.
124
130
  let backupGate: Promise<unknown> = Promise.resolve();
125
131
 
132
+ /** Run-15 (u2-2): how long a create/restore CALLER waits (gate queue + op)
133
+ * before withBackupGate answers gate_timeout. A hung op (an fs call that
134
+ * never settles) used to leave every later caller's promise pending
135
+ * forever with nothing to surface — 10 minutes is far past any healthy
136
+ * walk/zip/write while still finite. */
137
+ export const BACKUP_GATE_TIMEOUT_MS = 10 * 60 * 1000;
138
+ /** Test seam: the fake io cannot fast-forward a real timer, so the deadline
139
+ * itself is swappable (git.ts's setGitClockForTests pattern). Call with no
140
+ * argument to restore the production default. */
141
+ let backupGateTimeoutMs = BACKUP_GATE_TIMEOUT_MS;
142
+ export function setBackupGateTimeoutForTests(ms?: number): void {
143
+ backupGateTimeoutMs = ms ?? BACKUP_GATE_TIMEOUT_MS;
144
+ }
145
+
126
146
  /** Run `op` holding the backup gate — every create/restore passes through
127
147
  * here. FIFO by call order, advisory, failure-safe: a rejected predecessor
128
- * still releases (the gate chains on a swallowed catch, never on `run`). */
148
+ * still releases (the gate chains on a swallowed catch, never on `run`).
149
+ * Run-15 (u2-2): the CALLER races the deadline above, but the gate does
150
+ * NOT — backupGate keeps chaining on the raw `run`, so a gate_timeout
151
+ * rejects only the caller while the underlying op still owns the gate
152
+ * until it settles. The hung op is deliberately not aborted: no io seam
153
+ * can cancel a half-written zip, so the honest move is to let it settle
154
+ * (or hang) and keep later callers FIFO behind it, each with their own
155
+ * timeout instead of an eternal promise. */
129
156
  function withBackupGate<T>(op: () => Promise<T>): Promise<T> {
130
157
  const run = backupGate.then(op, op);
131
158
  backupGate = run.catch(() => {});
132
- return run;
159
+ return new Promise<T>((resolve, reject) => {
160
+ const timer = setTimeout(
161
+ () => reject(new BackupError("gate_timeout", `the backup gate is still busy after ${backupGateTimeoutMs} ms — a create/restore ahead of this one has not settled; retry once it finishes`)),
162
+ backupGateTimeoutMs,
163
+ );
164
+ // NOT unref'd on purpose: the timer IS the caller's surface — a CLI whose
165
+ // op hung stays alive until the deadline, then exits with the fault
166
+ // instead of draining silently. clearTimeout below keeps the daemon free
167
+ // of stray timers once ops settle.
168
+ run.then(
169
+ (value) => {
170
+ clearTimeout(timer);
171
+ resolve(value);
172
+ },
173
+ (error) => {
174
+ clearTimeout(timer);
175
+ reject(error);
176
+ },
177
+ );
178
+ });
133
179
  }
134
180
 
135
181
  // ---------------------------------------------------------------- create
@@ -177,9 +223,17 @@ async function walkHome(io: BackupIo, home: string, out: string, maxBytes: numbe
177
223
  const outAbs = resolve(out);
178
224
  const files: WalkedFile[] = [];
179
225
  let bytes = 0;
226
+ let walkedEntries = 0;
180
227
  const visit = async (dir: string, depth: number): Promise<void> => {
181
228
  if (depth > MAX_WALK_DEPTH) throw invalid(`${dir} nests deeper than ${MAX_WALK_DEPTH} levels — refusing to walk it`);
182
229
  for (const name of (await io.readdir(dir)).sort()) {
230
+ // run-15 (u2-3): count EVERY visited entry (dirs, skips and all) — the
231
+ // walk refuses runaway enumeration before the next stat, not after.
232
+ if (++walkedEntries > MAX_WALK_ENTRIES)
233
+ throw new BackupError(
234
+ "too_many_entries",
235
+ `walked more than ${MAX_WALK_ENTRIES} entries under ${home} — this looks like a runaway home (symlink explosion?); refusing to walk further`,
236
+ );
183
237
  if (name === "node_modules") continue;
184
238
  const abs = join(dir, name);
185
239
  let entry: BackupStat;
@@ -237,6 +237,15 @@ let gitSpawnLive = 0;
237
237
  // between arrays, holds no slot, wakes nobody, refuses nobody, and changes
238
238
  // nothing for waiters that are not aged.
239
239
  const GIT_SPAWN_AGE_MS = 10_000;
240
+ /** Run-15 (u2-1): promotion is BOUNDED — at most this many waiters move per
241
+ * promoteAgedLowWaiters() call. run-13 promoted the ENTIRE aged prefix at
242
+ * once, so a burst of aged fan-out waiters (a big status-batch caught at
243
+ * the 10 s line) could splice ahead of EVERY fresh high waiter in one go
244
+ * and invert f4's starvation onto interactive traffic. Bounding the batch
245
+ * to 2 keeps the inversion two slots deep per release while progress is
246
+ * still guaranteed: every acquire(low)/release re-runs the promotion scan,
247
+ * so the remaining aged prefix keeps draining at ≤2 per release. */
248
+ const GIT_SPAWN_AGE_BATCH = 2;
240
249
  /** Queued waiters — run-13 (f4) gave the low lane an aging clock: a bare
241
250
  * `() => void` could not say HOW LONG it had waited. The high lane shares
242
251
  * the shape so both queues stay one type; its timestamp is unused. */
@@ -281,16 +290,25 @@ function acquireGitSpawn(priority?: "high" | "low"): Promise<void> {
281
290
  );
282
291
  }
283
292
 
284
- /** run-13 (run-11 cold-review f4): move every low waiter older than
293
+ /** run-13 (run-11 cold-review f4): move low waiters older than
285
294
  * GIT_SPAWN_AGE_MS into the high lane. enqueuedAt is monotone along the
286
295
  * low queue (FIFO tail push), so the aged waiters are always a PREFIX —
287
296
  * spliced off whole, arrival order intact, and inserted behind the
288
297
  * already-promoted head so promotions stay globally FIFO among themselves
289
- * while still waking ahead of fresh high traffic. */
298
+ * while still waking ahead of fresh high traffic.
299
+ * Run-15 (u2-1): the prefix scan stops at GIT_SPAWN_AGE_BATCH waiters per
300
+ * call — a bounded inversion (≤2 promoted slots splice ahead of fresh high
301
+ * traffic per release) that still guarantees progress, because the scan
302
+ * re-runs on every acquire(low) and every release until the prefix drains. */
290
303
  function promoteAgedLowWaiters(): void {
291
304
  const now = gitSpawnNow();
292
305
  let aged = 0;
293
- while (aged < gitSpawnQueueLow.length && now - gitSpawnQueueLow[aged]!.enqueuedAt > GIT_SPAWN_AGE_MS) aged++;
306
+ while (
307
+ aged < GIT_SPAWN_AGE_BATCH &&
308
+ aged < gitSpawnQueueLow.length &&
309
+ now - gitSpawnQueueLow[aged]!.enqueuedAt > GIT_SPAWN_AGE_MS
310
+ )
311
+ aged++;
294
312
  if (!aged) return;
295
313
  const moving = gitSpawnQueueLow.splice(0, aged);
296
314
  gitSpawnQueueHigh.splice(gitSpawnPromotedHead, 0, ...moving);
@@ -3239,10 +3239,11 @@ export class Store {
3239
3239
  }
3240
3240
 
3241
3241
  private scheduleView(record: ScheduleRecord): ScheduleView {
3242
- // The SDK's ScheduleView union (dpi-sdk/src/api.ts) still lists only
3243
- // "ok" | "failed"; the intermediate outcomes are ordinary wire strings and
3244
- // dpi-sdk is not this fix's file, so carry the recorded value through with
3245
- // a narrowing cast. UIs treat the field as opaque text.
3242
+ // Run-15 (u4-2): the SDK's ScheduleView union now carries the registry's
3243
+ // full outcome set ("started"/"interrupted"/"timeout" included — the
3244
+ // intermediate states dispatchSchedule stamps), so the recorded value
3245
+ // passes through typed; the old narrowing cast is gone. UIs treat the
3246
+ // field as opaque text.
3246
3247
  const { lastOutcome, ...rest } = record;
3247
3248
  // R10 Design A: derived count of ring ids no longer live (archived or gone)
3248
3249
  // so the UI can render "keeping last N" truthfully. Bounded: ring ≤ 100.
@@ -3254,7 +3255,7 @@ export class Store {
3254
3255
  }
3255
3256
  return {
3256
3257
  ...rest,
3257
- ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
3258
+ ...(lastOutcome === undefined ? {} : { lastOutcome }),
3258
3259
  ...(archivedRuns !== undefined ? { archivedRuns } : {}),
3259
3260
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
3260
3261
  running: this.scheduleInFlight.has(record.id),
@@ -131,12 +131,17 @@ async function readBodyCapped(
131
131
  const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
132
132
  /** base64 inflates by 4/3 and the serialized envelope must still fit the chunk budget
133
133
  * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom.
134
- * R11 3.2 (doc): this 12 MB is the ceiling for EVERY tunnelled binary — an export
134
+ * R11 3.2 (doc): this 12 MiB is the ceiling for EVERY tunnelled binary — an export
135
135
  * larger than this refuses with response_too_large (deflate ≈ 3-5× on transcripts,
136
136
  * so most sessions fit; the LOCAL device ceiling is the 256 MiB streaming one in
137
137
  * zip.ts). The asymmetry is physics: textual frames get 16 MiB logical because
138
- * they never carry the 4/3 inflation; binaries pay it, so they get 12 MB pre-base64. */
139
- const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
138
+ * they never carry the 4/3 inflation; binaries pay it, so they get 12 MiB pre-base64.
139
+ * Run-15 (u4-1): unified to the exact 12 MiB (12_582_912 = 12*1024*1024) that the
140
+ * SDK client (BINARY_BODY_MAX) and the hub's LanTransport
141
+ * (BINARY_RESPONSE_MAX_BYTES) enforce — the old 12_000_000 was 582_912 bytes
142
+ * apart, so a binary could pass one leg and be refused by another.
143
+ * binary-caps-parity-r15.test.ts pins all three legs equal. */
144
+ const BINARY_RESPONSE_MAX_BYTES = 12_582_912;
140
145
  const safeHeaderValue = (value: string | null | undefined): string | undefined => {
141
146
  if (!value) return undefined;
142
147
  const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
@@ -746,7 +751,7 @@ export class DeviceConnector {
746
751
  ? `Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`
747
752
  : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget` +
748
753
  // R11 1.3: the two export ceilings must tell ONE story — the
749
- // tunnel cap is 12 MB compressed, the local one 256 MiB raw;
754
+ // tunnel cap is 12 MiB compressed, the local one 256 MiB raw;
750
755
  // name the remedies instead of a bare byte count.
751
756
  (frame.path.endsWith("/export")
752
757
  ? " — compact the session (archive old agents), or export it directly from the device"