@fungi.computer/darkroom 0.10.0 → 0.11.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.
@@ -143,6 +143,61 @@ export type MediaErasureReadback = Readonly<{
143
143
  /** True only after all local data and retained output are absent. */
144
144
  clear: boolean;
145
145
  }>;
146
+ /** How `erase` treats an operation that is still generating or saving. */
147
+ export type MediaErasePolicy =
148
+ /** Abort it: its later writes refuse and anything that lands is deleted. */
149
+ "abort-active"
150
+ /** Refuse, atomically with the erasure, so a host that waits for inactivity never aborts work. */
151
+ | "refuse-active";
152
+ /** Result of erasing one operation: readback plus what the host may still own. */
153
+ export type MediaErasure = MediaErasureReadback & Readonly<{
154
+ /**
155
+ * The destination path this operation wrote or could have written, kept
156
+ * through erasure so the host can delete the file it owns. Null when the
157
+ * operation was never admitted.
158
+ */
159
+ destinationPath: string | null;
160
+ /**
161
+ * SHA-256 of the exact bytes this operation wrote, or was about to write,
162
+ * to `destinationPath`. Delete the file only while it still matches. Null
163
+ * when no write was ever begun.
164
+ */
165
+ writtenSha256: string | null;
166
+ /**
167
+ * True when the operation was erased before it finished, so a billing hold
168
+ * it took may be open. The host settles it at zero units; repeating that
169
+ * is idempotent.
170
+ */
171
+ abandonedGeneration: boolean;
172
+ }>;
173
+ /** Exact provider bytes an operation retained, before any provenance. */
174
+ export type MediaRetainedBytes = Readonly<{
175
+ /** The retained bytes. */
176
+ bytes: Uint8Array;
177
+ /** Actual output encoding. */
178
+ format: string;
179
+ }>;
180
+ /** What one operation still retains, readable by operation id. */
181
+ export type MediaRetained = Readonly<{
182
+ /** Retry identity of the generation. */
183
+ requestId: string;
184
+ /** Current lifecycle state. */
185
+ state: MediaOperationState;
186
+ /** The host destination path the generation writes, or may already have written. */
187
+ destinationPath: string;
188
+ /**
189
+ * The exact provider bytes retained in the artifacts bucket, or null before
190
+ * any were retained. Found by key even when a crash left them unrecorded.
191
+ */
192
+ output: Readonly<{
193
+ /** Retained byte length. */
194
+ bytes: number;
195
+ /** Actual output encoding. */
196
+ format: string;
197
+ /** Media type of the retained bytes. */
198
+ contentType: string;
199
+ }> | null;
200
+ }>;
146
201
  /** Retained output projection, or a terminal spent format refusal. */
