my-durable 0.0.66 → 0.0.67

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.
@@ -25,6 +25,11 @@ export interface GcIo {
25
25
  readFile: (path: string) => string;
26
26
  homedir: () => string;
27
27
  now: () => number;
28
+ /** R13 P3-1: the pending-sweep marker's writer — optional so test fakes can
29
+ * omit it (a missing writer just means the retry hint degrades to the
30
+ * message, never a crash). */
31
+ writeFile?: (path: string, data: string) => void;
32
+ remove?: (path: string) => void;
28
33
  }
29
34
 
30
35
  export const defaultGcIo = (): GcIo => ({
@@ -39,10 +44,13 @@ export const defaultGcIo = (): GcIo => ({
39
44
  const HELP = `dpi gc — retention for archived sessions
40
45
 
41
46
  dpi gc --closed-before 30d [--dry-run | --yes] [--home <dir>] [--data-dir <dir>]
47
+ dpi gc --sweep [--home <dir>] [--data-dir <dir>]
42
48
 
43
49
  --closed-before D age cutoff: 90m, 12h, 30d, 2w
44
50
  --dry-run show what would be deleted (the default)
45
51
  --yes actually delete it
52
+ --sweep retry a pending dangling-ref sweep (after a delete whose
53
+ sweep failed — deletes nothing by itself)
46
54
  --home <dir> device home (default: $DPI_HOME, else ~/.dpi)
47
55
  --data-dir <dir> device data dir (default: <home>/backend)
48
56
 
@@ -88,7 +96,7 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
88
96
  io.print(HELP);
89
97
  return 0;
90
98
  }
91
- const known = new Set(["--closed-before", "--dry-run", "--yes", "--home", "--data-dir"]);
99
+ const known = new Set(["--closed-before", "--dry-run", "--yes", "--sweep", "--home", "--data-dir"]);
92
100
  for (const arg of argv) {
93
101
  if (arg.startsWith("-") && !known.has(arg)) {
94
102
  io.printErr(`dpi gc: unknown flag '${arg}'\n\n${HELP}`);
@@ -96,6 +104,34 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
96
104
  }
97
105
  }
98
106
  const at = argv.indexOf("--closed-before");
107
+ // R13 P3-1: `--sweep` is a standalone retry of a pending ref sweep — it
108
+ // needs no cutoff (it deletes nothing; it only clears refs left behind by
109
+ // an earlier delete-ok/sweep-fail pass).
110
+ if (argv.includes("--sweep")) {
111
+ let dataDir0: string;
112
+ try {
113
+ dataDir0 = resolveDataDir(argv, io);
114
+ } catch (e) {
115
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
116
+ return 1;
117
+ }
118
+ const pending0 = readPendingIds(io, pendingSweepPath(dataDir0));
119
+ if (!pending0.length) {
120
+ io.print("no pending ref sweep.");
121
+ return 0;
122
+ }
123
+ try {
124
+ await sweepRefs(dataDir0, pending0, io, deviceToken(io));
125
+ io.remove?.(pendingSweepPath(dataDir0));
126
+ io.print(`swept ${pending0.length} pending ref id(s); marker cleared.`);
127
+ return 0;
128
+ } catch (e) {
129
+ io.printErr(
130
+ `dpi gc: pending sweep failed: ${e instanceof Error ? e.message : String(e)} (marker kept — retry with --sweep)`,
131
+ );
132
+ return 1;
133
+ }
134
+ }
99
135
  if (at < 0 || !argv[at + 1]) {
100
136
  io.printErr(`dpi gc: --closed-before DURATION is required (e.g. 30d)\n\n${HELP}`);
101
137
  return 2;
@@ -118,6 +154,9 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
118
154
  return 1;
119
155
  }
120
156
  const options = { closedBeforeDays: days, now: io.now() };
157
+ const dataDir = dataDirOf(archiveDir);
158
+ const pendingFile = pendingSweepPath(dataDir);
159
+ const pending = readPendingIds(io, pendingFile);
121
160
 
122
161
  // The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
123
162
  // cutoff or unreadable archive used to escape as a raw stack trace.
@@ -141,28 +180,39 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
141
180
  `sweep would clear ${plan.danglingRefs.schedules} schedule ref(s) and ${plan.danglingRefs.graphRuns} graph-run ref(s) pointing at the deletions.`,
142
181
  );
143
182
  }
183
+ if (pending.length > 0)
184
+ io.print(
185
+ `${pending.length} pending ref id(s) from an earlier failed sweep — re-run with --yes (or --sweep) to retry.`,
186
+ );
144
187
  return 0;
145
188
  }
146
189
 
147
190
  const { removed, bytes } = await gcApply(archiveDir, options);
148
191
  io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
149
192
 
150
- // R10 Design B: sweep refs pointing at what we just removed. Daemon-first
151
- // (registry mutations happen in-process, no file race); offline falls back
152
- // to the same advisory lock Store.open takes.
153
- const ids = removedSessionIds(removed);
193
+ // R10 Design B: sweep refs pointing at what we just removed — MERGED with
194
+ // any ids a previous failed sweep left behind (R13 P3-1: the retry used to
195
+ // be a dead end — a re-run with nothing to delete never swept again, so
196
+ // refs stayed dangling forever while the operator read success).
197
+ // Daemon-first (registry mutations happen in-process, no file race);
198
+ // offline falls back to the same advisory lock Store.open takes.
199
+ const ids = [...new Set([...pending, ...removedSessionIds(removed)])];
154
200
  if (ids.length > 0) {
155
201
  try {
156
- await sweepRefs(dataDirOf(archiveDir), ids, io, deviceToken(io));
202
+ await sweepRefs(dataDir, ids, io, deviceToken(io));
203
+ if (pending.length > 0) {
204
+ io.remove?.(pendingFile);
205
+ io.print(`(included ${pending.length} pending ref id(s) from an earlier failed sweep — marker cleared.)`);
206
+ }
157
207
  } catch (e) {
208
+ writePendingIds(io, pendingFile, ids);
158
209
  io.printErr(
159
210
  `dpi gc: deleted ${ids.length} session(s) but the ref sweep failed: ${
160
211
  e instanceof Error ? e.message : String(e)
161
- } (re-run later — the sweep is idempotent)`,
212
+ } (ids kept for retry: dpi gc --sweep — the sweep is idempotent)`,
162
213
  );
163
214
  // R12 P2-3: cron/scripts gate on the exit code — a failed sweep after
164
- // a real delete must not read as success (nothing retries it
165
- // otherwise; a later no-delete gc pass never sweeps).
215
+ // a real delete must not read as success.
166
216
  return 1;
167
217
  }
168
218
  }
@@ -175,6 +225,30 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
175
225
 
176
226
  const dataDirOf = (archiveDir: string) => archiveDir.slice(0, archiveDir.length - "/archive".length);
177
227
 
228
+ /** R13 P3-1: the pending-sweep marker — ids a delete-ok/sweep-fail pass left
229
+ * behind. Session UUIDs only (not secret); written best-effort, read
230
+ * tolerantly, cleared on the first successful sweep. */
231
+ const pendingSweepPath = (dataDir: string) => join(dataDir, "gc-pending-sweep.json");
232
+
233
+ const readPendingIds = (io: GcIo, path: string): string[] => {
234
+ try {
235
+ const doc = JSON.parse(io.readFile(path)) as { ids?: unknown };
236
+ return Array.isArray(doc.ids)
237
+ ? [...new Set(doc.ids.filter((id): id is string => typeof id === "string" && id.length > 0))]
238
+ : [];
239
+ } catch {
240
+ return []; // absent/corrupt — nothing pending
241
+ }
242
+ };
243
+
244
+ const writePendingIds = (io: GcIo, path: string, ids: string[]): void => {
245
+ try {
246
+ io.writeFile?.(path, `${JSON.stringify({ ids }, null, 2)}\n`);
247
+ } catch {
248
+ /* best-effort — the printed remedy still names --sweep */
249
+ }
250
+ };
251
+
178
252
  /** The device token, from the process env or the env file (DPI_ENV_FILE) —
179
253
  * only needed for the daemon-first sweep route. */
180
254
  function deviceToken(io: GcIo): string | undefined {
@@ -212,7 +286,10 @@ async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: strin
212
286
  // anything else is a real fault; falling through to the offline path
213
287
  // would race the daemon, so surface it instead.
214
288
  if (res.status === 404)
215
- throw new Error("device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc");
289
+ throw new Error(
290
+ "device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc " +
291
+ "(or DPI_PORT points at another local service — check it)",
292
+ );
216
293
  if (res.status === 401)
217
294
  throw new Error("device refused the sweep token — stale DPI_TOKEN in the env file; refresh it and re-run dpi gc");
218
295
  throw new Error(`device answered ${res.status} to the sweep route`);
@@ -120,14 +120,20 @@ export function danglingRefCounts(
120
120
  let graphRuns = 0;
121
121
  try {
122
122
  const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
123
- schedules?: Array<{ lastSessionId?: string; recentSessionIds?: string[] }>;
123
+ schedules?: Array<{ lastSessionId?: string; keepRuns?: unknown; recentSessionIds?: string[] }>;
124
124
  };
125
125
  // R12 P3-11: count what the sweep actually clears — the retention ring
126
126
  // too (clearSessionRefs deletes ring entries alongside lastSessionId), so
127
- // the dry-run's "would clear N" stops under-promising.
127
+ // the dry-run's "would clear N" stops under-promising. R13 P3-2: ring
128
+ // refs count ONLY when keepRuns parses in-range — the registry coercion
129
+ // DROPS junk keepRuns together with its ring (schedules.ts), so counting
130
+ // a doomed ring here would dry-run-promise what the sweep never clears.
131
+ const keepRunsParses = (v: unknown) =>
132
+ typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 100;
128
133
  for (const s of doc.schedules ?? []) {
129
134
  if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
130
- else if ((s.recentSessionIds ?? []).some((id) => ids.has(id))) schedules += 1;
135
+ else if (keepRunsParses(s.keepRuns) && (s.recentSessionIds ?? []).some((id) => ids.has(id)))
136
+ schedules += 1;
131
137
  }
132
138
  } catch {
133
139
  /* absent or unreadable — nothing countable */
@@ -2905,8 +2905,9 @@ export class Store {
2905
2905
  * archived via the existing store.archive path (abort-open → atomic rename
2906
2906
  * to archive/ → catalog row deleted — nothing deleted, restorable, ages into
2907
2907
  * the gc plan). Archive failure leaves the session live; the id is already
2908
- * gone from the ring, but the session stays restorable and the operator can
2909
- * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2908
+ * gone from the ring, so a PERSISTENT failure accumulates one straggler
2909
+ * per run until recovery — unbounded while the fault lasts, which is why
2910
+ * R12 P2-1 reports the degraded episode instead of swallowing it. */
2910
2911
  /** R12 P2-1: the once-per-episode signal for a retention prune that could
2911
2912
  * not archive an evicted run — shared by the prune's own failure path and
2912
2913
  * the void-caller's outer catch. */
@@ -2946,7 +2947,10 @@ export class Store {
2946
2947
  void this.notifyEvent({
2947
2948
  kind: "schedule.ok",
2948
2949
  title: `Retention resumed: ${record.name}`,
2949
- body: `archived ${archived} evicted run(s); the window is healthy again`,
2950
+ body:
2951
+ archived > 0
2952
+ ? `archived ${archived} evicted run(s); the window is healthy again`
2953
+ : `archiving works again (the evicted run(s) were already gone); the window is healthy`,
2950
2954
  data: { scheduleId: record.id },
2951
2955
  });
2952
2956
  }
@@ -757,6 +757,11 @@ export class DeviceConnector {
757
757
  // Small responses ride one frame; large ones chunk (hub reassembles).
758
758
  // Textual bodies keep the legacy UTF-8 string envelope; binaries are
759
759
  // base64-flagged so the hub can serve bytes byte-exact (R8 export).
760
+ // R13 (R9-6.3 FE): the device's idempotency replay verdict rides the
761
+ // envelope as an optional literal — old hubs ignore it (rest-response
762
+ // is de-Strict by design), new hubs surface the header so clients can
763
+ // tell a replay from a fresh create.
764
+ const replayed = res.headers.get("idempotent-replay") === "true" ? { idempotentReplay: true } : {};
760
765
  const envelope = textual
761
766
  ? ({
762
767
  type: "rest-response",
@@ -764,6 +769,7 @@ export class DeviceConnector {
764
769
  status: res.status,
765
770
  contentType: resCt,
766
771
  body: read.bytes.toString("utf8"),
772
+ ...replayed,
767
773
  } as const)
768
774
  : ({
769
775
  type: "rest-response",
@@ -773,6 +779,7 @@ export class DeviceConnector {
773
779
  body: read.bytes.toString("base64"),
774
780
  bodyEncoding: "base64",
775
781
  contentDisposition: safeHeaderValue(res.headers.get("content-disposition")),
782
+ ...replayed,
776
783
  } as const);
777
784
  const serialized = JSON.stringify(envelope);
778
785
  if (Buffer.byteLength(serialized, "utf8") <= INLINE_FRAME_MAX_BYTES) {