@foldrun/core 17.4.0 → 18.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.
@@ -24,6 +24,7 @@
24
24
  // resumed (and swept by abortStaleUploads / a bucket lifecycle rule if no
25
25
  // one comes back).
26
26
 
27
+ import crypto from "node:crypto";
27
28
  import { s3Request, forgetS3Credentials, type S3Config, type S3StreamBody } from "./storage.ts";
28
29
  import {
29
30
  BlobNotFound,
@@ -47,6 +48,7 @@ const MiB = 1024 * 1024;
47
48
  export const MIN_PART_BYTES = 5 * MiB;
48
49
  /** S3's ceiling on the number of parts. */
49
50
  export const MAX_PARTS = 10_000;
51
+ const MAX_TIMER_MS = 2 ** 31 - 1;
50
52
 
51
53
  export interface S3BlobOptions {
52
54
  /** Objects at or above this many bytes go up as multipart. */
@@ -123,10 +125,22 @@ const isTimeout = (signal?: AbortSignal) => signal?.aborted === true && (signal.
123
125
  export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}): BlobStore & BlobSweeper & { checkBucket(signal?: AbortSignal): Promise<void> } {
124
126
  if (!cfg) throw new Error("the s3 blob store needs FOLDRUN_S3_ENDPOINT, FOLDRUN_S3_BUCKET and credentials");
125
127
  const o: S3BlobOptions = { ...s3OptionsFromEnv(), ...given };
126
- const requestDeadline = (bytes: number) => o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000);
128
+ // Clamped to the longest timer Node keeps: past 2^31-1 ms it fires after
129
+ // 1 ms instead, which would cut off the complete of a multi-TiB object.
130
+ const requestDeadline = (bytes: number) => Math.min(MAX_TIMER_MS, o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000));
127
131
 
128
132
  /** One signed request with the failures of the network turned into
129
- * BlobTransientError, so the retry wrapper above knows what to retry. */
133
+ * BlobTransientError, so the retry wrapper above knows what to retry.
134
+ *
135
+ * Every request carries this driver's own deadline (its floor plus its body
136
+ * at minBytesPerSec) on top of the caller's signal. bounded() leaves a
137
+ * streamed put to the driver, so without it a server that accepts the
138
+ * connection and never answers would hold the single PUT, or a multipart
139
+ * HEAD, list, create or complete, for as long as the caller's signal lets
140
+ * it — forever when there is none. `sizedBy` overrides the bytes the
141
+ * deadline is sized by (a complete, whose small body stands for a whole
142
+ * object the store has to assemble). A GET passes `false`: its signal also
143
+ * bounds reading the body, which is the caller's to bound. */
130
144
  const send = async (
131
145
  what: string,
132
146
  method: Parameters<typeof s3Request>[1],
@@ -136,15 +150,19 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
136
150
  signal?: AbortSignal,
137
151
  query?: Record<string, string>,
138
152
  mime?: string,
153
+ sizedBy?: number | false,
139
154
  ): Promise<Response> => {
155
+ const ms = requestDeadline(sizedBy === undefined || sizedBy === false ? (body?.length ?? 0) : sizedBy);
156
+ const bound = sizedBy === false ? signal : signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
140
157
  try {
141
- return await s3Request(cfg, method, key, body, mime, extra, signal, query ? { query } : {});
158
+ return await s3Request(cfg, method, key, body, mime, extra, bound, query ? { query } : {});
142
159
  } catch (err) {
143
160
  // A source that fails while it is being sent surfaces from fetch as
144
161
  // "fetch failed" with the real error as its cause. It is not the
145
162
  // network's fault and a retry would read the same bytes.
146
163
  for (let e: unknown = err, i = 0; e && i < 4; e = (e as Error).cause, i++) if (e instanceof BlobSourceError) throw e;
147
164
  if (signal?.aborted && !isTimeout(signal)) throw err; // the caller cancelled
165
+ if (bound?.aborted && isTimeout(bound)) throw new BlobTransientError(`s3 ${what}: no answer within ${ms}ms`);
148
166
  const name = (err as Error)?.name;
149
167
  if (name === "AbortError" || name === "TimeoutError") throw new BlobTransientError(`s3 ${what}: timed out`);
150
168
  const cause = (err as { cause?: { code?: string; message?: string } }).cause;
@@ -162,6 +180,18 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
162
180
  return new BlobStoreError(msg, res.status, code);
163
181
  };
164
182
  const drain = (res: Response) => res.arrayBuffer().catch(() => {});
183
+ /** A reply's body. The request's deadline still runs while it is read, and
184
+ * a deadline or a dropped connection here is as transient as one before
185
+ * the headers came. */
186
+ const textOf = async (res: Response, what: string): Promise<string> => {
187
+ try {
188
+ return await res.text();
189
+ } catch (err) {
190
+ if ((err as Error)?.name === "TimeoutError") throw new BlobTransientError(`s3 ${what}: timed out reading the reply`);
191
+ if (err instanceof TypeError) throw new BlobTransientError(`s3 ${what}: the reply was cut off (${(err as { cause?: { code?: string } }).cause?.code ?? err.message})`);
192
+ throw err;
193
+ }
194
+ };
165
195
 
166
196
  const headObject = async (key: string, signal?: AbortSignal): Promise<HeadResult | null> => {
167
197
  const res = await send("head", "HEAD", key, undefined, {}, signal);
@@ -207,7 +237,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
207
237
  if (uploadMarker) q["upload-id-marker"] = uploadMarker;
208
238
  const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
209
239
  if (!res.ok) throw await failure(res, "list uploads");
210
- const xml = await res.text();
240
+ const xml = await textOf(res, "list uploads");
211
241
  // The oldest open upload for the key: the one most likely to have parts.
212
242
  const mine = [...xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)]
213
243
  .map((m) => ({ key: unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? ""), id: unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? ""), at: Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "") || 0 }))
