@fungi.computer/darkroom 0.9.2 → 0.11.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.
Files changed (45) hide show
  1. package/README.md +130 -6
  2. package/dist/app-media-contracts.d.ts +104 -0
  3. package/dist/browser.d.ts +1 -0
  4. package/dist/browser.js +1 -0
  5. package/dist/cloudflare/provider.d.ts +5 -4
  6. package/dist/cloudflare/provider.js +20 -9
  7. package/dist/cloudflare/r2-destination.d.ts +50 -0
  8. package/dist/cloudflare/r2-destination.js +59 -0
  9. package/dist/cloudflare.d.ts +3 -2
  10. package/dist/cloudflare.js +1 -0
  11. package/dist/gateway-models.d.ts +44 -9
  12. package/dist/gateway-models.js +52 -20
  13. package/dist/index.d.ts +12 -2
  14. package/dist/index.js +81 -38
  15. package/dist/media-binding.d.ts +6 -0
  16. package/dist/media-content-type.d.ts +5 -0
  17. package/dist/media-content-type.js +49 -0
  18. package/dist/media-generation.js +2 -0
  19. package/dist/media-operation-contract.d.ts +13 -1
  20. package/dist/media-operation-do.d.ts +6 -0
  21. package/dist/media-operation-do.js +37 -2
  22. package/dist/media-operation-owner.d.ts +93 -5
  23. package/dist/media-operation-owner.js +250 -46
  24. package/dist/media-operation-storage.d.ts +18 -4
  25. package/dist/media-operation.js +30 -4
  26. package/dist/media-path.d.ts +3 -0
  27. package/dist/media-path.js +7 -0
  28. package/dist/media-run-lifetime.d.ts +5 -0
  29. package/dist/media-run-lifetime.js +5 -0
  30. package/dist/media-written.d.ts +22 -0
  31. package/dist/media-written.js +20 -0
  32. package/dist/model-catalog.d.ts +226 -0
  33. package/dist/model-catalog.js +254 -9
  34. package/dist/provenance.d.ts +5 -1
  35. package/dist/provenance.js +2 -1
  36. package/dist/reference-read.d.ts +24 -0
  37. package/dist/reference-read.js +26 -0
  38. package/dist/server.d.ts +58 -2
  39. package/dist/server.js +49 -5
  40. package/docs/api/app-media-contracts.md +49 -0
  41. package/docs/api/browser.md +15 -4
  42. package/docs/api/cloudflare.md +254 -5
  43. package/docs/api/index.md +346 -62
  44. package/docs/api/server.md +524 -66
  45. package/package.json +2 -2
@@ -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. */
@@ -4,9 +4,8 @@ import { mediaGenerationSettingsSchema, validateMediaGenerationSettings, } from
4
4
  import { z } from "zod";
5
5
  import { reportCatchFailure } from "./failure.js";
6
6
  import { MediaExecutionError, MediaSafetyFilterRefusal, mediaFailureStageSchema, } from "./execution-error.js";
7
+ import { backgroundProviderTimeoutMs } from "./media-run-lifetime.js";
7
8
  import { mediaProviderDiagnosticWireSchema, } from "@fungi.computer/agar/errors";
