@foldrun/core 17.4.0 → 18.0.1

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.
@@ -219,11 +219,20 @@ export declare function readAtHead(tenant: string, workspace: string, rel: strin
219
219
  export declare function listRevisionSummaries(tenant: string, workspace: string, opts?: {
220
220
  limit?: number;
221
221
  forPath?: string;
222
+ paths?: boolean;
222
223
  }): Promise<RevisionSummary[]>;
224
+ /** One revision of the workspace head, by id, without listing: the history's
225
+ * "is this a restore point" and "which revision is that id". */
226
+ export declare function revisionSummary(tenant: string, workspace: string, id: string): Promise<RevisionSummary | null>;
223
227
  /** One revision with what changed, in history.ts's Revision shape (text
224
228
  * before/after, clipped). */
225
229
  export declare function readRevisionDetail(tenant: string, workspace: string, id: string, forPath?: string): Promise<HistoryRevision | null>;
226
- /** The whole tree at a revision (the files a restore would bring back), text. */
230
+ /** The whole tree at a revision (the files a restore would bring back), text.
231
+ * All of it or an error: a file whose blob cannot be had throws BlobMissing.
232
+ * Until 9 Nov 2026 such a file was left out, and a tree that lacks a file is
233
+ * indistinguishable from one where it was deleted — a restore from it would
234
+ * have removed the file from the folder (FOL-152). Through history.ts the
235
+ * error answers "no snapshot", and the restore refuses. */
227
236
  export declare function snapshotFiles(tenant: string, workspace: string, id: string): Promise<{
228
237
  path: string;
229
238
  content: string;
@@ -253,7 +262,8 @@ export declare function readHeadTree(tenant: string, workspace: string): Promise
253
262
  mode: number;
254
263
  }[] | null>;
255
264
  /** The dashboard's and the API's read of one editable file: the head's bytes
256
- * when reads through revisions are on and the head has the file, otherwise
265
+ * when reads through revisions are on, the head has the file and nothing in
266
+ * this process says the head is behind the folder for it (headBehind), otherwise
257
267
  * the folder exactly as readWorkspaceFile answers (same path rules, same
258
268
  * "file not found"). */
259
269
  export declare function readWorkspaceFileVia(tenant: string, workspace: string, rel: string): Promise<string>;
@@ -41,7 +41,7 @@ import { opsError, opsLog } from "./ops-log.js";
41
41
  import { readAll, BlobNotFound } from "./blob-store.js";
42
42
  import { fsJournalStore } from "./journal-store.js";
43
43
  import { blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
44
- import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, PublishError } from "./publish.js";
44
+ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
45
45
  import { OpIdReused } from "./revision-store.js";
46
46
  import { pruneStateRevisions } from "./state-retention.js";
47
47
  // ------------------------------------------------------------- the backend
@@ -98,6 +98,8 @@ const queues = new Map();
98
98
  const chains = new Map();
99
99
  const marked = new Set(); // overflowed or dropped: needs reconcileWorkspace
100
100
  const verified = new Set(); // reconciled once in this process
101
+ const unjournalled = new Set(); // changed here while the journal was off: the head has not seen it
102
+ const repairing = new Set(); // a reconcile is publishing: the head is about to change
101
103
  const retryAt = new Map();
102
104
  const wantPrune = new Set(); // a state checkpoint was committed since the last look
103
105
  const prunedAt = new Map();
@@ -137,6 +139,7 @@ function journalChange(tenant, scope, files, meta) {
137
139
  const k = key(tenant, scope);
138
140
  if (!safe(gate.journal)) {
139
141
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
142
+ unjournalled.add(k);
140
143
  return;
141
144
  }
142
145
  // Only what the head needs: the new content. The old text is the writer's
@@ -195,6 +198,7 @@ export function recordStepOutputs(tenant, workspace, writes, meta) {
195
198
  const k = key(tenant, workspace);
196
199
  if (!safe(gate.journal)) {
197
200
  verified.delete(k); // the head will not see this: reconcile before trusting it again
201
+ unjournalled.add(k);
198
202
  return 0;
199
203
  }
200
204
  const files = [];
@@ -333,6 +337,8 @@ async function drainOne(k) {
333
337
  function permanent(err) {
334
338
  if (err instanceof PublishError)
335
339
  return err.code === "bad_change";
340
+ if (err instanceof OpIdReused)
341
+ return true; // commitEntry asked again and it still is: see there
336
342
  const m = err instanceof Error ? err.message : "";
337
343
  return /^illegal manifest path|differ only by case|a manifest holds at most|is not workspace content/.test(m);
338
344
  }
@@ -351,6 +357,8 @@ export function resetJournalForTests() {
351
357
  chains.clear();
352
358
  marked.clear();
353
359
  verified.clear();
360
+ unjournalled.clear();
361
+ repairing.clear();
354
362
  retryAt.clear();
355
363
  restoring.clear();
356
364
  wantPrune.clear();
@@ -370,6 +378,7 @@ export function dropJournal(tenant, workspace) {
370
378
  queues.delete(k);
371
379
  marked.delete(k);
372
380
  verified.delete(k);
381
+ unjournalled.delete(k);
373
382
  retryAt.delete(k);
374
383
  }
375
384
  }
@@ -995,31 +1004,68 @@ async function commitEntry(deps, tenant, workspace, entry) {
995
1004
  return null;
996
1005
  // A restore tag only counts when that revision is in the store.
997
1006
  const restoredFrom = entry.restoredFrom && (await deps.revisions.revision(ws, entry.restoredFrom)) ? entry.restoredFrom : undefined;
998
- try {
999
- return await publish(deps, {
1000
- ws,
1001
- opId: opIdOf(baseline.authored || baseline.state ? "jb" : "jr", entry.id),
1002
- by: entry.by,
1003
- message: entry.message,
1004
- changes,
1005
- restoredFrom,
1006
- bytesOf: async (sha) => {
1007
- const b = bytes.get(sha);
1008
- if (!b)
1009
- throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1010
- return b;
1011
- },
1012
- });
1013
- }
1014
- catch (err) {
1015
- // This entry's id was used before for a different set of changes: an
1016
- // earlier attempt committed it (its answer was lost) and the head has
1017
- // moved on, so the changes computed now differ. It is done.
1018
- if (err instanceof OpIdReused)
1007
+ const prefix = baseline.authored || baseline.state ? "jb" : "jr";
1008
+ // An entry is two commits (workspace head, then state head), each with its
1009
+ // own op id. A retry after only the first landed must still make the second:
1010
+ // so a side whose op id has finished is left out, rather than recomputed —
1011
+ // recomputed, its changes differ (what landed now matches the head and drops
1012
+ // out, a conflict does not), the op id would be "reused", and until 9 Nov
1013
+ // 2026 that was taken as the whole entry being done and the state half was
1014
+ // never committed (FOL-152). Asked again after an OpIdReused: another pod
1015
+ // replaying the same entry may finish a side between the look and the publish.
1016
+ for (let attempt = 0;; attempt++) {
1017
+ const done = await sidesDone(deps, ws, entry.id);
1018
+ const todo = {};
1019
+ for (const [p, c] of Object.entries(changes))
1020
+ if (!done[sideOf(p)])
1021
+ todo[p] = c;
1022
+ if (!Object.keys(todo).length)
1019
1023
  return null;
1020
- throw err;
1024
+ try {
1025
+ return await publish(deps, {
1026
+ ws,
1027
+ // The op id of a side that finished, when one did, so the other side's
1028
+ // conflict copies are named the way the first attempt would have.
1029
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1030
+ by: entry.by,
1031
+ message: entry.message,
1032
+ changes: todo,
1033
+ restoredFrom: done.authored ? undefined : restoredFrom,
1034
+ bytesOf: async (sha) => {
1035
+ const b = bytes.get(sha);
1036
+ if (!b)
1037
+ throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1038
+ return b;
1039
+ },
1040
+ });
1041
+ }
1042
+ catch (err) {
1043
+ // Never "done" by itself: a side that finished is found by sidesDone on
1044
+ // the next look. One that keeps answering OpIdReused without having
1045
+ // finished is a bug, and permanent(): the entry is dropped and the
1046
+ // workspace reconciled from the folder, so nothing is lost silently.
1047
+ if (!(err instanceof OpIdReused) || attempt >= 2)
1048
+ throw err;
1049
+ }
1021
1050
  }
1022
1051
  }
1052
+ /** Which halves of a journal entry finished in an earlier attempt (an
1053
+ * operation is recorded for each, committed or unchanged). Both prefixes are
1054
+ * asked: an entry that was a baseline when it first ran is not one on retry. */
1055
+ async function sidesDone(deps, ws, id) {
1056
+ const out = { authored: false, state: false };
1057
+ const ids = ["jb", "jr"].map((prefix) => opIdOf(prefix, id));
1058
+ const found = await Promise.all(ids.map((opId) => Promise.all([deps.revisions.operation({ ...ws, scope: "workspace" }, opId), deps.revisions.operation({ ...ws, scope: "state" }, stateOpId(opId))])));
1059
+ found.forEach(([a, s], i) => {
1060
+ if (a)
1061
+ out.authored = true;
1062
+ if (s)
1063
+ out.state = true;
1064
+ if ((a || s) && !out.opId)
1065
+ out.opId = ids[i];
1066
+ });
1067
+ return out;
1068
+ }
1023
1069
  /** Bring the heads to the folder's content in one revision: the way in for a
1024
1070
  * workspace that predates the journal (the importer, phase 8), and the repair
1025
1071
  * after a journal overflow. Text files only, as the tree reader lists them. */
@@ -1033,6 +1079,8 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1033
1079
  // writing a file too big to journal while this publishes) asks for another
1034
1080
  // repair; a repair that fails puts it back for the next one.
1035
1081
  const wasMarked = marked.delete(k);
1082
+ const wasUnjournalled = unjournalled.delete(k);
1083
+ repairing.add(k);
1036
1084
  try {
1037
1085
  // The heads first, then the folder: a folder read older than the heads
1038
1086
  // would diff a stale copy against a newer head, and with that head as each
@@ -1080,8 +1128,13 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1080
1128
  catch (err) {
1081
1129
  if (wasMarked)
1082
1130
  marked.add(k);
1131
+ if (wasUnjournalled)
1132
+ unjournalled.add(k);
1083
1133
  throw err;
1084
1134
  }
1135
+ finally {
1136
+ repairing.delete(k);
1137
+ }
1085
1138
  }
1086
1139
  // ------------------------------------------------------------- reading
1087
1140
  async function blobBytes(deps, tenant, sha) {
@@ -1130,25 +1183,58 @@ export async function listRevisionSummaries(tenant, workspace, opts = {}) {
1130
1183
  const deps = backend;
1131
1184
  if (!deps)
1132
1185
  return [];
1133
- const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: opts.forPath ? 500 : (opts.limit ?? 200) });
1134
- const out = [];
1135
1186
  const want = opts.limit ?? 200;
1136
- // Eight at a time: each revision is two manifest reads, and a history page
1137
- // asks for hundreds.
1138
- for (let i = 0; i < revs.length && out.length < want; i += 8) {
1139
- const rows = await Promise.all(revs.slice(i, i + 8).map(async (r) => {
1140
- const [mine, before] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1141
- return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(before, mine)).sort() };
1142
- }));
1143
- for (const row of rows) {
1144
- if (opts.forPath && !row.paths.includes(opts.forPath))
1145
- continue;
1146
- if (out.length < want)
1147
- out.push(row);
1187
+ // `paths: false` (resolving a restore point) needs only who, when and why:
1188
+ // no manifest is read, and every row says paths [].
1189
+ const withPaths = opts.paths !== false || !!opts.forPath;
1190
+ // Page by page: the store answers at most PAGE revisions a call, and until
1191
+ // 9 Nov 2026 that first page was taken as the whole history, so a revision
1192
+ // older than the 500th could not be listed or resolved (FOL-152). A search
1193
+ // for one path still looks at no more than FOR_PATH_SCAN of them: each is two
1194
+ // manifest reads.
1195
+ const scanUpTo = opts.forPath ? FOR_PATH_SCAN : Infinity;
1196
+ const out = [];
1197
+ let before;
1198
+ for (let scanned = 0; out.length < want && scanned < scanUpTo;) {
1199
+ const ask = opts.forPath ? Math.min(PAGE, scanUpTo - scanned) : Math.min(PAGE, want - out.length);
1200
+ const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: ask, ...(before !== undefined ? { before } : {}) });
1201
+ if (!revs.length)
1202
+ break;
1203
+ scanned += revs.length;
1204
+ // Eight at a time: each revision is two manifest reads, and a history page
1205
+ // asks for hundreds.
1206
+ for (let i = 0; i < revs.length && out.length < want; i += 8) {
1207
+ const rows = await Promise.all(revs.slice(i, i + 8).map(async (r) => {
1208
+ if (!withPaths)
1209
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] };
1210
+ const [mine, parent] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1211
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(parent, mine)).sort() };
1212
+ }));
1213
+ for (const row of rows) {
1214
+ if (opts.forPath && !row.paths.includes(opts.forPath))
1215
+ continue;
1216
+ if (out.length < want)
1217
+ out.push(row);
1218
+ }
1148
1219
  }