@@ -234,7 +264,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
234
264
  return null; // NoSuchUpload: it was completed or aborted under us
235
265
  }
236
266
  if (!res.ok) throw await failure(res, "list parts");
237
- const xml = await res.text();
267
+ const xml = await textOf(res, "list parts");
238
268
  for (const m of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
239
269
  const n = Number(/<PartNumber>(\d+)<\/PartNumber>/.exec(m[1])?.[1]);
240
270
  const size = Number(/<Size>(\d+)<\/Size>/.exec(m[1])?.[1]);
@@ -268,7 +298,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
268
298
  if (!uploadId || !have) {
269
299
  const res = await send("create upload", "POST", key, undefined, {}, signal, { uploads: "" }, opts.contentType);
270
300
  if (!res.ok) throw await failure(res, "create upload");
271
- uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await res.text())?.[1] ?? "");
301
+ uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await textOf(res, "create upload"))?.[1] ?? "");
272
302
  if (!uploadId) throw new BlobTransientError("s3 create upload: no upload id in the reply");
273
303
  have = new Map();
274
304
  }
@@ -281,6 +311,35 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
281
311
  // AbortError, which would hide a transient or final cause.
282
312
  let firstError: { err: unknown } | null = null;
283
313
  const both = signal ? AbortSignal.any([signal, inner.signal]) : inner.signal;
314
+
315
+ // Each part is checked against the bytes read for it (the sha256 signed
316
+ // into its PUT, or the md5 a part already in the store must match), but
317
+ // that alone says nothing about the object: a file that changed after the
318
+ // caller hashed it would go up whole and consistent under the OLD content
319
+ // address. So the same reads also feed one sha256 of the whole object,
320
+ // compared with opts.sha256 before the upload is completed. A sha256
321
+ // cannot be put together from the parts' own, so the reads have to reach
322
+ // it in order: each part's hash pass waits for the one before it.
323
+ // Workers take part numbers in order, so chaining their passes keeps it,
324
+ // and the uploads still overlap. A part reused from an earlier attempt is
325
+ // read and hashed like the others, so a resumed upload is covered too.
326
+ const whole = opts.sha256 ? crypto.createHash("sha256") : null;
327
+ let hashed: Promise<unknown> = Promise.resolve();
328
+ const hashPart = (start: number, end: number): Promise<{ sha256: string; md5: string }> => {
329
+ const pass = hashed.then(async () => {
330
+ const sha = crypto.createHash("sha256");
331
+ const md5 = crypto.createHash("md5");
332
+ for await (const chunk of source.read(start, end, both)) {
333
+ sha.update(chunk);
334
+ md5.update(chunk);
335
+ whole?.update(chunk);
336
+ }
337
+ return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
338
+ });
339
+ hashed = pass; // a failed pass fails the ones after it: the upload is over anyway
340
+ return pass;
341
+ };
342
+
284
343
  let next = 1;