8
- /** Safely inside the 15-minute alarm wall-clock limit that would kill the call. */
9
- const backgroundProviderTimeoutMs = 12 * 60_000;
10
9
  const providerFailureSchema = z.strictObject({
11
10
  stage: mediaFailureStageSchema.extract(["provider", "normalization"]),
12
11
  safetyRefused: z.boolean(),
@@ -30,6 +29,33 @@ const audioReferenceMetadataSchema = z.lazy(() => z.object({
30
29
  durationSeconds: z.coerce.number().positive(),
31
30
  }));
32
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
+ ];
33
59
  /** Fixed generation destination captured before provider dispatch. */
34
60
  export const mediaOperationDestinationSchema = z.lazy(() => z.strictObject({
35
61
  /** Host-admitted destination or reference identity. */
@@ -219,6 +245,9 @@ export class MediaOperationOwner {
219
245
  provider;
220
246
  hooks;
221
247
  erased = false;
248
+ retainsInFlight = 0;
249
+ /** Output keys whose delete after a late write failed; erase retries them. */
250
+ lateDeletes = new Set();
222
251
  leaseMs = 5 * 60 * 1_000;
223
252
  /**
224
253
  * A background (video) generation holds its lease past the 15-minute alarm
@@ -241,7 +270,8 @@ export class MediaOperationOwner {
241
270
  this.provider = provider;
242
271
  this.hooks = hooks;
243
272
  void ctx.blockConcurrencyWhile(async () => {
244
- if (await ctx.storage.isErased()) {
273
+ const durablyErased = await ctx.storage.isErased();
274
+ if (durablyErased || this.erased) {
245
275
  this.erased = true;
246
276
  return;
247
277
  }
@@ -402,34 +432,91 @@ export class MediaOperationOwner {
402
432
  }
403
433
  /** Check host namespace, request identity and inactivity before erasure. */
404
434
  preflightErasure(namespace, requestId) {
405
- if (this.ctx.id.name !== `media:${requestId}`)
406
- throw new Error("Media erasure address mismatch");
407
- if (this.erased)
435
+ if (this.erased) {
436
+ this.assertErasureAddress(requestId);
408
437
  return { namespace, requestId, erased: true };
438
+ }
409
439
  const record = this.readRecord();
410
- const ownerNamespace = record?.namespace ?? this.hooks.namespace?.() ?? null;
411
- if ((ownerNamespace !== null && ownerNamespace !== namespace) ||
412
- (record !== null && record.requestId !== requestId))
413
- throw new Error("Media erasure scope mismatch");
440
+ this.assertScope(namespace, requestId, record);
414
441
  if (record !== null &&
415
442
  ["estimating", "generating", "writing", "charging"].includes(record.state))
416
443
  throw new Error("Media operation is still active");
417
444
  return { namespace, requestId, erased: false };
418
445
  }
419
- /** Erase inactive output and local storage, then retain the durable erasure marker. */
420
- async erase(namespace, requestId) {
421
- if (this.erased)
422
- return this.readErasure();
423
- this.preflightErasure(namespace, requestId);
424
- // The operation's immutable output key is owned by this DO identity.
425
- await this.env.APP_ARTIFACTS.delete(this.erasureOutputKey());
426
- if (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey()))
427
- 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();
428
509
  await this.ctx.storage.deleteAlarm();
429
- await this.ctx.storage.deleteAll();
430
- await this.ctx.storage.markErased();
431
- this.erased = true;
432
- 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 };
433
520
  }
434
521
  /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
435
522
  async readErasure() {
@@ -438,14 +525,102 @@ export class MediaOperationOwner {
438
525
  .exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
439
526
  .toArray();
440
527
  return {
441
- clear: keys.length === 1 &&
442
- keys[0] === "botanical:erased" &&
528
+ clear: keys.includes("botanical:erased") &&
529
+ keys.every((key) => key.startsWith("botanical:erased")) &&
443
530
  (await this.ctx.storage.isErased()) &&
444
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 &&
445
535
  (await this.ctx.storage.getAlarm()) === null &&
446
536
  (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey())) === null,
447
537
  };
448
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
+ }
449
624
  erasureOutputKey() {
450
625
  const name = this.ctx.id.name;
451
626
  if (name === undefined)
@@ -588,7 +763,8 @@ export class MediaOperationOwner {
588
763
  format: output.format,
589
764
  },
590
765
  output,
591
- writeReceipt: null,
766
+ // A write may have landed before the worker died; the retry writes the same bytes.
767
+ writeReceipt: record.writeReceipt,
592
768
  result: null,
593
769
  });
594
770
  return {
@@ -679,23 +855,25 @@ export class MediaOperationOwner {
679
855
  const record = this.requireRecord();
680
856
  if (record.state !== "generating" || record.leaseId !== leaseId)
681
857
  throw new MediaOperationError("lease_lost");
682
- for (const [index, reference] of references.entries()) {
683
- await this.env.APP_ARTIFACTS.put(referenceKey(record.operationId, index), reference.bytes, {
684
- customMetadata: {
685
- format: reference.format,
686
- width: String(reference.width),
687
- height: String(reference.height),
688
- },
689
- });
690
- }
691
- for (const [index, clip] of audioReferences.entries()) {
692
- await this.env.APP_ARTIFACTS.put(audioReferenceKey(record.operationId, index), clip.bytes, {
693
- customMetadata: {
694
- mimeType: clip.mimeType,
695
- durationSeconds: String(clip.durationSeconds),
696
- },
697
- });
698
- }
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
+ });
699
877
  const timestamp = Date.now();
700
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);
701
879
  await this.ctx.storage.setAlarm(timestamp);
@@ -876,10 +1054,10 @@ export class MediaOperationOwner {
876
1054
  };
877
1055
  }