147
202
  export type MediaRetentionResult = MediaOperationProjection | Readonly<{
148
203
  /** Provider execution finished with an unusable pinned format. */
@@ -173,6 +228,9 @@ export declare class MediaOperationOwner {
173
228
  private readonly provider?;
174
229
  private readonly hooks;
175
230
  private erased;
231
+ private retainsInFlight;
232
+ /** Output keys whose delete after a late write failed; erase retries them. */
233
+ private readonly lateDeletes;
176
234
  private readonly leaseMs;
177
235
  /**
178
236
  * A background (video) generation holds its lease past the 15-minute alarm
@@ -202,13 +260,36 @@ export declare class MediaOperationOwner {
202
260
  readShare(namespace: string): MediaShareSource | null;
203
261
  /** Check host namespace, request identity and inactivity before erasure. */
204
262
  preflightErasure(namespace: string, requestId: string): MediaErasurePreflight;
205
- /** Erase inactive output and local storage, then retain the durable erasure marker. */
206
- erase(namespace: string, requestId: string): Promise<Readonly<{
207
- /** True only after all local data and retained output are absent. */
208
- clear: boolean;
209
- }>>;
263
+ private assertErasureAddress;
264
+ private assertScope;
265
+ /** The stored record even after erasure began, while its tables still exist. */
266
+ private readRecordForErasure;
267
+ /**
268
+ * Erase the operation and everything it retained or could still write, even
269
+ * mid-generation. Erasure is marked first, so an attempt still running, or a
270
+ * lease recovered later, can neither transition nor leave output behind: a
271
+ * write that lands after the mark is deleted. The marker is never removed, so
272
+ * a crash cannot resurrect the operation. Safe to repeat until `clear`; a
273
+ * repeat after a partial failure resumes the cleanup.
274
+ */
275
+ erase(namespace: string, requestId: string, policy?: MediaErasePolicy): Promise<MediaErasure>;
210
276
  /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
211
277
  readErasure(): Promise<MediaErasureReadback>;
278
+ /**
279
+ * Run a write to the artifacts bucket. If erasure began while it was in
280
+ * flight, delete what landed and refuse; a failed delete is remembered so
281
+ * `erase` reports not-clear and a repeat retries it.
282
+ */
283
+ private retaining;
284
+ private retainedOutput;
285
+ /** List what this operation retains: its destination path and exact provider output. Null once erased. */
286
+ retained(namespace: string, requestId: string): Promise<MediaRetained | null>;
287
+ /**
288
+ * Read back the exact retained provider bytes, before any provenance, so a
289
+ * host can re-save a result whose destination write was lost. Null when
290
+ * erased or nothing was retained.
291
+ */
292
+ readRetained(namespace: string, requestId: string): Promise<MediaRetainedBytes | null>;
212
293
  private erasureOutputKey;
213
294
  private requireRecord;
214
295
  private update;
@@ -267,6 +348,13 @@ export declare class MediaOperationOwner {
267
348
  readGenerated(leaseId: string): Promise<Uint8Array>;
268
349
  /** A fixed-path exact-byte save is safe to retry without repeating generation. */
269
350
  releaseWrite(leaseId: string): MediaOperationProjection;
351
+ /**
352
+ * Record the digest of the exact bytes about to be written to the
353
+ * destination, before writing them. An erasure then knows which file this
354
+ * operation owns, even if the process dies between the write and its
355
+ * record, and refuses the write once erased.
356
+ */
357
+ recordWriteIntent(leaseId: string, sha256: string): MediaOperationProjection;
270
358
  /** Record a destination write and move to idempotent settlement. */
271
359
  recordWritten(leaseId: string, receipt: string, written: MediaImage): Readonly<{
272
360
  /** Durable object name identifying this operation. */
@@ -29,6 +29,33 @@ const audioReferenceMetadataSchema = z.lazy(() => z.object({
29
29
  durationSeconds: z.coerce.number().positive(),
30
30
  }));
31
31
  const audioReferenceKey = (operationId, index) => `media-audio-reference/v1/${operationId}/${String(index)}`;
32
+ const activeStates = [
33
+ "estimating",
34
+ "generating",
35
+ "writing",
36
+ "charging",
37
+ ];
38
+ /** States whose billing hold the executor has not yet settled itself. */
39
+ const holdOpenStates = [
40
+ "estimating",
41
+ "generating",
42
+ "writing",
43
+ ];
44
+ const writeReceiptSchema = z.string().regex(/^sha256:([0-9a-f]{64})$/);
45
+ function erasureMarker(record) {
46
+ const receipt = writeReceiptSchema.safeParse(record?.writeReceipt);
47
+ return {
48
+ destinationPath: record?.input.path ?? null,
49
+ writtenSha256: receipt.success
50
+ ? receipt.data.slice("sha256:".length)
51
+ : null,
52
+ abandonedGeneration: record !== null && holdOpenStates.includes(record.state),
53
+ };
54
+ }
55
+ const referenceKeys = (record) => [
56
+ ...(record.input.references ?? []).map((_reference, index) => referenceKey(record.operationId, index)),
57
+ ...(record.input.audioReferences ?? []).map((_reference, index) => audioReferenceKey(record.operationId, index)),
58
+ ];
32
59
  /** Fixed generation destination captured before provider dispatch. */
33
60
  export const mediaOperationDestinationSchema = z.lazy(() => z.strictObject({
34
61
  /** Host-admitted destination or reference identity. */
@@ -218,6 +245,9 @@ export class MediaOperationOwner {
218
245
  provider;
219
246
  hooks;
220
247
  erased = false;
248
+ retainsInFlight = 0;
249
+ /** Output keys whose delete after a late write failed; erase retries them. */
250
+ lateDeletes = new Set();
221
251
  leaseMs = 5 * 60 * 1_000;
222
252
  /**
223
253
  * A background (video) generation holds its lease past the 15-minute alarm
@@ -240,7 +270,8 @@ export class MediaOperationOwner {
240
270
  this.provider = provider;
241
271
  this.hooks = hooks;
242
272
  void ctx.blockConcurrencyWhile(async () => {
243
- if (await ctx.storage.isErased()) {
273
+ const durablyErased = await ctx.storage.isErased();
274
+ if (durablyErased || this.erased) {
244
275
  this.erased = true;
245
276
  return;
246
277
  }
@@ -401,34 +432,91 @@ export class MediaOperationOwner {
401
432
  }
402
433
  /** Check host namespace, request identity and inactivity before erasure. */
403
434
  preflightErasure(namespace, requestId) {
404
- if (this.ctx.id.name !== `media:${requestId}`)
405
- throw new Error("Media erasure address mismatch");
406
- if (this.erased)
435
+ if (this.erased) {
436
+ this.assertErasureAddress(requestId);
407
437
  return { namespace, requestId, erased: true };
438
+ }
408
439
  const record = this.readRecord();
409
- const ownerNamespace = record?.namespace ?? this.hooks.namespace?.() ?? null;
410
- if ((ownerNamespace !== null && ownerNamespace !== namespace) ||
411
- (record !== null && record.requestId !== requestId))
412
- throw new Error("Media erasure scope mismatch");
440
+ this.assertScope(namespace, requestId, record);
413
441
  if (record !== null &&
414
442
  ["estimating", "generating", "writing", "charging"].includes(record.state))
415
443
  throw new Error("Media operation is still active");
416
444
  return { namespace, requestId, erased: false };
417
445
  }
418
- /** Erase inactive output and local storage, then retain the durable erasure marker. */
419
- async erase(namespace, requestId) {
420
- if (this.erased)
421
- return this.readErasure();
422
- this.preflightErasure(namespace, requestId);
423
- // The operation's immutable output key is owned by this DO identity.
424
- await this.env.APP_ARTIFACTS.delete(this.erasureOutputKey());
425
- if (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey()))
426
- throw new Error("Media output erasure readback incomplete");
446
+ assertErasureAddress(requestId) {
447
+ if (this.ctx.id.name !== `media:${requestId}`)
448
+ throw new Error("Media erasure address mismatch");
449
+ }
450
+ assertScope(namespace, requestId, record) {
451
+ this.assertErasureAddress(requestId);
452
+ const ownerNamespace = record?.namespace ?? this.hooks.namespace?.() ?? null;
453
+ if ((ownerNamespace !== null && ownerNamespace !== namespace) ||
454
+ (record !== null && record.requestId !== requestId))
455
+ throw new Error("Media erasure scope mismatch");
456
+ }
457
+ /** The stored record even after erasure began, while its tables still exist. */
458
+ readRecordForErasure() {
459
+ const table = this.ctx.storage.sql
460
+ .exec("SELECT name FROM sqlite_master WHERE type='table' AND name='hub_media_operation'")
461
+ .toArray()[0];
462
+ if (table === undefined)
463
+ return null;
464
+ const row = this.ctx.storage.sql
465
+ .exec("SELECT * FROM hub_media_operation WHERE singleton=1")
466
+ .toArray()[0];
467
+ if (row === undefined)
468
+ return null;
469
+ const parsed = operationRowSchema.safeParse(row);
470
+ if (!parsed.success)
471
+ throw new MediaOperationError("partial_init", { cause: parsed.error });
472
+ return this.decode(parsed.data);
473
+ }
474
+ /**
475
+ * Erase the operation and everything it retained or could still write, even
476
+ * mid-generation. Erasure is marked first, so an attempt still running, or a
477
+ * lease recovered later, can neither transition nor leave output behind: a
478
+ * write that lands after the mark is deleted. The marker is never removed, so
479
+ * a crash cannot resurrect the operation. Safe to repeat until `clear`; a
480
+ * repeat after a partial failure resumes the cleanup.
481
+ */
482
+ async erase(namespace, requestId, policy = "abort-active") {
483
+ const record = this.readRecordForErasure();
484
+ this.assertScope(namespace, requestId, record);
485
+ if (!this.erased) {
486
+ if (policy === "refuse-active" &&
487
+ record !== null &&
488
+ activeStates.includes(record.state))
489
+ throw new Error("Media operation is still active");
490
+ // Synchronously, before any await: nothing in this object transitions again.
491
+ this.erased = true;
492
+ }
493
+ if (!(await this.ctx.storage.isErased()))
494
+ await this.ctx.storage.markErased(erasureMarker(record));
495
+ const marker = (await this.ctx.storage.readErasureMarker()) ?? {
496
+ destinationPath: null,
497
+ writtenSha256: null,
498
+ abandonedGeneration: false,
499
+ };
500
+ // The immutable output key is owned by this DO identity; background
501
+ // reference copies hold the person's private inputs.
502
+ const keys = [
503
+ this.erasureOutputKey(),
504
+ ...(record === null ? [] : referenceKeys(record)),
505
+ ...this.lateDeletes,
506
+ ];
507
+ await Promise.all(keys.map((key) => this.env.APP_ARTIFACTS.delete(key)));
508
+ this.lateDeletes.clear();
427
509
  await this.ctx.storage.deleteAlarm();
428
- await this.ctx.storage.deleteAll();
429
- await this.ctx.storage.markErased();
430
- this.erased = true;
431
- return this.readErasure();
510
+ // Never deleteAll: it would remove the marker and its facts.
511
+ const tables = z
512
+ .array(z.strictObject({ name: z.string() }))
513
+ .parse(this.ctx.storage.sql
514
+ .exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
515
+ .toArray());
516
+ for (const { name } of tables)
517
+ this.ctx.storage.sql.exec(`DROP TABLE "${name.replaceAll('"', '""')}"`);
518
+ await this.ctx.storage.deleteKeys((await this.ctx.storage.listKeys()).filter((key) => !key.startsWith("botanical:erased")));
519
+ return { ...(await this.readErasure()), ...marker };
432
520
  }
433
521
  /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
434
522
  async readErasure() {
@@ -437,14 +525,102 @@ export class MediaOperationOwner {
437
525
  .exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
438
526
  .toArray();
439
527
  return {
440
- clear: keys.length === 1 &&
441
- keys[0] === "botanical:erased" &&
528
+ clear: keys.includes("botanical:erased") &&
529
+ keys.every((key) => key.startsWith("botanical:erased")) &&
442
530
  (await this.ctx.storage.isErased()) &&
443
531
  tables.length === 0 &&
532
+ // A put still in flight, or a late delete that failed, is not clear yet.
533
+ this.retainsInFlight === 0 &&
534
+ this.lateDeletes.size === 0 &&
444
535
  (await this.ctx.storage.getAlarm()) === null &&
445
536
  (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey())) === null,
446
537
  };
447
538
  }
539
+ /**
540
+ * Run a write to the artifacts bucket. If erasure began while it was in
541
+ * flight, delete what landed and refuse; a failed delete is remembered so
542
+ * `erase` reports not-clear and a repeat retries it.
543
+ */
544
+ async retaining(keys, write) {
545
+ this.retainsInFlight += 1;
546
+ try {
547
+ const written = await write();
548
+ if (this.erased) {
549
+ for (const key of keys)
550
+ this.lateDeletes.add(key);
551
+ await Promise.all(keys.map((key) => this.env.APP_ARTIFACTS.delete(key)));
552
+ for (const key of keys)
553
+ this.lateDeletes.delete(key);
554
+ throw new MediaOperationError("not_found");
555
+ }
556
+ return written;
557
+ }
558
+ finally {
559
+ this.retainsInFlight -= 1;
560
+ }
561
+ }
562
+ async retainedOutput(record) {
563
+ if (record.output !== null)
564
+ return {
565
+ key: record.output.key,
566
+ bytes: record.output.bytes,
567
+ format: record.output.format,
568
+ version: record.output.version,
569
+ };
570
+ // A crash after the R2 write and before its record leaves exact bytes
571
+ // nothing points to; find them by the key this operation owns.
572
+ const head = await this.env.APP_ARTIFACTS.head(`media-output/v1/${record.operationId}`);
573
+ if (head === null)
574
+ return null;
575
+ return {
576
+ key: head.key,
577
+ bytes: head.size,
578
+ format: retainedFormatSchema.parse(head.httpMetadata?.contentType),
579
+ version: head.version,
580
+ };
581
+ }
582
+ /** List what this operation retains: its destination path and exact provider output. Null once erased. */
583
+ async retained(namespace, requestId) {
584
+ const record = this.readRecord();
585
+ this.assertScope(namespace, requestId, record);
586
+ if (record === null)
587
+ return null;
588
+ const output = await this.retainedOutput(record);
589
+ return Object.freeze({
590
+ requestId: record.requestId,
591
+ state: record.state,
592
+ destinationPath: record.input.path,
593
+ output: output === null
594
+ ? null
595
+ : Object.freeze({
596
+ bytes: output.bytes,
597
+ format: output.format,
598
+ contentType: outputMime(output.format),
599
+ }),
600
+ });
601
+ }
602
+ /**
603
+ * Read back the exact retained provider bytes, before any provenance, so a
604
+ * host can re-save a result whose destination write was lost. Null when
605
+ * erased or nothing was retained.
606
+ */
607
+ async readRetained(namespace, requestId) {
608
+ const record = this.readRecord();
609
+ this.assertScope(namespace, requestId, record);
610
+ if (record === null)
611
+ return null;
612
+ const output = await this.retainedOutput(record);
613
+ if (output === null)
614
+ return null;
615
+ const object = await this.env.APP_ARTIFACTS.get(output.key);
616
+ if (object?.version !== output.version || object.size !== output.bytes)
617
+ throw new MediaOperationError("partial_init");
618
+ const bytes = new Uint8Array(await object.arrayBuffer());
619
+ // Erasure may have begun while the object was read.
620
+ if (this.erased)
621
+ throw new MediaOperationError("not_found");
622
+ return { bytes, format: output.format };
623
+ }
448
624
  erasureOutputKey() {
449
625
  const name = this.ctx.id.name;
450
626
  if (name === undefined)
@@ -587,7 +763,8 @@ export class MediaOperationOwner {
587
763
  format: output.format,
588
764
  },
589
765
  output,
590
- writeReceipt: null,
766
+ // A write may have landed before the worker died; the retry writes the same bytes.
767
+ writeReceipt: record.writeReceipt,
591
768
  result: null,
592
769
  });
593
770
  return {
@@ -678,23 +855,25 @@ export class MediaOperationOwner {
678
855
  const record = this.requireRecord();
679
856
  if (record.state !== "generating" || record.leaseId !== leaseId)
680
857
  throw new MediaOperationError("lease_lost");
681
- for (const [index, reference] of references.entries()) {
682
- await this.env.APP_ARTIFACTS.put(referenceKey(record.operationId, index), reference.bytes, {
683
- customMetadata: {
684
- format: reference.format,
685
- width: String(reference.width),
686
- height: String(reference.height),
687
- },
688
- });
689
- }
690
- for (const [index, clip] of audioReferences.entries()) {
691
- await this.env.APP_ARTIFACTS.put(audioReferenceKey(record.operationId, index), clip.bytes, {
692
- customMetadata: {
693
- mimeType: clip.mimeType,
694
- durationSeconds: String(clip.durationSeconds),
695
- },
696
- });
697
- }
858
+ await this.retaining(referenceKeys(record), async () => {
859
+ for (const [index, reference] of references.entries()) {
860
+ await this.env.APP_ARTIFACTS.put(referenceKey(record.operationId, index), reference.bytes, {
861
+ customMetadata: {
862
+ format: reference.format,
863
+ width: String(reference.width),
864
+ height: String(reference.height),
865
+ },
866
+ });
867
+ }
868
+ for (const [index, clip] of audioReferences.entries()) {
869
+ await this.env.APP_ARTIFACTS.put(audioReferenceKey(record.operationId, index), clip.bytes, {
870
+ customMetadata: {
871
+ mimeType: clip.mimeType,
872
+ durationSeconds: String(clip.durationSeconds),
873
+ },
874
+ });
875
+ }
876
+ });
698
877
  const timestamp = Date.now();
699
878
  this.ctx.storage.sql.exec("UPDATE hub_media_operation SET background=1, lease_expires_at=?, updated_at=? WHERE singleton=1 AND state='generating' AND lease_id=?", timestamp + this.backgroundLeaseMs, timestamp, leaseId);
700
879
  await this.ctx.storage.setAlarm(timestamp);
@@ -772,6 +951,11 @@ export class MediaOperationOwner {
772
951
  timer = setTimeout(() => {
773
952
  const timeout = new MediaExecutionError("provider", {
774
953
  cause: new Error("Background media provider timed out"),
954
+ provider: {
955
+ category: "TimeoutError",
956
+ code: null,
957
+ reason: "timeout",
958
+ },
775
959
  });
776
960
  controller.abort(timeout);
777
961
  reject(timeout);
@@ -875,10 +1059,10 @@ export class MediaOperationOwner {
875
1059
  };
876
1060
  }
877
1061
  const key = `media-output/v1/${record.operationId}`;
878
- const stored = await this.env.APP_ARTIFACTS.put(key, bytes, {
1062
+ const stored = await this.retaining([key], () => this.env.APP_ARTIFACTS.put(key, bytes, {
879
1063
  onlyIf: { etagDoesNotMatch: "*" },
880
1064
  httpMetadata: { contentType: outputMime(image.data.format) },
881
- });
1065
+ }));
882
1066
  if (stored === null)
883
1067
  throw new MediaOperationError("conflict");
884
1068
  return this.transition(leaseId, "generating", "writing", {
@@ -923,7 +1107,33 @@ export class MediaOperationOwner {
923
1107
  estimatedCostMilliunits: record.estimatedCostMilliunits,
924
1108
  image: record.image,
925
1109
  output: record.output,
926
- writeReceipt: null,
1110
+ writeReceipt: record.writeReceipt,
1111
+ result: null,
1112
+ })));
1113
+ }
1114
+ /**
1115
+ * Record the digest of the exact bytes about to be written to the
1116
+ * destination, before writing them. An erasure then knows which file this
1117
+ * operation owns, even if the process dies between the write and its
1118
+ * record, and refuses the write once erased.
1119
+ */
1120
+ recordWriteIntent(leaseId, sha256) {
1121
+ const receipt = `sha256:${sha256}`;
1122
+ if (!writeReceiptSchema.safeParse(receipt).success)
1123
+ throw new MediaOperationError("invalid_input");
1124
+ const record = this.requireRecord();
1125
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1126
+ throw new MediaOperationError("lease_lost");
1127
+ return this.ctx.storage.transactionSync(() => this.project(this.update({
1128
+ expectedState: "writing",
1129
+ expectedLeaseId: leaseId,
1130
+ state: "writing",
1131
+ leaseId,
1132
+ leaseExpiresAt: record.leaseExpiresAt,
1133
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1134
+ image: record.image,
1135
+ output: record.output,
1136
+ writeReceipt: receipt,
927
1137
  result: null,
928
1138
  })));
929
1139
  }
@@ -1,3 +1,12 @@
1
+ /** Facts an erased operation keeps: its destination file, and whether a billing hold may be open. */
2
+ export type MediaErasureMarker = Readonly<{
3
+ /** The destination path the operation wrote or could have written. */
4
+ destinationPath: string | null;
5
+ /** SHA-256 of the bytes it wrote or was about to write there. */
6
+ writtenSha256: string | null;
7
+ /** The operation was erased before it finished. */
8
+ abandonedGeneration: boolean;
9
+ }>;
1
10
  /** SQL rows stay untrusted until the owner decodes their stored representation. */
2
11
  export type MediaOperationStorage = {
3
12
  /** Native synchronous SQL interface. */
@@ -12,14 +21,19 @@ export type MediaOperationStorage = {
12
21
  transactionSync<T>(body: () => T): T;
13
22
  /** Read the durable erasure marker. */
14
23
  isErased(): Promise<boolean>;
15
- /** Persist the durable erasure marker. */
16
- markErased(): Promise<void>;
24
+ /**
25
+ * Persist the durable erasure marker with the facts the host needs after
26
+ * erasure. Never removed: nothing may delete it.
27
+ */
28
+ markErased(marker: MediaErasureMarker): Promise<void>;
29
+ /** Read the facts kept with the marker, or null for a marker without them. */
30
+ readErasureMarker(): Promise<MediaErasureMarker | null>;
17
31
  /** List local key-value storage keys for erasure readback. */
18
32
  listKeys(): Promise<readonly string[]>;
19
33
  /** Remove any scheduled background alarm. */
20
34
  deleteAlarm(): Promise<void>;
21
- /** Remove local SQL and key-value storage. */
22
- deleteAll(): Promise<void>;
35
+ /** Remove the named key-value entries. */
36
+ deleteKeys(keys: readonly string[]): Promise<void>;
23
37
  /** Read the current background alarm, or null. */
24
38
  getAlarm(): Promise<number | null>;
25
39
  /** Schedule background generation at the given timestamp. */
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
3
3
  import { reportCatchFailure } from "./failure.js";
4
4
  import { mediaUnits } from "./gateway-models.js";
5
5
  import { getMediaModel } from "./model-catalog.js";
6
+ import { mediaWrittenDigest } from "./media-written.js";
6
7
  import { embedProvenance } from "./provenance.js";
7
8
  import { z } from "zod";
8
9
  import { mediaGenerationSettingsSchema, validateMediaGenerationSettings, } from "./index.js";
@@ -135,7 +136,17 @@ export function executeMediaOperation(input) {
135
136
  units: billed.units,
136
137
  providerCostMilliunits: prepared.costMilliunits,
137
138
  }), "billing").pipe(Effect.tapError(releaseEstimate))).priceMilliunits;
138
- yield* call(() => input.operation.recordEstimate(leaseId, costMilliunits), "estimate");
139
+ yield* call(() => input.operation.recordEstimate(leaseId, costMilliunits), "estimate").pipe(
140
+ // Erasure settled its hold before this admit ran, so the hold just
141
+ // opened belongs to nobody: release it rather than leave it to expire.
142
+ Effect.tapError(() => call(async () => {
143
+ const kept = await input.operation.retained(input.coordinates.namespace, input.requestId);
144
+ if (kept === null && metering !== null)
145
+ await metering.settle({ operationId, units: 0 });
146
+ }, "billing").pipe(Effect.catch((cause) => {
147
+ reportCatchFailure("media-operation-erased-hold", cause);
148
+ return Effect.void;
149
+ }))));
139
150
  if (background) {
140
151
  // Video outlives one request: the owner's alarm generates, and a
141
152
  // retry of this request id saves and charges the retained output.
@@ -213,7 +224,7 @@ export function executeMediaOperation(input) {
213
224
  ? yield* call(() => embedProvenance(output.bytes, format.data, {
214
225
  printId: operationId,
215
226
  model: input.request.model,
216
- prompt: input.request.prompt,
227
+ prompt: input.embedPrompt === true ? input.request.prompt : null,
217
228
  createdAt: admission.operation.createdAt,
218
229
  }), "operation")
219
230
  : {
@@ -227,13 +238,28 @@ export function executeMediaOperation(input) {
227
238
  format: output.format,
228
239
  reason: provenance.reason,
229
240
  });
241
+ // The digest of what is about to land is durable before it lands, so an
242
+ // erasure knows which file is this operation's and refuses the write.
243
+ const digest = yield* call(() => mediaWrittenDigest(provenance.bytes), "operation");
244
+ const receipt = `sha256:${digest}`;
245
+ yield* call(() => input.operation.recordWriteIntent(leaseId, digest), "operation");
230
246
  yield* call(() => input.destination.write(provenance.bytes), "destination-write").pipe(Effect.tapError(() => call(() => input.operation.releaseWrite(leaseId), "operation").pipe(Effect.ignore)));
231
247
  image = {
232
248
  bytes: provenance.bytes.byteLength,
233
249
  format: output.format,
234
250
  };
251
+ // The write landed. If erasure won the race the operation can no longer
252
+ // record it, and nothing else points at the file: delete what landed.
253
+ const deleteIfErased = (error) => call(async () => {
254
+ const kept = await input.operation.retained(input.coordinates.namespace, input.requestId);
255
+ if (kept === null)
256
+ await input.destination.remove(digest);
257
+ }, "destination-write").pipe(Effect.catch((cause) => {
258
+ reportCatchFailure("media-operation-erased-write", cause);
259
+ return Effect.void;
260
+ }), Effect.andThen(Effect.fail(error)));
235
261
  if (metering === null) {
236
- yield* call(() => input.operation.recordWrittenWithoutSettlement(leaseId, "computer-write-committed", image), "operation");
262
+ yield* call(() => input.operation.recordWrittenWithoutSettlement(leaseId, receipt, image), "operation").pipe(Effect.catch(deleteIfErased));
237
263
  return {
238
264
  kind: "succeeded",
239
265
  bytes: image.bytes,
@@ -241,7 +267,7 @@ export function executeMediaOperation(input) {
241
267
  costMilliunits,
242
268
  };
243
269
  }
244
- yield* call(() => input.operation.recordWritten(leaseId, "computer-write-committed", image), "operation");
270
+ yield* call(() => input.operation.recordWritten(leaseId, receipt, image), "operation").pipe(Effect.catch(deleteIfErased));
245
271
  }
246
272
  if (metering === null)
247
273
  return { kind: "unavailable" };
@@ -0,0 +1,22 @@
1
+ /** What a destination did when asked to delete a file this operation wrote. */
2
+ export type MediaRemoval =
3
+ /** The file matched what the operation wrote and was deleted. */
4
+ "removed"
5
+ /** Nothing was at the path. */
6
+ | "absent"
7
+ /** The path holds different bytes now; it is not this operation's file and was left alone. */
8
+ | "not-ours"
9
+ /** The destination cannot delete files; the host must remove the matching file itself. */
10
+ | "kept";
11
+ /** Lowercase hex SHA-256 of the exact bytes written to a destination. */
12
+ export declare function mediaWrittenDigest(bytes: Uint8Array): Promise<string>;
13
+ /**
14
+ * Delete the file at a destination path only while it still holds the exact
15
+ * bytes the operation wrote, so a path reused for something else is never lost.
16
+ */
17
+ export declare function removeMediaIfWritten(file: Readonly<{
18
+ /** Read the current bytes at the path, or null when absent. */
19
+ read: () => Promise<Uint8Array | null>;
20
+ /** Delete the file at the path. */
21
+ delete: () => Promise<void>;
22
+ }>, sha256: string): Promise<MediaRemoval>;
@@ -0,0 +1,20 @@
1
+ /** Lowercase hex SHA-256 of the exact bytes written to a destination. */
2
+ export async function mediaWrittenDigest(bytes) {
3
+ const digest = await crypto.subtle.digest("SHA-256", bytes.slice());
4
+ return [...new Uint8Array(digest)]
5
+ .map((byte) => byte.toString(16).padStart(2, "0"))
6
+ .join("");
7
+ }
8
+ /**
9
+ * Delete the file at a destination path only while it still holds the exact
10
+ * bytes the operation wrote, so a path reused for something else is never lost.
11
+ */
12
+ export async function removeMediaIfWritten(file, sha256) {
13
+ const current = await file.read();
14
+ if (current === null)
15
+ return "absent";
16
+ if ((await mediaWrittenDigest(current)) !== sha256)
17
+ return "not-ours";
18
+ await file.delete();
19
+ return "removed";
20
+ }