285
344
  const worker = async () => {
286
345
  while (!both.aborted) {
@@ -289,8 +348,10 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
289
348
  const [start, end] = range(n);
290
349
  const len = end - start;
291
350
  // Hash first: the sha256 is signed into the request, the md5 is what a
292
- // part already in the store must match to be trusted.
293
- const h = await hashRange(source, start, end, both);
351
+ // part already in the store must match to be trusted. (No await
352
+ // between taking `n` and queueing its pass: that is what keeps the
353
+ // whole-object hash in order.)
354
+ const h = await hashPart(start, end);
294
355
  const prior = have!.get(n);
295
356
  if (prior && prior.size === len && unquote(prior.etag) === h.md5) {
296
357
  done.set(n, prior.etag);
@@ -302,7 +363,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
302
363
  key,
303
364
  { stream: source.read(start, end, both), length: len, sha256: h.sha256 },
304
365
  {},
305
- AbortSignal.any([both, AbortSignal.timeout(requestDeadline(len))]),
366
+ both, // send() adds the part's deadline, sized by its length
306
367
  { partNumber: String(n), uploadId: id },
307
368
  );
308
369
  if (!res.ok) throw await failure(res, `part ${n}`);
@@ -324,6 +385,14 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
324
385
  await Promise.allSettled(pool);
325
386
  if (firstError) throw (firstError as { err: unknown }).err;
326
387
 
388
+ // Every part went through hashPart, in order: `whole` is the object the
389
+ // store would assemble. Not the bytes asked for means not this key —
390
+ // a final failure, so the catch below aborts the upload.
391
+ if (whole) {
392
+ const got = whole.digest("hex");
393
+ if (got !== opts.sha256) throw new BlobSourceError(`the bytes for ${key} do not hash to ${opts.sha256} (they hash to ${got}): the source changed after it was hashed`);
394
+ }
395
+
327
396
  const xml =
328
397
  `<CompleteMultipartUpload>` +
329
398
  [...done.entries()]
@@ -331,7 +400,9 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
331
400
  .map(([n, etag]) => `<Part><PartNumber>${n}</PartNumber><ETag>${etag.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</ETag></Part>`)
332
401
  .join("") +
333
402
  `</CompleteMultipartUpload>`;
334
- const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml");
403
+ // Assembling the parts takes the store longer the bigger the object
404
+ // (AWS warns of minutes), so its deadline is sized by the object.
405
+ const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml", source.size);
335
406
  if (res.status === 412) {
336
407
  // Someone else's identical object won. Ours is not needed.
337
408
  await drain(res);
@@ -348,7 +419,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
348
419
  }
349
420
  if (!res.ok) throw await failure(res, "complete upload");
350
421
  // S3 can answer 200 and put the error in the body.
351
- const text = await res.text();
422
+ const text = await textOf(res, "complete upload");
352
423
  if (/<Error>/.test(text)) {
353
424
  const code = codeOf(text);
354
425
  const msg = `s3 complete upload failed: 200 ${code ?? "error in body"}`;
@@ -382,7 +453,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
382
453
  },
383
454
  async get(key, opts = {}) {
384
455
  assertKey(key);
385
- const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal);
456
+ const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal, undefined, undefined, false);
386
457
  if (res.status === 404) {
387
458
  const text = await res.text().catch(() => "");
388
459
  // A GET carries the reason a HEAD cannot: the bucket may be the thing that is missing.
@@ -425,7 +496,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
425
496
  if (uploadMarker) q["upload-id-marker"] = uploadMarker;
426
497
  const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
427
498
  if (!res.ok) throw await failure(res, "list uploads");
428
- const xml = await res.text();
499
+ const xml = await textOf(res, "list uploads");
429
500
  for (const m of xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)) {
430
501
  const key = unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? "");
431
502
  const id = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? "");
@@ -447,7 +518,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
447
518
  const q: Record<string, string> = { "list-type": "2", prefix: prefix.endsWith("/") ? prefix : `${prefix}/`, ...(token ? { "continuation-token": token } : {}) };
448
519
  const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
449
520
  if (!res.ok) throw await failure(res, "list");