878
1056
  const key = `media-output/v1/${record.operationId}`;
879
- const stored = await this.env.APP_ARTIFACTS.put(key, bytes, {
1057
+ const stored = await this.retaining([key], () => this.env.APP_ARTIFACTS.put(key, bytes, {
880
1058
  onlyIf: { etagDoesNotMatch: "*" },
881
1059
  httpMetadata: { contentType: outputMime(image.data.format) },
882
- });
1060
+ }));
883
1061
  if (stored === null)
884
1062
  throw new MediaOperationError("conflict");
885
1063
  return this.transition(leaseId, "generating", "writing", {
@@ -924,7 +1102,33 @@ export class MediaOperationOwner {
924
1102
  estimatedCostMilliunits: record.estimatedCostMilliunits,
925
1103
  image: record.image,
926
1104
  output: record.output,
927
- writeReceipt: null,
1105
+ writeReceipt: record.writeReceipt,
1106
+ result: null,
1107
+ })));
1108
+ }
1109
+ /**
1110
+ * Record the digest of the exact bytes about to be written to the
1111
+ * destination, before writing them. An erasure then knows which file this
1112
+ * operation owns, even if the process dies between the write and its
1113
+ * record, and refuses the write once erased.
1114
+ */
1115
+ recordWriteIntent(leaseId, sha256) {
1116
+ const receipt = `sha256:${sha256}`;
1117
+ if (!writeReceiptSchema.safeParse(receipt).success)
1118
+ throw new MediaOperationError("invalid_input");
1119
+ const record = this.requireRecord();
1120
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1121
+ throw new MediaOperationError("lease_lost");
1122
+ return this.ctx.storage.transactionSync(() => this.project(this.update({
1123
+ expectedState: "writing",
1124
+ expectedLeaseId: leaseId,
1125
+ state: "writing",
1126
+ leaseId,
1127
+ leaseExpiresAt: record.leaseExpiresAt,
1128
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1129
+ image: record.image,
1130
+ output: record.output,
1131
+ writeReceipt: receipt,
928
1132
  result: null,
929
1133
  })));
930
1134
  }
@@ -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,3 @@
1
+ import * as z from "zod";
2
+ /** A fixed destination or reference path: an R2 object key or a file path, never a URL. */
3
+ export declare const mediaPathSchema: z.ZodString;
@@ -0,0 +1,7 @@
1
+ import * as z from "zod";
2
+ /** A fixed destination or reference path: an R2 object key or a file path, never a URL. */
3
+ export const mediaPathSchema = z
4
+ .string()
5
+ .min(1)
6
+ .max(1_024)
7
+ .refine((path) => !path.includes("\0"));
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The longest a background provider call runs before it is cut off, safely
3
+ * inside the 15-minute alarm wall-clock limit that would kill the call.
4
+ */
5
+ export declare const backgroundProviderTimeoutMs: number;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The longest a background provider call runs before it is cut off, safely
3
+ * inside the 15-minute alarm wall-clock limit that would kill the call.
4
+ */
5
+ export const backgroundProviderTimeoutMs = 12 * 60_000;