1220
+ before = revs[revs.length - 1].seq;
1221
+ if (before <= 1)
1222
+ break; // that was the first revision: nothing older to ask for
1149
1223
  }
1150
1224
  return out;
1151
1225
  }
1226
+ /** The most revisions the store answers in one call (revision-store.ts). */
1227
+ const PAGE = 500;
1228
+ const FOR_PATH_SCAN = 500;
1229
+ /** One revision of the workspace head, by id, without listing: the history's
1230
+ * "is this a restore point" and "which revision is that id". */
1231
+ export async function revisionSummary(tenant, workspace, id) {
1232
+ const deps = backend;
1233
+ if (!deps)
1234
+ return null;
1235
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1236
+ return r ? { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } : null;
1237
+ }
1152
1238
  /** One revision with what changed, in history.ts's Revision shape (text
1153
1239
  * before/after, clipped). */
1154
1240
  export async function readRevisionDetail(tenant, workspace, id, forPath) {
@@ -1171,7 +1257,12 @@ export async function readRevisionDetail(tenant, workspace, id, forPath) {
1171
1257
  }
1172
1258
  return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
1173
1259
  }
1174
- /** The whole tree at a revision (the files a restore would bring back), text. */
1260
+ /** The whole tree at a revision (the files a restore would bring back), text.
1261
+ * All of it or an error: a file whose blob cannot be had throws BlobMissing.
1262
+ * Until 9 Nov 2026 such a file was left out, and a tree that lacks a file is
1263
+ * indistinguishable from one where it was deleted — a restore from it would
1264
+ * have removed the file from the folder (FOL-152). Through history.ts the
1265
+ * error answers "no snapshot", and the restore refuses. */
1175
1266
  export async function snapshotFiles(tenant, workspace, id) {
1176
1267
  const deps = backend;
1177
1268
  if (!deps)
@@ -1183,8 +1274,9 @@ export async function snapshotFiles(tenant, workspace, id) {
1183
1274
  const out = [];
1184
1275
  for (const [p, e] of Object.entries(m.files).sort(([a], [b]) => a.localeCompare(b))) {
1185
1276
  const b = await blobBytes(deps, tenant, e.sha);
1186
- if (b)
1187
- out.push({ path: p, content: b.toString("utf8") });
1277
+ if (!b)
1278
+ throw new BlobMissing(p, e.sha);
1279
+ out.push({ path: p, content: b.toString("utf8") });
1188
1280
  }
1189
1281
  return out;
1190
1282
  }
@@ -1217,6 +1309,7 @@ const view = {
1217
1309
  list: (t, w, o) => guarded("list", t, w, () => listRevisionSummaries(t, w, o)),
1218
1310
  read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1219
1311
  snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1312
+ get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1220
1313
  };
1221
1314
  // ------------------------------------------------------------- reads through heads
1222
1315
  /** One workspace file, from its head when reads through revisions are on and
@@ -1224,7 +1317,7 @@ const view = {
1224
1317
  * fallback is the point: a head behind the folder, a missing blob, a store
1225
1318
  * that is down, a binary file the tree reader never recorded). */
1226
1319
  export async function readHeadText(tenant, workspace, rel) {
1227
- if (!revisionReadsOn())
1320
+ if (!revisionReadsOn() || headBehind(tenant, workspace, rel))
1228
1321
  return null;
1229
1322
  try {
1230
1323
  const b = await readAtHead(tenant, workspace, rel);
@@ -1235,6 +1328,20 @@ export async function readHeadText(tenant, workspace, rel) {
1235
1328
  return null;
1236
1329
  }
1237
1330
  }
1331
+ /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1332
+ * A change to it is queued (its commit failed or has not run yet), the
1333
+ * workspace is marked for a repair or being repaired, or it was written while
1334
+ * the journal was off. The folder is the working copy and what a save's
1335
+ * `ifMatch` is checked against, so a read that answered the older head there
1336
+ * would tell the client a hash its next save can never match (FOL-152).
1337
+ * In-memory only, so it costs nothing per read; a change another process
1338
+ * has queued is not seen here. */
1339
+ function headBehind(tenant, workspace, rel) {
1340
+ const k = key(tenant, workspace);
1341
+ if (marked.has(k) || unjournalled.has(k) || repairing.has(k))
1342
+ return true;
1343
+ return !!queues.get(k)?.some((e) => e.files.some((f) => f.path === rel));
1344
+ }
1238
1345
  /** Every file of the workspace head with its bytes and mode (both heads), for
1239
1346
  * a stage-in; null when reads through revisions are off, there is no head,
1240
1347
  * or any blob could not be had (the caller then stages from the folder). */
@@ -1264,7 +1371,8 @@ export async function readHeadTree(tenant, workspace) {
1264
1371
  }
1265
1372
  }
1266
1373
  /** The dashboard's and the API's read of one editable file: the head's bytes
1267
- * when reads through revisions are on and the head has the file, otherwise
1374
+ * when reads through revisions are on, the head has the file and nothing in
1375
+ * this process says the head is behind the folder for it (headBehind), otherwise
1268
1376
  * the folder exactly as readWorkspaceFile answers (same path rules, same
1269
1377
  * "file not found"). */
1270
1378
  export async function readWorkspaceFileVia(tenant, workspace, rel) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "17.4.0",
3
+ "version": "18.0.1",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/blob-cache.ts CHANGED
@@ -240,13 +240,15 @@ export function blobCache(opts: BlobCacheOptions): BlobCache {
240
240
  function startFill(k: string, tenant: string, sha: string, f: Fill): Promise<void> {
241
241
  return gate(async () => {
242
242
  inFlight++;
243
- const part = path.join(tmpDir, `${tenant}-${sha}.${process.pid}.part`);
243
+ // downloadToFile writes `<dl>.part` and renames it to `dl` once the hash
244
+ // matched; `dl` is then renamed into the cache. Both names are removed
245
+ // below whatever happens: a fill that failed (a final error, retries
246
+ // spent) would otherwise leave its bytes in tmp/, outside the count
247
+ // that maxBytes holds, until the next start-up sweep.
248
+ const dl = path.join(tmpDir, `${tenant}-${sha}.${process.pid}.dl`);
244
249
  try {
245
250
  const final = fileOf(tenant, sha);
246
251
  fs.mkdirSync(path.dirname(final), { recursive: true });
247
- // downloadToFile resumes a cut body with a Range and checks the hash
248
- // before it renames `part` to its name; nothing is left on a mismatch.
249
- const dl = `${part}.dl`;
250
252
  const { size } = await downloadToFile(store, blobObjectKey(tenant, sha), dl, { sha256: sha });
251
253
  fs.renameSync(dl, final);
252
254
  const e: Entry = { size, pins: f.waiters, tick: ++tick };
@@ -260,7 +262,8 @@ export function blobCache(opts: BlobCacheOptions): BlobCache {
260
262
  evict(); // the new entry is pinned by its waiters; others may go
261
263
  } finally {
262
264
  inFlight--;
263
- fs.rmSync(part, { force: true });
265
+ fs.rmSync(`${dl}.part`, { force: true });
266
+ fs.rmSync(dl, { force: true });
264
267
  }
265
268
  });
266
269
  }
package/src/blob-store.ts CHANGED
@@ -210,6 +210,10 @@ export async function downloadToFile(
210
210
  if (!transient || attempt + 1 >= max || opts.signal?.aborted) throw err;
211
211
  continue;
212
212
  }
213
+ } else if (have === 0) {
214
+ // An empty object: nothing to fetch, but the file must still exist to
215
+ // be checked and renamed into place like any other.
216
+ fs.writeFileSync(part, "");
213
217
  }
214
218
  if (fs.statSync(part).size !== size) {
215
219
  if (attempt + 1 >= max) throw new BlobTransientError(`download of ${key} stopped short`);
@@ -26,8 +26,15 @@
26
26
  // Refusals (nothing deleted, said in the report): the store cannot list; the
27
27
  // database holds no revision at all while the bucket holds objects (a wiped or
28
28
  // not-yet-restored database); a retained manifest cannot be read (its blobs are
29
- // unknown). `dryRun` marks and counts nothing it would not report: it writes no
30
- // records and deletes nothing.
29
+ // unknown). A manifest committed DURING the sweep that cannot be read stops that
30
+ // account's sweep where it is: the objects deleted before it stay deleted (they
31
+ // were checked), nothing after it goes. `dryRun` marks and counts nothing it
32
+ // would not report: it writes no records and deletes nothing.
33
+ //
34
+ // `maxDeletes` is one budget for all accounts. It is charged from the report
35
+ // (what was deleted, or in a dry run what would be), so an account whose sweep
36
+ // fails part-way still pays for what it deleted, and a dry run stops counting
37
+ // where a real run would stop deleting.
31
38
  //
32
39
  // An account that was deleted needs no special case: its rows and pins are gone,
33
40
  // so everything under its prefix is unreferenced, waits the delay, and goes.
@@ -120,15 +127,17 @@ export async function sweepBlobs(deps: SweepDeps, marks: SweepMarks, opts: Sweep
120
127
  if (!opts.allowEmpty && tenants.length && !(await deps.revisions.anyRevisions())) {
121
128
  return refuse(rep, "the database holds no revision but the store holds objects: not deleting on that evidence");
122
129
  }
123
- let budget = Math.max(0, opts.maxDeletes);
124
130
  for (const tenant of tenants) {
125
131
  if (!TENANT.test(tenant)) {
126
132
  rep.foreign++;
127
133
  continue;
128
134
  }
129
135
  rep.tenants++;
136
+ // Read from the report, not from what sweepTenant returns: a tenant that
137
+ // throws after deleting never returns, and its deletions must still count.
138
+ const budget = Math.max(0, opts.maxDeletes - rep.deleted - rep.wouldDelete);
130
139
  try {
131
- budget -= await sweepTenant(deps, marks, opts, tenant, rep, budget);
140
+ await sweepTenant(deps, marks, opts, tenant, rep, budget);
132
141
  } catch (err) {
133
142
  rep.errors++;
134
143
  opsError("blobs.sweep_failed", err, { tenant });
@@ -145,7 +154,9 @@ function refuse(rep: SweepReport, why: string): SweepReport {
145
154
  return rep;
146
155
  }
147
156
 
148
- async function sweepTenant(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions, tenant: string, rep: SweepReport, budget: number): Promise<number> {
157
+ /** Adds what it did to `rep` as it goes, so a throw part-way leaves the report
158
+ * (and with it the shared budget) true to what was deleted. */
159
+ async function sweepTenant(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions, tenant: string, rep: SweepReport, budget: number): Promise<void> {
149
160
  const { blobs, revisions, pins } = deps;
150
161
  const started = await marks.now();
151
162
 
@@ -221,47 +232,64 @@ async function sweepTenant(deps: SweepDeps, marks: SweepMarks, opts: SweepOption
221
232
  }
222
233
 
223
234
  // ---- sweep
235
+ due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
224
236
  if (opts.dryRun) {
237
+ // The same objects, in the same order, a real run would take with this
238
+ // budget; adding to the report is what charges the shared budget.
225
239
  rep.wouldDelete += Math.min(due.length, budget);
226
240
  rep.wouldDeleteBytes += due.slice(0, budget).reduce((a, o) => a + o.size, 0);
227
- return 0;
241
+ return;
228
242
  }
229
243
  let did = 0;
230
244
  const since = new Date(started.getTime() - 60_000);
231
245
  const newlyLive = new Map<string, Set<string>>(); // manifest id → its blobs, for revisions made since the mark began
232
246
  const gone: Record<"blob" | "manifest", string[]> = { blob: [], manifest: [] };
233
- due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
234
- for (const o of due) {
235
- if (did >= budget) break;
236
- const ran = await (pins ?? NO_GUARD).guardDelete(tenant, o.kind === "blob" ? "blob" : "manifest", o.ref, async () => {
237
- // Inside the pin lock: whatever was committed since the mark began.
238
- const recent = await revisions.manifestIds(tenant, { since });
239
- if (o.kind === "manifest" && recent.includes(o.ref)) return void rep.skippedHeld++;
240
- if (o.kind === "blob") {
241
- for (const id of recent) {
242
- let set = newlyLive.get(id);
243
- if (!set) {
244
- set = new Set();
245
- try {
246
- for (const f of Object.values((await loadManifest({ blobs, revisions }, tenant, id)).files)) set.add(f.sha);
247
- } catch {
248
- set.add(o.ref); // unreadable: keep what we were about to delete
247
+ const clearGone = async () => {
248
+ for (const kind of ["blob", "manifest"] as const) if (gone[kind].length) await marks.clear(tenant, kind, gone[kind]);
249
+ };
250
+ try {
251
+ for (const o of due) {
252
+ if (did >= budget) break;
253
+ const ran = await (pins ?? NO_GUARD).guardDelete(tenant, o.kind === "blob" ? "blob" : "manifest", o.ref, async () => {
254
+ // Inside the pin lock: whatever was committed since the mark began.
255
+ const recent = await revisions.manifestIds(tenant, { since });
256
+ if (o.kind === "manifest" && recent.includes(o.ref)) return void rep.skippedHeld++;
257
+ if (o.kind === "blob") {
258
+ for (const id of recent) {
259
+ let set = newlyLive.get(id);
260
+ if (!set) {
261
+ // A new revision's manifest that cannot be read leaves its blobs
262
+ // unknown, for this candidate and every one after it. Caching
263
+ // anything here would let a later candidate it names be deleted,
264
+ // so the account's sweep stops instead (the caller counts it).
265
+ let m;
266
+ try {
267
+ m = await loadManifest({ blobs, revisions }, tenant, id);
268
+ } catch (err) {
269
+ throw new Error(`a revision committed during the sweep names manifest ${id.slice(0, 12)}…, which cannot be read: stopping this account's sweep`, { cause: err });
270
+ }
271
+ set = new Set(Object.values(m.files).map((f) => f.sha));
272
+ newlyLive.set(id, set);
249
273
  }
250
- newlyLive.set(id, set);
274
+ if (set.has(o.ref)) return void rep.skippedHeld++;
251
275
  }
252
- if (set.has(o.ref)) return void rep.skippedHeld++;
253
276
  }
254
- }
255
- await blobs.delete(o.key);
256
- rep.deleted++;
257
- rep.deletedBytes += o.size;
258
- did++;
259
- gone[o.kind].push(o.ref);
260
- });
261
- if (!ran) rep.skippedHeld++; // a live pin
277
+ await blobs.delete(o.key);
278
+ rep.deleted++;
279
+ rep.deletedBytes += o.size;
280
+ did++;
281
+ gone[o.kind].push(o.ref);
282
+ });
283
+ if (!ran) rep.skippedHeld++; // a live pin
284
+ }
285
+ } catch (err) {
286
+ // What was deleted before the failure is gone; its records go too, best
287
+ // effort (one left behind is stale next run, since its object is not
288
+ // listed, and is cleared then).
289
+ await clearGone().catch((e) => opsError("blobs.sweep_marks_not_cleared", e, { tenant }));
290
+ throw err;
262
291
  }
263
- for (const kind of ["blob", "manifest"] as const) if (gone[kind].length) await marks.clear(tenant, kind, gone[kind]);
264
- return did;
292
+ await clearGone();
265
293
  }
266
294
 
267
295
  const NO_GUARD = {