450
- const xml = await res.text();
521
+ const xml = await textOf(res, "list");
451
522
  for (const c of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
452
523
  const key = xmlText(c[1], "Key");
453
524
  const size = Number(xmlText(c[1], "Size"));
@@ -464,7 +535,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
464
535
  const q: Record<string, string> = { "list-type": "2", prefix: "t/", delimiter: "/", ...(token ? { "continuation-token": token } : {}) };
465
536
  const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
466
537
  if (!res.ok) throw await failure(res, "list");
467
- const xml = await res.text();
538
+ const xml = await textOf(res, "list");
468
539
  for (const c of xml.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>/g)) out.push(unxml(c[1]).replace(/^t\//, "").replace(/\/$/, ""));
469
540
  token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
470
541
  } while (token);
@@ -54,7 +54,7 @@ import {
54
54
  type Changes,
55
55
  type Manifest,
56
56
  } from "./manifest.ts";
57
- import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
57
+ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
58
58
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
59
59
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
60
60
  import type { SweepMarks } from "./blob-sweeper.ts";
@@ -181,6 +181,8 @@ const queues = new Map<string, Entry[]>();
181
181
  const chains = new Map<string, Promise<unknown>>();
182
182
  const marked = new Set<string>(); // overflowed or dropped: needs reconcileWorkspace
183
183
  const verified = new Set<string>(); // reconciled once in this process
184
+ const unjournalled = new Set<string>(); // changed here while the journal was off: the head has not seen it
185
+ const repairing = new Set<string>(); // a reconcile is publishing: the head is about to change
184
186
  const retryAt = new Map<string, number>();
185
187
  const wantPrune = new Set<string>(); // a state checkpoint was committed since the last look
186
188
  const prunedAt = new Map<string, number>();
@@ -220,6 +222,7 @@ function journalChange(tenant: string, scope: string, files: RevisionFile[], met
220
222
  const k = key(tenant, scope);
221
223
  if (!safe(gate.journal)) {
222
224
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
225
+ unjournalled.add(k);
223
226
  return;
224
227
  }
225
228
  // Only what the head needs: the new content. The old text is the writer's
@@ -297,6 +300,7 @@ export function recordStepOutputs(
297
300
  const k = key(tenant, workspace);
298
301
  if (!safe(gate.journal)) {
299
302
  verified.delete(k); // the head will not see this: reconcile before trusting it again
303
+ unjournalled.add(k);
300
304
  return 0;
301
305
  }
302
306
  const files: EntryFile[] = [];
@@ -428,6 +432,7 @@ async function drainOne(k: string): Promise<void> {
428
432
  /** An error that retrying will not cure: the manifest refused the content. */
429
433
  function permanent(err: unknown): boolean {
430
434
  if (err instanceof PublishError) return err.code === "bad_change";
435
+ if (err instanceof OpIdReused) return true; // commitEntry asked again and it still is: see there
431
436
  const m = err instanceof Error ? err.message : "";
432
437
  return /^illegal manifest path|differ only by case|a manifest holds at most|is not workspace content/.test(m);
433
438
  }
@@ -448,6 +453,8 @@ export function resetJournalForTests(): void {
448
453
  chains.clear();
449
454
  marked.clear();
450
455
  verified.clear();
456
+ unjournalled.clear();
457
+ repairing.clear();
451
458
  retryAt.clear();
452
459
  restoring.clear();
453
460
  wantPrune.clear();
@@ -467,6 +474,7 @@ export function dropJournal(tenant: string, workspace?: string): void {
467
474
  queues.delete(k);
468
475
  marked.delete(k);
469
476
  verified.delete(k);
477
+ unjournalled.delete(k);
470
478
  retryAt.delete(k);
471
479
  }
472
480
  }
@@ -1062,29 +1070,63 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1062
1070
  if (!Object.keys(changes).length) return null;
1063
1071
  // A restore tag only counts when that revision is in the store.
1064
1072
  const restoredFrom = entry.restoredFrom && (await deps.revisions.revision(ws, entry.restoredFrom)) ? entry.restoredFrom : undefined;
1065
- try {
1066
- return await publish(deps, {
1067
- ws,
1068
- opId: opIdOf(baseline.authored || baseline.state ? "jb" : "jr", entry.id),
1069
- by: entry.by,
1070
- message: entry.message,
1071
- changes,
1072
- restoredFrom,
1073
- bytesOf: async (sha) => {
1074
- const b = bytes.get(sha);
1075
- if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1076
- return b;
1077
- },
1078
- });
1079
- } catch (err) {
1080
- // This entry's id was used before for a different set of changes: an
1081
- // earlier attempt committed it (its answer was lost) and the head has
1082
- // moved on, so the changes computed now differ. It is done.
1083
- if (err instanceof OpIdReused) return null;
1084
- throw err;
1073
+ const prefix = baseline.authored || baseline.state ? "jb" : "jr";
1074
+ // An entry is two commits (workspace head, then state head), each with its
1075
+ // own op id. A retry after only the first landed must still make the second:
1076
+ // so a side whose op id has finished is left out, rather than recomputed —
1077
+ // recomputed, its changes differ (what landed now matches the head and drops
1078
+ // out, a conflict does not), the op id would be "reused", and until 9 Nov
1079
+ // 2026 that was taken as the whole entry being done and the state half was
1080
+ // never committed (FOL-152). Asked again after an OpIdReused: another pod
1081
+ // replaying the same entry may finish a side between the look and the publish.
1082
+ for (let attempt = 0; ; attempt++) {
1083
+ const done = await sidesDone(deps, ws, entry.id);
1084
+ const todo: Changes = {};
1085
+ for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
1086
+ if (!Object.keys(todo).length) return null;
1087
+ try {
1088
+ return await publish(deps, {
1089
+ ws,
1090
+ // The op id of a side that finished, when one did, so the other side's
1091
+ // conflict copies are named the way the first attempt would have.
1092
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1093
+ by: entry.by,
1094
+ message: entry.message,
1095
+ changes: todo,
1096
+ restoredFrom: done.authored ? undefined : restoredFrom,
1097
+ bytesOf: async (sha) => {
1098
+ const b = bytes.get(sha);
1099
+ if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1100
+ return b;
1101
+ },
1102
+ });
1103
+ } catch (err) {
1104
+ // Never "done" by itself: a side that finished is found by sidesDone on
1105
+ // the next look. One that keeps answering OpIdReused without having
1106
+ // finished is a bug, and permanent(): the entry is dropped and the
1107
+ // workspace reconciled from the folder, so nothing is lost silently.
1108
+ if (!(err instanceof OpIdReused) || attempt >= 2) throw err;
1109
+ }
1085
1110
  }
1086
1111
  }
1087
1112
 
1113
+ /** Which halves of a journal entry finished in an earlier attempt (an
1114
+ * operation is recorded for each, committed or unchanged). Both prefixes are
1115
+ * asked: an entry that was a baseline when it first ran is not one on retry. */
1116
+ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ authored: boolean; state: boolean; opId?: string }> {
1117
+ const out: { authored: boolean; state: boolean; opId?: string } = { authored: false, state: false };
1118
+ const ids = ["jb", "jr"].map((prefix) => opIdOf(prefix, id));
1119
+ const found = await Promise.all(
1120
+ ids.map((opId) => Promise.all([deps.revisions.operation({ ...ws, scope: "workspace" }, opId), deps.revisions.operation({ ...ws, scope: "state" }, stateOpId(opId))])),
1121
+ );
1122
+ found.forEach(([a, s], i) => {
1123
+ if (a) out.authored = true;
1124
+ if (s) out.state = true;
1125
+ if ((a || s) && !out.opId) out.opId = ids[i];
1126
+ });
1127
+ return out;
1128
+ }
1129
+
1088
1130
  /** Bring the heads to the folder's content in one revision: the way in for a
1089
1131
  * workspace that predates the journal (the importer, phase 8), and the repair
1090
1132
  * after a journal overflow. Text files only, as the tree reader lists them. */
@@ -1097,6 +1139,8 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1097
1139
  // writing a file too big to journal while this publishes) asks for another
1098
1140
  // repair; a repair that fails puts it back for the next one.
1099
1141
  const wasMarked = marked.delete(k);
1142
+ const wasUnjournalled = unjournalled.delete(k);
1143
+ repairing.add(k);
1100
1144
  try {
1101
1145
  // The heads first, then the folder: a folder read older than the heads
1102
1146
  // would diff a stale copy against a newer head, and with that head as each
@@ -1138,7 +1182,10 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1138
1182
  });
1139
1183
  } catch (err) {
1140
1184
  if (wasMarked) marked.add(k);
1185
+ if (wasUnjournalled) unjournalled.add(k);
1141
1186
  throw err;
1187
+ } finally {
1188
+ repairing.delete(k);
1142
1189
  }
1143
1190
  }
