Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Replicate: follow its files, deadline, throttling and output lifetime rules

Adarshec1f247fe452
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 8699f3ef..73f8c2e9 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -2883,7 +2883,9 @@ function accountTrouble(e: unknown, account: string, providerId: string, stage:
// The provider's own words (provider-keys.ts accountKeyError keeps them, without the key) tell a refused key from a
// model the key may not run.
const said = (e as { said?: unknown } | null)?.said;
- if (typeof status === "number" && status > 0) return diagnoseKey({ stage, status, text: typeof said === "string" ? said : message }, ctx);
+ // How long the provider asked to wait (a 429's Retry-After, kept by the adapter): the next try waits that long.
+ const retryAfterS = (e as { retryAfterS?: unknown } | null)?.retryAfterS;
+ if (typeof status === "number" && status > 0) return diagnoseKey({ stage, status, text: typeof said === "string" ? said : message, ...(typeof retryAfterS === "number" && retryAfterS > 0 && { retryAfterS }) }, ctx);
const net = networkReason(e);
if (net) return diagnoseKey({ stage, error: net }, ctx);
// A step at the provider that failed in words of its own (a voice it couldn't clone): plain words already, its own in details.
@@ -4189,7 +4191,9 @@ async function pollOne(r: Row): Promise<void> {
// whose copy broke off (it is copied again at the next poll).
const healing = own ? pollHeals().get(r.id) : undefined;
if (healing && Date.now() < healing.next) return;
- if (own && typeof ctx.meta.saveNext === "number" && Date.now() < ctx.meta.saveNext) return;
+ // (The owner's Replicate run too: Replicate deletes the file an hour after it is made, so its copy is tried again.)
+ const copyHeals = !!own || (!account && r.provider === "replicate");
+ if (copyHeals && typeof ctx.meta.saveNext === "number" && Date.now() < ctx.meta.saveNext) return;
try {
res = await adapterFor(r.provider, account).poll(ctx);
} catch (e) {
@@ -4382,8 +4386,8 @@ async function pollOne(r: Row): Promise<void> {
try {
// An account's own GPU or key: a copy that breaks off is tried again (the result is made, and paid). The files a
// result links to are kept once, before (never fetched again with each try of the main file).
- const linked = own ? await persistArtifacts(o.meta, r.id, o.url) : undefined;
- outputs.push(await (own ? persistWithRetry(o, r.id, linked) : persistOutput(o, r.id)));
+ const linked = copyHeals ? await persistArtifacts(o.meta, r.id, o.url) : undefined;
+ outputs.push(await (copyHeals ? persistWithRetry(o, r.id, linked) : persistOutput(o, r.id)));
// Still saving: the turn is still this process's.
claimFinish(r.id);
} catch (e) {
@@ -4424,6 +4428,30 @@ async function pollOne(r: Row): Promise<void> {
}
return;
}
+ // The owner's Replicate run: a link to Replicate's file is no result to keep (Replicate deletes it an hour after it
+ // is made). A copy that broke off for a passing reason is tried again at a later poll, with a growing wait, for 15
+ // minutes; one that can't be saved fails the run in words.
+ // https://replicate.com/docs/topics/predictions/data-retention
+ if (copyHeals && /^https?:\/\//.test(o.url ?? "")) {
+ for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);
+ const at = Date.now();
+ const since = typeof ctx.meta.saveSince === "number" ? ctx.meta.saveSince : at;
+ const tries = (typeof ctx.meta.saveTries === "number" ? ctx.meta.saveTries : 0) + 1;
+ if (passingSave(e) && at - since < SAVE_HEAL_MS * SELF_HEAL.scale) {
+ const next = at + backoffMs(tries, { budgetMs: 0, firstMs: 5_000, maxMs: 60_000 }) * SELF_HEAL.scale;
+ db()
+ .prepare(
+ `UPDATE generations SET message = @words, updated_at = @at,
+ external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.saveSince', @since, '$.saveTries', @tries, '$.saveNext', @next)
+ WHERE id = @id AND status = 'running'`,
+ )
+ .run({ id: r.id, words: "Your result is made. Copying it from Replicate", at, since, tries, next });
+ return;
+ }
+ const expired = /^download (403|404|410)$/.test((e as Error).message ?? "");
+ updateLive(r.id, { status: "failed", error: expired ? resultExpired().words : "We couldn't save this result. Press Retry.", completed_at: Date.now(), message: null });
+ return;
+ }
outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });
console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);
}
diff --git a/src/server/providers/replicate.ts b/src/server/providers/replicate.ts
index b72979bd..7d8d1fe1 100644
--- a/src/server/providers/replicate.ts
+++ b/src/server/providers/replicate.ts
@@ -1,10 +1,15 @@
import "server-only";
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
import { loraEndpointFor } from "@/lib/catalog/loras";
import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";
+import { resultExpired } from "@/lib/diagnose";
import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
import { toDataUri } from "../storage";
import { tenant } from "../tenant";
-import type { KeyCheck } from "./fal";
+import { falProvider, type KeyCheck } from "./fal";
import { ProviderError, type ProviderAdapter } from "./types";
/**
@@ -26,6 +31,33 @@ function token(): string {
return cloudKey("replicate");
}
+/**
+ * Replicate's own deadline for a prediction (the Cancel-After header, counted from when it is created): the longest
+ * Fuobe waits for it to start (4 hours; an account's run 30 minutes, account-files.ts ACCOUNT_LIMITS.queueMs) plus the
+ * longest it may run (45 minutes), as generations.ts pollOne counts them. A cancel that never reaches Replicate (a
+ * restart, a network error, a hand-over that lost its race) can't leave a job running: past the deadline Replicate stops
+ * it, as "aborted" when it never started (not billed). https://replicate.com/docs/topics/predictions/create-a-prediction#prediction-deadlines
+ */
+const cancelAfter = () => `${(tenant() ? 30 : 4 * 60) * 60 + 45 * 60}s`;
+
+/** Replicate deletes an API prediction's output an hour after it is made: what a run says when it was too late. */
+export const RESULT_REMOVED = "Replicate deleted this result an hour after it was made, before Fuobe could save it. Press Retry to make it again.";
+
+/**
+ * How long Replicate asks to wait after a 429: its Retry-After header (seconds or a date), else its words ("Expected
+ * available in 30 seconds", "Your rate limit resets in ~30s"). https://replicate.com/docs/topics/predictions/rate-limits
+ */
+export function retryAfterOf(header: string | null, detail: unknown): number | undefined {
+ if (header) {
+ const s = Number(header);
+ if (Number.isFinite(s) && s > 0) return Math.ceil(s);
+ const at = Date.parse(header);
+ if (!Number.isNaN(at)) return Math.max(1, Math.ceil((at - Date.now()) / 1000));
+ }
+ const m = typeof detail === "string" ? /(?:available in|resets in)\s*~?\s*(\d+)\s*s/i.exec(detail) : null;
+ return m ? Number(m[1]) : undefined;
+}
+
async function rFetch(url: string, init: RequestInit = {}): Promise<unknown> {
const t = token();
if (!t && tenant()) throw missingKeyError("replicate");
@@ -47,26 +79,129 @@ async function rFetch(url: string, init: RequestInit = {}): Promise<unknown> {
const b = body as { detail?: string; title?: string };
// A provider's error may echo the request: the token never reaches a message, a row or a log.
const said = redactKey(`replicate ${res.status}: ${b?.detail ?? b?.title ?? String(text).slice(0, 300)}`, t);
- throw accountKeyError("replicate", res.status, said, t) ?? new ProviderError(said, res.status);
+ const err = accountKeyError("replicate", res.status, said, t) ?? new ProviderError(said, res.status);
+ // A throttled call keeps how long Replicate asked to wait (generations.ts waits that long before it asks again).
+ const after = res.status === 429 || res.status >= 500 ? retryAfterOf(res.headers.get("retry-after"), b?.detail) : undefined;
+ throw after ? Object.assign(err, { retryAfterS: after }) : err;
}
return body;
}
+/** Replicate's Files API takes files under 100 MB (POST /v1/files answers 413 "Files must be less than 100MB in size"). */
+export const REPLICATE_FILE_MAX = 100 * 1000 * 1000;
+
+/** A file sent through Replicate's Files API (multipart field `content`): its `urls.get` is the input. */
+async function upload(data: Buffer, contentType: string, name: string): Promise<string> {
+ const form = new FormData();
+ form.append("content", new Blob([new Uint8Array(data)], { type: contentType }), name);
+ const file = (await rFetch(`${api()}/files`, { method: "POST", body: form })) as { urls: { get: string } };
+ return file.urls.get;
+}
+
+/**
+ * The speech of a recording or clip as a small mono Opus file (16 kHz, 32 kbps: about 15 MB an hour), for a transcript
+ * whose file is too big for Replicate's Files API. Null when ffmpeg can't make one.
+ */
+function speechCopy(data: Buffer): Promise<Buffer | null> {
+ return new Promise((resolve) => {
+ let dir: string;
+ try {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-speech-"));
+ fs.writeFileSync(path.join(dir, "in"), data);
+ } catch {
+ return resolve(null);
+ }
+ const out = path.join(dir, "speech.ogg");
+ const done = (ok: boolean) => {
+ let copy: Buffer | null = null;
+ try {
+ if (ok) copy = fs.readFileSync(out);
+ } catch {}
+ fs.rmSync(dir, { recursive: true, force: true });
+ resolve(copy);
+ };
+ const args = ["-hide_banner", "-loglevel", "error", "-y", "-threads", "2", "-i", path.join(dir, "in"), "-vn", "-ac", "1", "-ar", "16000", "-c:a", "libopus", "-b:a", "32k", out];
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(process.env.FFMPEG_PATH || "ffmpeg", args, { stdio: ["ignore", "ignore", "ignore"] });
+ } catch {
+ return done(false);
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 10 * 60_000);
+ child.on("error", () => {
+ clearTimeout(timer);
+ done(false);
+ });
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ done(code === 0);
+ });
+ });
+}
+
+/**
+ * The most file data one create request carries inline, as data URIs. Replicate's own client refuses more ("Combined
+ * filesize of prediction ... exceeds 10mb limit for inline encoding, please provide URLs instead", MAX_DATA_URI_SIZE in
+ * https://github.com/replicate/replicate-javascript/blob/main/lib/util.js), and the docs recommend a data URI only for a
+ * file under 1 MB (https://replicate.com/docs/topics/predictions/input-files). Many references (14 pictures, 24 H3
+ * references) can each be under 1 MB but not together: past the cap, the largest go through the Files API instead.
+ */
+export const INLINE_MAX_BYTES = 10_000_000;
+
+async function capInline(payload: Record<string, unknown>): Promise<void> {
+ const inline: { at: Record<string | number, unknown>; key: string | number; uri: string }[] = [];
+ const walk = (v: unknown): void => {
+ if (!v || typeof v !== "object") return;
+ for (const [k, x] of Object.entries(v)) {
+ if (typeof x === "string" && x.startsWith("data:")) inline.push({ at: v as Record<string | number, unknown>, key: Array.isArray(v) ? Number(k) : k, uri: x });
+ else walk(x);
+ }
+ };
+ walk(payload);
+ const bytes = (uri: string) => Math.floor(((uri.length - uri.indexOf(",") - 1) * 3) / 4);
+ let total = inline.reduce((n, f) => n + bytes(f.uri), 0);
+ for (const f of inline.sort((a, b) => b.uri.length - a.uri.length)) {
+ if (total <= INLINE_MAX_BYTES) break;
+ const head = /^data:([^;,]*)[^,]*;base64,/.exec(f.uri);
+ if (!head) continue;
+ const type = head[1] || "application/octet-stream";
+ f.at[f.key] = await upload(Buffer.from(f.uri.slice(head[0].length), "base64"), type, `input.${type.split("/")[1]?.split("+")[0] || "bin"}`);
+ total -= bytes(f.uri);
+ }
+}
+
export const replicateProvider: ProviderAdapter = {
id: "replicate",
label: "Replicate",
isConfigured: () => !!token(),
- async prepareFile(data, contentType, name) {
+ async prepareFile(data, contentType, name, route) {
+ // A file list the model reads as plain text ("Public URLs": H3 Lite's and HighSpeed's reference_*_urls, FieldMap.publicLinks):
+ // Replicate passes it on as it is, so neither a data: URI nor a Files API link (which needs the token) can be read there.
+ // The file goes to fal.ai's storage, a public https link, when a fal.ai key is set; otherwise the run stops before its job.
+ if (route?.map?.publicLinks) {
+ if (!falProvider.isConfigured()) {
+ throw new ProviderError("This model on Replicate reads reference files only as public web links: add a fal.ai key in Settings, and Fuobe hosts them there");
+ }
+ return falProvider.prepareFile(data, contentType, name);
+ }
if (data.length < 1_000_000) return toDataUri(data, contentType);
- const form = new FormData();
- form.append("content", new Blob([new Uint8Array(data)], { type: contentType }), name);
- const file = (await rFetch(`${api()}/files`, { method: "POST", body: form })) as { urls: { get: string } };
- return file.urls.get;
+ let [body, type, fileName] = [data, contentType, name];
+ // A transcript needs only the speech (Scribe v2 takes Ogg Opus): a recording or clip of 100 MB or more goes as a small copy.
+ if (data.length >= REPLICATE_FILE_MAX && route?.op === "transcribe" && /^(audio|video)\//.test(contentType)) {
+ const speech = await speechCopy(data);
+ if (speech?.length) [body, type, fileName] = [speech, "audio/ogg", `${name.replace(/\.[^.]+$/, "")}.ogg`];
+ }
+ // Sent anyway, a file this big only comes back as Replicate's 413, after the whole upload.
+ if (body.length >= REPLICATE_FILE_MAX)
+ throw new ProviderError(`Replicate takes files under 100 MB, and this one is ${Math.round(body.length / 1e6)} MB. Run it with a fal key, or pick a shorter or smaller file.`, 413);
+ return upload(body, type, fileName);
},
async submit({ route, input }) {
const payload = buildPayload(route.map ?? {}, input);
+ // Many small files together go through the Files API past Replicate's inline cap (the rest stay data URIs).
+ await capInline(payload);
// LoRAs go in the route's own fields (lora_weights[] / one per Wan 2.2 expert) or its LoRA model.
let endpoint: string;
try {
@@ -76,8 +211,8 @@ export const replicateProvider: ProviderAdapter = {
}
const [slug, version] = endpoint.split(":");
const res = (await (version
- ? rFetch(`${api()}/predictions`, { method: "POST", body: JSON.stringify({ version, input: payload }) })
- : rFetch(`${api()}/models/${slug}/predictions`, { method: "POST", body: JSON.stringify({ input: payload }) }))) as {
+ ? rFetch(`${api()}/predictions`, { method: "POST", headers: { "Cancel-After": cancelAfter() }, body: JSON.stringify({ version, input: payload }) })
+ : rFetch(`${api()}/models/${slug}/predictions`, { method: "POST", headers: { "Cancel-After": cancelAfter() }, body: JSON.stringify({ input: payload }) }))) as {
id: string;
};
return { externalId: res.id, payload };
@@ -89,6 +224,7 @@ export const replicateProvider: ProviderAdapter = {
output: unknown;
error?: string;
logs?: string;
+ data_removed?: boolean;
};
if (p.status === "starting") return { state: "queued", message: "Starting" };
if (p.status === "processing") {
@@ -97,6 +233,8 @@ export const replicateProvider: ProviderAdapter = {
return { state: "running", progress: pct ? Number(pct) / 100 : undefined, message: last ?? "Processing" };
}
if (p.status === "succeeded") {
+ // Collected over an hour after it was made (a server that was down that long): Replicate has deleted the output.
+ if (p.data_removed && (p.output === null || p.output === undefined)) return { state: "failed", error: RESULT_REMOVED, trouble: resultExpired() };
// Object outputs (Scribe's {text, words}) are read as the result itself; URL lists keep their order (layers).
const outputs = extractOutputs({ output: p.output }, route?.op);
if (!outputs.length) return { state: "failed", error: noOutputsError({ output: p.output }) };
diff --git a/tests/replicate-file-limit.test.ts b/tests/replicate-file-limit.test.ts
new file mode 100644
index 00000000..ec0b6639
--- /dev/null
+++ b/tests/replicate-file-limit.test.ts
@@ -0,0 +1,86 @@
+import { spawnSync } from "node:child_process";
+import { describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Replicate's Files API takes files under 100 MB: https://replicate.com/docs/topics/predictions/input-files ("This will
+ * work for files up to 100MB") and https://api.replicate.com/openapi.json (POST /v1/files answers 413
+ * application/problem+json "Files must be less than 100MB in size"). Scribe v2 itself takes recordings up to 3 GB and 10
+ * hours (https://replicate.com/elevenlabs/scribe-v2/api), and Fuobe takes uploads up to 200 MB, so a 10-minute stereo WAV
+ * (105.8 MB) or a long clip has to reach Replicate some other way. No key, no network: fetch is answered here.
+ */
+process.env.FUOBE_DATA_DIR = tempDir("fuobe-rep-file-limit-");
+
+const { replicateProvider } = await import("@/server/providers/replicate");
+const { getModel } = await import("@/lib/catalog");
+const { routesFor } = await import("@/lib/catalog/plan");
+
+const hasFfmpeg = spawnSync(process.env.FFMPEG_PATH || "ffmpeg", ["-version"]).status === 0;
+
+type Sent = { url: string; form?: { name: string; type: string; size: number } };
+async function stubbed<T>(fn: () => Promise<T>) {
+ const real = globalThis.fetch;
+ const sent: Sent[] = [];
+ globalThis.fetch = (async (u: string, init: RequestInit = {}) => {
+ const content = init.body instanceof FormData ? (init.body.get("content") as File) : undefined;
+ sent.push({ url: String(u), ...(content && { form: { name: content.name, type: content.type, size: content.size } }) });
+ if (content && content.size >= 100_000_000)
+ return new Response(JSON.stringify({ detail: "Files must be less than 100MB in size" }), { status: 413, headers: { "content-type": "application/problem+json" } });
+ return new Response(JSON.stringify({ id: "f1", urls: { get: "https://api.replicate.com/v1/files/f1" } }), { status: 201 });
+ }) as typeof fetch;
+ try {
+ const result = await fn().then(
+ (v) => ({ ok: true as const, v }),
+ (e: Error) => ({ ok: false as const, e }),
+ );
+ return { result, sent };
+ } finally {
+ globalThis.fetch = real;
+ }
+}
+
+/** A silent 16-bit PCM WAV: `seconds` long, stereo at 44.1 kHz. */
+function silentWav(seconds: number): Buffer {
+ const bytes = seconds * 44_100 * 2 * 2;
+ const b = Buffer.alloc(44 + bytes);
+ b.write("RIFF", 0);
+ b.writeUInt32LE(36 + bytes, 4);
+ b.write("WAVEfmt ", 8);
+ b.writeUInt32LE(16, 16);
+ b.writeUInt16LE(1, 20);
+ b.writeUInt16LE(2, 22);
+ b.writeUInt32LE(44_100, 24);
+ b.writeUInt32LE(44_100 * 4, 28);
+ b.writeUInt16LE(4, 32);
+ b.writeUInt16LE(16, 34);
+ b.write("data", 36);
+ b.writeUInt32LE(bytes, 40);
+ return b;
+}
+
+const route = (id: string, op: string) => routesFor(getModel(id)!, op as never).find((r) => r.provider === "replicate")!;
+
+describe("Replicate's Files API limit (100 MB)", () => {
+ it("never uploads a file of 100 MB or more, and says why in plain words", async () => {
+ const { result, sent } = await stubbed(() => replicateProvider.prepareFile!(Buffer.alloc(100_000_000, 1), "image/png", "big.png", route("lyria-3", "music")));
+ expect(sent).toEqual([]);
+ expect(result.ok).toBe(false);
+ expect(!result.ok && result.e.message).toMatch(/under 100 MB/);
+ });
+
+ it("still sends a file just under 100 MB through the Files API", async () => {
+ const { result, sent } = await stubbed(() => replicateProvider.prepareFile!(Buffer.alloc(99_000_000, 1), "video/mp4", "clip.mp4", route("scribe-v2", "transcribe")));
+ expect(result).toEqual({ ok: true, v: "https://api.replicate.com/v1/files/f1" });
+ expect(sent.map((s) => s.form)).toEqual([{ name: "clip.mp4", type: "video/mp4", size: 99_000_000 }]);
+ });
+
+ it.skipIf(!hasFfmpeg)("sends a transcript's 10-minute WAV (105.8 MB) as a small speech copy", async () => {
+ const wav = silentWav(600);
+ expect(wav.length).toBeGreaterThanOrEqual(100_000_000);
+ const { result, sent } = await stubbed(() => replicateProvider.prepareFile!(wav, "audio/wav", "talk.wav", route("scribe-v2", "transcribe")));
+ expect(result).toEqual({ ok: true, v: "https://api.replicate.com/v1/files/f1" });
+ expect(sent).toHaveLength(1);
+ expect(sent[0].form).toMatchObject({ name: "talk.ogg", type: "audio/ogg" });
+ expect(sent[0].form!.size).toBeLessThan(5_000_000);
+ }, 120_000);
+});
diff --git a/tests/replicate-files-lifetime.test.ts b/tests/replicate-files-lifetime.test.ts
new file mode 100644
index 00000000..6e2e21f8
--- /dev/null
+++ b/tests/replicate-files-lifetime.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Replicate input files as Replicate documents them (read 2026-11-06): a data URI only for a file under 1 MB, at most
+ * 10 MB of them in one request (the official client's cap), and a Files API file lives 24 hours. Stand-ins only: no key
+ * is real and nothing leaves this machine.
+ * https://replicate.com/docs/topics/predictions/input-files
+ * https://github.com/replicate/replicate-javascript/blob/main/lib/util.js (MAX_DATA_URI_SIZE)
+ * https://github.com/replicate/replicate-javascript#replicatefilescreate ("expire after 24 hours")
+ */
+const dir = tempDir("fuobe-replicate-files-");
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+delete process.env.HF_TOKEN;
+
+const { setSetting } = await import("@/server/settings");
+const { db } = await import("@/server/db");
+const { MODELS } = await import("@/lib/catalog");
+const { replicateProvider } = await import("@/server/providers/replicate");
+const loras = await import("@/server/loras");
+
+setSetting("replicateToken", "owner-rep");
+
+describe("Replicate: the data URIs one create request carries", () => {
+ it("keeps at most 10 MB inline; the largest of many sub-1 MB files go through POST /v1/files", async () => {
+ const model = MODELS.find((m) => m.id === "nano-banana-pro")!;
+ const route = model.routes.find((r) => r.provider === "replicate" && r.op === "t2i")!;
+ const real = globalThis.fetch;
+ const sent: { url: string; body: unknown }[] = [];
+ let n = 0;
+ globalThis.fetch = (async (url: string, init: RequestInit = {}) => {
+ sent.push({ url: String(url), body: init.body });
+ const json = String(url).endsWith("/files") ? { id: `f${++n}`, urls: { get: `https://api.replicate.com/v1/files/f${n}` } } : { id: "p1", status: "starting" };
+ return new Response(JSON.stringify(json), { status: 201, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ // 14 pictures (Nano Banana Pro's limit), each 999,999 bytes: every one is a data URI on its own.
+ const images = await Promise.all(Array.from({ length: 14 }, (_, i) => replicateProvider.prepareFile(Buffer.alloc(999_999, i + 1), "image/png", `in-${i}.png`)));
+ expect(images.every((u) => u.startsWith("data:image/png;base64,"))).toBe(true);
+ try {
+ await replicateProvider.submit({ generationId: "g", model, route, input: { prompt: "a quiet harbour", images } as never });
+ } finally {
+ globalThis.fetch = real;
+ }
+ const create = sent.find((s) => s.url.endsWith("/predictions"))!;
+ const input = (JSON.parse(String(create.body)) as { input: { image_input: string[] } }).input;
+ expect(input.image_input).toHaveLength(14);
+ const inlineBytes = input.image_input.filter((u) => u.startsWith("data:")).reduce((t, u) => t + ((u.length - u.indexOf(",") - 1) * 3) / 4, 0);
+ expect(inlineBytes).toBeLessThanOrEqual(10_000_000);
+ expect(sent.filter((s) => s.url.endsWith("/files")).length).toBeGreaterThan(0);
+ expect(input.image_input.filter((u) => !u.startsWith("data:")).every((u) => u.startsWith("https://api.replicate.com/v1/files/"))).toBe(true);
+ });
+});
+
+describe("Replicate: Fuobe's copy of a LoRA on the Files API", () => {
+ it("is not used once it is 20 hours old (Replicate deletes it at 24 hours; a run may wait 4 hours to start)", () => {
+ const file = "replicate-ttl-check.safetensors";
+ loras.recordTrainedMirror(file, "replicate", "https://api.replicate.com/v1/files/ttl");
+ const age = (h: number) => db().prepare("UPDATE lora_mirrors SET created_at = ? WHERE file = ? AND target = 'replicate'").run(Date.now() - h * 3_600_000, file);
+ age(19);
+ expect(loras.gatedFileReady(file, "replicate")).toBe(true);
+ age(21);
+ expect(loras.gatedFileReady(file, "replicate")).toBe(false);
+ });
+});
diff --git a/tests/replicate-lifecycle.test.ts b/tests/replicate-lifecycle.test.ts
new file mode 100644
index 00000000..6ae1b3d8
--- /dev/null
+++ b/tests/replicate-lifecycle.test.ts
@@ -0,0 +1,185 @@
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { startFakeReplicate, type CloudRequest, type FakeCloud } from "./helpers/fake-cloud";
+import { TINY_PNG } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * A Replicate prediction's life as Replicate documents it (read 2026-11-06): a deadline sent with every prediction
+ * (Cancel-After), how long a throttled call asks to wait (429), and an output Replicate deletes an hour after it is made
+ * (data_removed; replicate.delivery links expire). Stand-ins only: no key is real and nothing leaves this machine.
+ * https://replicate.com/docs/topics/predictions/create-a-prediction#prediction-deadlines
+ * https://replicate.com/docs/topics/predictions/rate-limits
+ * https://replicate.com/docs/topics/predictions/data-retention
+ */
+const dir = tempDir("fuobe-replicate-lifecycle-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const generationsRoute = await import("@/app/api/generations/route");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const { resetRates } = await import("@/server/rate");
+const { replicateProvider } = await import("@/server/providers/replicate");
+
+let rep: FakeCloud;
+let delivery: http.Server;
+let deliveryUrl = "";
+/** Answers of the stand-in replicate.delivery, in turn (then 200 with a PNG). */
+let deliveryAnswers: number[] = [];
+let A = "";
+const cookies: Record<string, string> = {};
+
+beforeAll(async () => {
+ rep = await startFakeReplicate();
+ globalThis.__fuobeTestReplicateUrl = rep.url;
+ rep.keys["owner-rep"] = "good";
+ rep.keys["acct-rep-A"] = "good";
+ setSetting("replicateToken", "owner-rep");
+ delivery = http.createServer((req, res) => {
+ const status = deliveryAnswers.shift() ?? 200;
+ if (status !== 200) {
+ res.writeHead(status, { "Content-Type": "text/plain" });
+ return res.end("busy");
+ }
+ res.writeHead(200, { "Content-Type": "image/png", "Content-Length": String(TINY_PNG.length) });
+ res.end(TINY_PNG);
+ });
+ await new Promise<void>((r) => delivery.listen(0, "127.0.0.1", r));
+ deliveryUrl = `http://127.0.0.1:${(delivery.address() as { port: number }).port}`;
+ auth.setPassword("install password");
+ A = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(A, "replicate", "acct-rep-A");
+ cookies.A = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;
+ gens.ensureRunner();
+});
+afterAll(async () => {
+ globalThis.__fuobeTestReplicateUrl = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ gens.SELF_HEAL.scale = 1;
+ await rep.close();
+ await new Promise<void>((r) => delivery.close(() => r()));
+});
+beforeEach(async () => {
+ resetRates();
+ gens.SELF_HEAL.scale = 0.01;
+ globalThis.__fuobePollHeals?.clear();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ rep.log.length = 0;
+ rep.pollsToFinish = 2;
+ rep.script = null;
+ deliveryAnswers = [];
+});
+
+const isPoll = (r: CloudRequest) => r.method === "GET" && /^\/v1\/predictions\/[^/]+$/.test(r.path);
+const accountRun = async () => {
+ const text = JSON.stringify({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour at dawn", prefer: "replicate" });
+ const r = await generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const g = ((await r.json()) as { items: { id: string; provider: string }[] }).items[0];
+ expect(g.provider).toBe("replicate");
+ return g.id;
+};
+const ownerRun = () => {
+ const [g] = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour at dawn" });
+ expect(g.provider).toBe("replicate");
+ return g.id;
+};
+async function settle(id: string, until: (g: NonNullable<ReturnType<typeof gens.getGeneration>>) => boolean = (g) => !["queued", "running"].includes(g.status), ms = 15_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = gens.getGeneration(id, { includeDeleted: true })!;
+ if (until(g) || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 15));
+ }
+}
+
+describe("Replicate: a deadline with every prediction (Cancel-After)", () => {
+ const sent = async (fn: () => Promise<unknown>) => {
+ const real = globalThis.fetch;
+ let headers: Record<string, string> = {};
+ globalThis.fetch = (async (_url: string, init: RequestInit = {}) => {
+ headers = Object.fromEntries(Object.entries((init.headers ?? {}) as Record<string, string>).map(([k, v]) => [k.toLowerCase(), v]));
+ return new Response(JSON.stringify({ id: "p1", status: "starting" }), { status: 201, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ try {
+ await fn();
+ } finally {
+ globalThis.fetch = real;
+ }
+ return headers;
+ };
+ const route = { op: "t2i", provider: "replicate", endpoint: "google/nano-banana-pro", map: {} } as never;
+ const model = { id: "x" } as never;
+
+ it("the owner's: 4 hours to start plus 45 minutes to run; an account's: 30 minutes plus 45", async () => {
+ // Replicate: "Valid values are between 5 seconds and 24 hours"; an integer with s, m or h.
+ expect((await sent(() => replicateProvider.submit({ generationId: "g", model, route, input: { prompt: "x" } as never })))["cancel-after"]).toBe("17100s");
+ const own = await gens.asAccount(A, () => sent(() => replicateProvider.submit({ generationId: "g", model, route, input: { prompt: "x" } as never })));
+ expect(own["cancel-after"]).toBe("4500s");
+ });
+});
+
+describe("Replicate: a throttled call (429) waits as long as Replicate asks", () => {
+ it("keeps the Retry-After header, else the wait in Replicate's words", async () => {
+ const real = globalThis.fetch;
+ const answers = [
+ new Response(JSON.stringify({ detail: "Request was throttled. Expected available in 12 seconds." }), { status: 429, headers: { "content-type": "application/problem+json", "retry-after": "30" } }),
+ new Response(JSON.stringify({ detail: "Request was throttled. Expected available in 12 seconds." }), { status: 429, headers: { "content-type": "application/problem+json" } }),
+ new Response(JSON.stringify({ detail: "Request was throttled. Your rate limit resets in ~30s." }), { status: 429, headers: { "content-type": "application/problem+json" } }),
+ ];
+ globalThis.fetch = (async () => answers.shift()!) as typeof fetch;
+ const waits: unknown[] = [];
+ try {
+ for (let i = 0; i < 3; i++) {
+ await replicateProvider.poll({ externalId: "p1", meta: {}, route: { op: "t2i" } as never, model: {} as never, createdAt: 0 }).catch((e) => waits.push((e as { retryAfterS?: number }).retryAfterS));
+ }
+ } finally {
+ globalThis.fetch = real;
+ }
+ expect(waits).toEqual([30, 12, 30]);
+ });
+
+ it("an account's poll that Replicate throttles asks again after Replicate's wait, not after 5 seconds", async () => {
+ gens.SELF_HEAL.scale = 1;
+ const id = await accountRun();
+ await settle(id, (g) => g.status === "queued" && !!gens.getGeneration(id)?.provider && rep.log.some(isPoll), 5_000);
+ rep.script = (r) => (isPoll(r) ? { status: 429, body: { detail: "Request was throttled. Expected available in 90 seconds." }, headers: { "Retry-After": "90" } } : null);
+ await settle(id, () => !!globalThis.__fuobePollHeals?.get(id), 5_000);
+ const heal = globalThis.__fuobePollHeals!.get(id)!;
+ expect(heal.next - Date.now()).toBeGreaterThan(60_000);
+ await gens.cancelGeneration(id);
+ });
+});
+
+describe("Replicate: an output deleted an hour after it was made", () => {
+ it("an account's run that collects it too late says it expired (not that Replicate sent nothing back)", async () => {
+ rep.script = (r) => (isPoll(r) ? { status: 200, body: { id: r.path.split("/").at(-1), status: "succeeded", output: null, data_removed: true } } : null);
+ const g = await settle(await accountRun());
+ expect(g.status).toBe("failed");
+ expect(g.trouble?.cause).toBe("result-expired");
+ });
+
+ it("the owner's run says so too", async () => {
+ rep.script = (r) => (isPoll(r) ? { status: 200, body: { id: r.path.split("/").at(-1), status: "succeeded", output: null, data_removed: true } } : null);
+ const g = await settle(ownerRun());
+ expect(g.status).toBe("failed");
+ expect(g.error).toMatch(/deleted this result an hour after it was made/);
+ });
+
+ it("the owner's result whose copy breaks off is copied again at a later poll, never kept as Replicate's expiring link", async () => {
+ deliveryAnswers = [503, 503, 503];
+ rep.script = (r) => (isPoll(r) ? { status: 200, body: { id: r.path.split("/").at(-1), status: "succeeded", output: `${deliveryUrl}/xezq/out.png` } } : null);
+ const g = await settle(ownerRun());
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs[0].url.startsWith(deliveryUrl)).toBe(false);
+ expect(g.outputs[0].kind).toBe("image");
+ });
+});
diff --git a/tests/replicate-public-links.test.ts b/tests/replicate-public-links.test.ts
index f2da0521..c0cf17d2 100644
--- a/tests/replicate-public-links.test.ts
+++ b/tests/replicate-public-links.test.ts
@@ -64,8 +64,7 @@ const refsRun = (): Req => ({
inputs: { images: [saveFile({ data: png(200_000), contentType: "image/png", source: "upload" }).url], videos: [saveFile({ data: mp4(1_500_000), contentType: "video/mp4", source: "upload" }).url] },
} as Req);
-// Skipped until the server side lands: FieldMap.publicLinks from scripts/gen-cloud-models.py and src/server/providers/replicate.ts prepareFile sending public links. It fails without that change.
-describe.skip("H3 Lite references on Replicate go as public links", () => {
+describe("H3 Lite references on Replicate go as public links", () => {
it("with a fal.ai key, each reference file goes to fal's storage and its public link is sent", async () => {
setSetting("falKey", "fal_standin");
const [g] = gens.createGenerations(refsRun());