1144
1191
 
@@ -1183,28 +1230,58 @@ async function parentManifest(deps: Deps, tenant: string, workspace: string, rev
1183
1230
  /** The history page's rows, newest first: the workspace head's revisions in
1184
1231
  * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
1185
1232
  * the message); the id is the revision's. */
1186
- export async function listRevisionSummaries(tenant: string, workspace: string, opts: { limit?: number; forPath?: string } = {}): Promise<RevisionSummary[]> {
1233
+ export async function listRevisionSummaries(tenant: string, workspace: string, opts: { limit?: number; forPath?: string; paths?: boolean } = {}): Promise<RevisionSummary[]> {
1187
1234
  const deps = backend;
1188
1235
  if (!deps) return [];
1189
- const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: opts.forPath ? 500 : (opts.limit ?? 200) });
1190
- const out: RevisionSummary[] = [];
1191
1236
  const want = opts.limit ?? 200;
1192
- // Eight at a time: each revision is two manifest reads, and a history page
1193
- // asks for hundreds.
1194
- for (let i = 0; i < revs.length && out.length < want; i += 8) {
1195
- const rows = await Promise.all(
1196
- revs.slice(i, i + 8).map(async (r) => {
1197
- const [mine, before] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1198
- return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(before, mine)).sort() } as RevisionSummary;
1199
- }),
1200
- );
1201
- for (const row of rows) {
1202
- if (opts.forPath && !row.paths.includes(opts.forPath)) continue;
1203
- if (out.length < want) out.push(row);
1237
+ // `paths: false` (resolving a restore point) needs only who, when and why:
1238
+ // no manifest is read, and every row says paths [].
1239
+ const withPaths = opts.paths !== false || !!opts.forPath;
1240
+ // Page by page: the store answers at most PAGE revisions a call, and until
1241
+ // 9 Nov 2026 that first page was taken as the whole history, so a revision
1242
+ // older than the 500th could not be listed or resolved (FOL-152). A search
1243
+ // for one path still looks at no more than FOR_PATH_SCAN of them: each is two
1244
+ // manifest reads.
1245
+ const scanUpTo = opts.forPath ? FOR_PATH_SCAN : Infinity;
1246
+ const out: RevisionSummary[] = [];
1247
+ let before: number | undefined;
1248
+ for (let scanned = 0; out.length < want && scanned < scanUpTo; ) {
1249
+ const ask = opts.forPath ? Math.min(PAGE, scanUpTo - scanned) : Math.min(PAGE, want - out.length);
1250
+ const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: ask, ...(before !== undefined ? { before } : {}) });
1251
+ if (!revs.length) break;
1252
+ scanned += revs.length;
1253
+ // Eight at a time: each revision is two manifest reads, and a history page
1254
+ // asks for hundreds.
1255
+ for (let i = 0; i < revs.length && out.length < want; i += 8) {
1256
+ const rows = await Promise.all(
1257
+ revs.slice(i, i + 8).map(async (r) => {
1258
+ if (!withPaths) return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } as RevisionSummary;
1259
+ const [mine, parent] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1260
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(parent, mine)).sort() } as RevisionSummary;
1261
+ }),
1262
+ );
1263
+ for (const row of rows) {
1264
+ if (opts.forPath && !row.paths.includes(opts.forPath)) continue;
1265
+ if (out.length < want) out.push(row);
1266
+ }
1204
1267
  }
1268
+ before = revs[revs.length - 1].seq;
1269
+ if (before <= 1) break; // that was the first revision: nothing older to ask for
1205
1270
  }
1206
1271
  return out;
1207
1272
  }
1273
+ /** The most revisions the store answers in one call (revision-store.ts). */
1274
+ const PAGE = 500;
1275
+ const FOR_PATH_SCAN = 500;
1276
+
1277
+ /** One revision of the workspace head, by id, without listing: the history's
1278
+ * "is this a restore point" and "which revision is that id". */
1279
+ export async function revisionSummary(tenant: string, workspace: string, id: string): Promise<RevisionSummary | null> {
1280
+ const deps = backend;
1281
+ if (!deps) return null;
1282
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1283
+ return r ? { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } : null;
1284
+ }
1208
1285
 
1209
1286
  /** One revision with what changed, in history.ts's Revision shape (text
1210
1287
  * before/after, clipped). */
@@ -1226,7 +1303,12 @@ export async function readRevisionDetail(tenant: string, workspace: string, id:
1226
1303
  return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
1227
1304
  }
1228
1305
 
1229
- /** The whole tree at a revision (the files a restore would bring back), text. */
1306
+ /** The whole tree at a revision (the files a restore would bring back), text.
1307
+ * All of it or an error: a file whose blob cannot be had throws BlobMissing.
1308
+ * Until 9 Nov 2026 such a file was left out, and a tree that lacks a file is
1309
+ * indistinguishable from one where it was deleted — a restore from it would
1310
+ * have removed the file from the folder (FOL-152). Through history.ts the
1311
+ * error answers "no snapshot", and the restore refuses. */
1230
1312
  export async function snapshotFiles(tenant: string, workspace: string, id: string): Promise<{ path: string; content: string }[] | null> {
1231
1313
  const deps = backend;
1232
1314
  if (!deps) return null;
@@ -1236,7 +1318,8 @@ export async function snapshotFiles(tenant: string, workspace: string, id: strin
1236
1318
  const out: { path: string; content: string }[] = [];
1237
1319
  for (const [p, e] of Object.entries(m.files).sort(([a], [b]) => a.localeCompare(b))) {
1238
1320
  const b = await blobBytes(deps, tenant, e.sha);
1239
- if (b) out.push({ path: p, content: b.toString("utf8") });
1321
+ if (!b) throw new BlobMissing(p, e.sha);
1322
+ out.push({ path: p, content: b.toString("utf8") });
1240
1323
  }
1241
1324
  return out;
1242
1325
  }
@@ -1269,6 +1352,7 @@ const view: RevisionView = {
1269
1352
  list: (t, w, o) => guarded("list", t, w, () => listRevisionSummaries(t, w, o)),
1270
1353
  read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1271
1354
  snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1355
+ get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1272
1356
  };
1273
1357
 
1274
1358
  // ------------------------------------------------------------- reads through heads
@@ -1278,7 +1362,7 @@ const view: RevisionView = {
1278
1362
  * fallback is the point: a head behind the folder, a missing blob, a store
1279
1363
  * that is down, a binary file the tree reader never recorded). */
1280
1364
  export async function readHeadText(tenant: string, workspace: string, rel: string): Promise<string | null> {
1281
- if (!revisionReadsOn()) return null;
1365
+ if (!revisionReadsOn() || headBehind(tenant, workspace, rel)) return null;
1282
1366
  try {
1283
1367
  const b = await readAtHead(tenant, workspace, rel);
1284
1368
  return b ? b.toString("utf8") : null;
@@ -1288,6 +1372,20 @@ export async function readHeadText(tenant: string, workspace: string, rel: strin
1288
1372
  }
1289
1373
  }
1290
1374
 
1375
+ /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1376
+ * A change to it is queued (its commit failed or has not run yet), the
1377
+ * workspace is marked for a repair or being repaired, or it was written while
1378
+ * the journal was off. The folder is the working copy and what a save's
1379
+ * `ifMatch` is checked against, so a read that answered the older head there
1380
+ * would tell the client a hash its next save can never match (FOL-152).
1381
+ * In-memory only, so it costs nothing per read; a change another process
1382
+ * has queued is not seen here. */
1383
+ function headBehind(tenant: string, workspace: string, rel: string): boolean {
1384
+ const k = key(tenant, workspace);
1385
+ if (marked.has(k) || unjournalled.has(k) || repairing.has(k)) return true;
1386
+ return !!queues.get(k)?.some((e) => e.files.some((f) => f.path === rel));
1387
+ }
1388
+
1291
1389
  /** Every file of the workspace head with its bytes and mode (both heads), for
1292
1390
  * a stage-in; null when reads through revisions are off, there is no head,
1293
1391
  * or any blob could not be had (the caller then stages from the folder). */
@@ -1314,7 +1412,8 @@ export async function readHeadTree(tenant: string, workspace: string): Promise<{
1314
1412
  }
1315
1413
 
1316
1414
  /** The dashboard's and the API's read of one editable file: the head's bytes
1317
- * when reads through revisions are on and the head has the file, otherwise
1415
+ * when reads through revisions are on, the head has the file and nothing in
1416
+ * this process says the head is behind the folder for it (headBehind), otherwise
1318
1417
  * the folder exactly as readWorkspaceFile answers (same path rules, same
1319
1418
  * "file not found"). */
1320
1419
  export async function readWorkspaceFileVia(tenant: string, workspace: string, rel: string): Promise<string> {