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.

fal.ai: keep its reasons, stop jobs Fuobe gives up on, and expire its copies

Adarsh720c7939d8ce
diff --git a/src/lib/diagnose.ts b/src/lib/diagnose.ts
index 0f5b8655..0ff1774d 100644
--- a/src/lib/diagnose.ts
+++ b/src/lib/diagnose.ts
@@ -781,8 +781,10 @@ export interface KeyContext {
}
const BALANCE = /exhausted balance|insufficient (credit|balance|funds)|out of credit|top up your balance|payment required|balance has run out/i;
-const CONTENT = /content (checker|policy|moderation)|flagged|nsfw|safety (checker|filter|system)|E005|sensitive/i;
-const PERMISSION = /(do not|don't) have (permission|access)|not authori[sz]ed to (access|use|run)|no access to (this )?(model|app|endpoint)|not allowed to (use|run)/i;
+const CONTENT = /content[ _](checker|policy|moderation)|flagged|nsfw|safety (checker|filter|system)|E005|sensitive/i;
+// fal.ai's 403 also says why in its `type` (providers/fal.ts keeps it): permission_denied, resource_restricted (a model
+// restriction on the key, a spending limit). Only rejected_key is a key to replace.
+const PERMISSION = /(do not|don't) have (permission|access)|not authori[sz]ed to (access|use|run)|no access to (this )?(model|app|endpoint)|not allowed to (use|run)|\b(permission_denied|resource_restricted)\b/i;
/** The provider's words without its "fal 422: " or "replicate 404: " start. */
const providerText = (t: string | undefined) => (t ?? "").replace(/^(fal|replicate)\s+(\d{3}|upload):\s*/i, "");
/** A request field fal or Replicate named in a refusal ("body.image_url", "input.image"), as the person knows it. */
@@ -837,6 +839,12 @@ export function diagnoseKey(f: KeyFailure, ctx: KeyContext): Diagnosis {
retryable: false,
};
}
+ if (status === 404 && (f.stage === "poll" || f.stage === "result")) {
+ // A 404 on a run's status or result is about the run, not the model: the provider has no such job for this key (it
+ // belongs to another account, as when the key was replaced by another account's) or keeps it no longer (fal.ai docs:
+ // Queue API, status and result; Replicate: Get a prediction). Asking again can't bring it back.
+ return { cause: "provider-stopped", words: `${name} no longer has this run for your key. Press Retry to run it again.`, details, actions: [A.retry(), ...other], retryable: false };
+ }
if (status === 404) {
return { cause: "model-unavailable", words: `This model isn't available on ${name} right now. Pick another model.`, details, actions: [A.pick(), ...other], retryable: false };
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 92af42b5..260cdf80 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -2668,6 +2668,19 @@ export const OWN_QUEUE = { scale: 1 };
/** The longest an account's job waits in its own GPU's (or provider's) queue, however it moves. */
const OWN_QUEUE_CAP_MS = 2 * 60 * 60_000;
+/**
+ * Whether another of the account's runs on this provider has started there. fal.ai starts a key's jobs a few at a time
+ * (its concurrency limit: 2 on a new account, more as it buys credit) and keeps the others IN_QUEUE until one of those
+ * ends (fal.ai docs: Concurrency Limits): their place doesn't move meanwhile, but their queue does.
+ */
+function ownRunStarted(id: string, account: string, provider: string): boolean {
+ return !!db()
+ .prepare(
+ "SELECT 1 FROM generations g JOIN generation_runs t ON t.id = g.id WHERE g.id != ? AND g.provider = ? AND g.status = 'running' AND t.started_at IS NOT NULL AND json_extract(g.request_json, '$.account') = ? LIMIT 1",
+ )
+ .get(id, provider, account);
+}
+
/**
* The words a waiting run's tile shows, its wait kept with it (external_meta_json `heal`). False: it isn't waiting any more,
* or this process no longer holds its turn (it stalled, and another took the wait over: that one's wait, and its mark of
@@ -2964,7 +2977,7 @@ const RESENT_WORDS = "Your GPU restarted, so we sent this run again";
const resentRuns = () => (globalThis.__fuobeResent ??= new Set());
/** What a poll can't wait out: a key refused, credit gone, no access; a GPU that wants a password or a sign-in. */
-const FINAL_AT_POLL: ReadonlySet<string> = new Set(["key-rejected", "key-balance", "key-permission", "gpu-password", "gpu-password-wrong", "gpu-sign-in", "address-local"]);
+const FINAL_AT_POLL: ReadonlySet<string> = new Set(["key-rejected", "key-balance", "key-permission", "provider-stopped", "gpu-password", "gpu-password-wrong", "gpu-sign-in", "address-local"]);
/** How long an account's run's polls on its own GPU may keep failing before it stops (its key's provider: the run's own clock). */
const POLL_HEAL_MS = { comfyui: 15 * 60_000 };
@@ -4175,8 +4188,11 @@ async function pollOne(r: Row): Promise<void> {
)
.run({ id: r.id, place, movedAt, busyWith: busyWith ?? null });
}
+ // A job on the account's fal.ai key behind its own started jobs there waits for one of them to end, its place
+ // unmoved (ownRunStarted).
+ const ownAhead = ownQueue && !busyWith && r.provider === "fal" && res?.state === "queued" && ownRunStarted(r.id, own!, r.provider);
// While a job runs ahead of it, that one job may take its own time (45 minutes) before the queue counts as stuck.
- const stillMs = ownQueue && busyWith ? Math.max(queueMs, TIMEOUT_MS) : queueMs;
+ const stillMs = ownQueue && (busyWith || ownAhead) ? Math.max(queueMs, TIMEOUT_MS) : queueMs;
const queueOver = ownQueue
? now - Math.max(run.submitted_at, movedAt) > stillMs * OWN_QUEUE.scale || now - run.submitted_at > OWN_QUEUE_CAP_MS * OWN_QUEUE.scale
: now - run.submitted_at > queueMs;
diff --git a/src/server/loras.ts b/src/server/loras.ts
index 6a1def03..aae19358 100644
--- a/src/server/loras.ts
+++ b/src/server/loras.ts
@@ -28,8 +28,17 @@ export class LoraError extends Error {
}
const CIVITAI_API = "https://civitai.com/api/v1";
-/** fal and Replicate don't document how long an upload lives (unverified): mirrors are made again after this. */
-const MIRROR_TTL_MS: Record<string, number> = { fal: 7 * 86_400_000, replicate: 86_400_000 };
+/**
+ * How long Fuobe uses its copy of a LoRA on a provider before it sends a new one. Fuobe's uploads to fal.ai expire with
+ * its upload retention (providers/fal.ts FAL_KEEP_S: 14 days), so a week there is safe. Replicate's Files API keeps a
+ * file 24 hours ("Files uploaded to Replicate using this endpoint expire after 24 hours",
+ * https://github.com/replicate/replicate-javascript#replicatefilescreate; `expires_at` in
+ * https://api.replicate.com/openapi.json), and Replicate reads it only when the prediction starts, up to 4 hours later
+ * (generations.ts QUEUE_TIMEOUT_MS): so a copy there is used for 20 hours at most.
+ */
+const MIRROR_TTL_MS: Record<string, number> = { fal: 7 * 86_400_000, replicate: 20 * 3_600_000 };
+/** Replicate's Files API takes files under 100 MB (https://api.replicate.com/openapi.json: POST /files, 413). */
+const REPLICATE_LORA_FILE_MAX = 100 * 1000 * 1000;
/** Where Fuobe keeps a LoRA it downloaded only to mirror it (ComfyUI's folder is used when it has the file). */
export const LORA_CACHE_DIR = path.join(DATA_DIR, "loras");
@@ -573,6 +582,10 @@ async function sendOwnLora(l: LoraRef, target: "fal" | "replicate", upload: (dat
}
})();
const local = ownCopy(l.file) ?? inComfy;
+ // Replicate's Files API takes files under 100 MB (POST /v1/files answers 413 "Files must be less than 100MB in size")
+ // and deletes an upload after 24 h. A LoRA fal trained has a public fal.media URL, which Replicate's LoRA fields take as
+ // it is, so a large one goes by that URL.
+ if (local && target === "replicate" && l.url && fs.statSync(/*turbopackIgnore: true*/ local).size >= REPLICATE_LORA_FILE_MAX) return { ...l, hostedUrl: l.url };
if (local) {
onProgress?.(`Sending ${name} to ${target === "fal" ? "fal.ai" : "Replicate"} (once)`);
const data = fs.readFileSync(/*turbopackIgnore: true*/ local);
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 039806c1..2b74ce2b 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -6,11 +6,12 @@ import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payl
import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
import { tenant, tenantAccount } from "../tenant";
import { unzip } from "../unzip";
-import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";
+import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage, RETENTION_MS } from "../account-files";
import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";
import { newScratchOutput } from "../storage";
import type { FieldMap } from "@/lib/catalog/types";
-import { ProviderError, type ProviderAdapter } from "./types";
+import { resultExpired } from "@/lib/diagnose";
+import { ProviderError, type CancelOutcome, type ProviderAdapter } from "./types";
/**
* fal.ai queue API.
@@ -46,11 +47,27 @@ const falRun = () => standIn("fal") ?? RUN;
* $0.01, priced as Pricing.uploadUsd): the id the tool then takes.
*/
async function uploadSong(upload: { endpoint: string; purpose: string }, fileUrl: string): Promise<string> {
- const res = (await falFetch(`${falRun()}/${upload.endpoint}`, { method: "POST", body: JSON.stringify({ file_url: fileUrl, purpose: upload.purpose }) })) as { id?: unknown };
- if (typeof res?.id !== "string" || !res.id) throw Object.assign(new ProviderError("We couldn't send the song. Press Retry."), { said: "Mureka gave no file id" });
- return res.id;
+ for (let attempt = 0; ; attempt++) {
+ let res: { id?: unknown };
+ try {
+ res = (await falFetch(`${falRun()}/${upload.endpoint}`, { method: "POST", body: JSON.stringify({ file_url: fileUrl, purpose: upload.purpose }) })) as { id?: unknown };
+ } catch (e) {
+ // fal.ai never retries a synchronous run: one it marks temporary (X-Fal-Needs-Retry: 1, its sync API reference: a busy
+ // runner, a concurrency limit, a timeout before it started) is sent again, twice at most.
+ if ((e as { needsRetry?: boolean } | null)?.needsRetry && attempt < UPLOAD_RETRY_MS.length) {
+ await new Promise((r) => setTimeout(r, UPLOAD_RETRY_MS[attempt]));
+ continue;
+ }
+ throw e;
+ }
+ if (typeof res?.id !== "string" || !res.id) throw Object.assign(new ProviderError("We couldn't send the song. Press Retry."), { said: "Mureka gave no file id" });
+ return res.id;
+ }
}
+/** The waits before a song's upload is sent again after fal.ai marks it temporary (X-Fal-Needs-Retry: 1). */
+const UPLOAD_RETRY_MS = [1000, 3000];
+
/** The most a stems download may be, and how long it may take: past either, it stops and the run fails. */
const STEMS_MAX_BYTES = 256 * 1024 * 1024;
const STEMS_WAIT_MS = 3 * 60 * 1000;
@@ -164,6 +181,17 @@ function key(): string {
*/
export const FAL_CALL_MS = { long: 60_000, short: 20_000 };
+/**
+ * How long fal.ai keeps the files Fuobe puts on its CDN, in seconds: an upload as long as Fuobe keeps an upload, the files
+ * a job makes as long as Fuobe keeps a run (account-files.ts RETENTION_MS, as the Privacy page says). Unset, fal.ai keeps
+ * them public to anyone with the link, with no end (its default; fal.ai docs: Platform Headers,
+ * X-Fal-Object-Lifecycle-Preference). Fuobe copies a result as soon as it is made, and sends a mirrored LoRA again well
+ * inside both (loras.ts MIRROR_TTL_MS). A training's LoRA gets none (training.ts): fal's copy may be the only one.
+ */
+export const FAL_KEEP_S = { upload: RETENTION_MS.upload / 1000, result: RETENTION_MS.run / 1000 };
+/** The queue submit's header that sets it for the files the job makes. */
+const RESULT_LIFECYCLE = { "X-Fal-Object-Lifecycle-Preference": JSON.stringify({ expiration_duration_seconds: FAL_KEEP_S.result }) };
+
export async function falFetch(url: string, init: RequestInit = {}): Promise<unknown> {
const k = key();
if (!k && tenant()) throw missingKeyError("fal");
@@ -183,7 +211,10 @@ export async function falFetch(url: string, init: RequestInit = {}): Promise<unk
if (!res.ok) {
// A provider's error may echo the request: the key never reaches a message, a row or a log.
const said = redactKey(`fal ${res.status}: ${describeError(body)}`, k);
- throw accountKeyError("fal", res.status, said, k) ?? new ProviderError(said, res.status);
+ const err = accountKeyError("fal", res.status, said, k) ?? new ProviderError(said, res.status);
+ // fal.ai's mark of a temporary failure that a retry can get past (X-Fal-Needs-Retry: 1): read by the synchronous upload.
+ if (res.headers.get("x-fal-needs-retry") === "1") Object.assign(err, { needsRetry: true });
+ throw err;
}
return body;
}
@@ -203,14 +234,40 @@ const clientFetch: typeof fetch = (input, init) => {
function describeError(body: unknown): string {
if (typeof body === "string") return body.slice(0, 500);
- const b = body as { detail?: unknown; error?: unknown; message?: unknown };
+ const b = body as { detail?: unknown; error?: unknown; message?: unknown; type?: unknown; error_type?: unknown };
const d = b.detail ?? b.error ?? b.message ?? body;
if (Array.isArray(d)) {
return d
- .map((e: { loc?: unknown[]; msg?: string }) => `${(e.loc ?? []).join(".")}: ${e.msg ?? JSON.stringify(e)}`)
+ // Each error's `type` too (fal.ai Model Errors: content_policy_violation, image_too_large...): fal.ai says to rely on it,
+ // never on `msg`, whose words change from model to model.
+ .map((e: { loc?: unknown[]; msg?: string; type?: unknown }) => `${(e.loc ?? []).join(".")}: ${e.msg ?? JSON.stringify(e)}${errorKind(e.type)}`)
.join("; ");
}
- return typeof d === "string" ? d : JSON.stringify(d).slice(0, 500);
+ // fal.ai's machine-readable reason, when it gives one (DetailError.type: rejected_key, permission_denied,
+ // resource_restricted; RequestError.error_type: startup_timeout, runner_disconnected...): it tells a refused key from a key
+ // that may not run this model, and a passing failure from one to fix (src/lib/diagnose.ts).
+ return (typeof d === "string" ? d : JSON.stringify(d).slice(0, 500)) + errorKind(b.type ?? b.error_type);
+}
+
+/** fal.ai's category of an error, as " (content_policy_violation)", or "" when it gives none that reads as one. */
+function errorKind(kind: unknown): string {
+ return typeof kind === "string" && /^[a-z_.]{3,60}$/.test(kind) ? ` (${kind})` : "";
+}
+
+/**
+ * Why a job fal.ai finished as failed (status COMPLETED with `error`): its result, which fal.ai answers with the job's own
+ * error (a model's 422 detail[]: a content flag, an image too large; a timeout's detail). The status's `error` is only
+ * "Invalid status code: 422" for those. The status's words when the result says nothing more or can't be read.
+ */
+async function failedJobWords(responseUrl: unknown, statusError: string): Promise<string> {
+ if (typeof responseUrl !== "string" || !responseUrl) return statusError;
+ try {
+ await falFetch(responseUrl);
+ } catch (e) {
+ // The job's own error, not a passing one (the key, busy, a gateway) nor no answer: those keep the status's words.
+ if (e instanceof ProviderError && typeof e.status === "number" && ![401, 402, 403, 404, 429, 502, 503].includes(e.status)) return e.message;
+ }
+ return statusError;
}
/** A plain file name with an extension to upload under ("x.safetensors", "dataset.zip"), or undefined. */
@@ -228,16 +285,25 @@ const CLONE_WAIT_MS = 3 * 60 * 1000;
*/
export async function cloneVoice(cf: NonNullable<FieldMap["cloneFirst"]>, audio: string, transcript?: string, waitMs = CLONE_WAIT_MS): Promise<string> {
const body = { [cf.audio]: audio, ...(cf.text && transcript?.trim() && { [cf.text]: transcript.trim() }) };
- const job = (await falFetch(`${falQueue()}/${cf.endpoint}`, { method: "POST", body: JSON.stringify(body) })) as { status_url: string; response_url: string };
+ const job = (await falFetch(`${falQueue()}/${cf.endpoint}`, { method: "POST", body: JSON.stringify(body), headers: RESULT_LIFECYCLE })) as {
+ status_url: string;
+ response_url: string;
+ cancel_url?: string;
+ };
const until = Date.now() + waitMs;
for (let wait = 500; ; wait = Math.min(wait * 1.5, 3000)) {
const st = (await falFetch(job.status_url)) as { status?: string; error?: string };
if (st.status === "COMPLETED") {
- // fal.ai's own words go to the run's details line; the sentence is plain.
- if (st.error) throw Object.assign(new ProviderError("We couldn't copy this voice. Try a longer, clearer sample, or press Retry."), { said: st.error });
+ // fal.ai's own words go to the run's details line (the job's result holds the model's own); the sentence is plain.
+ if (st.error) throw Object.assign(new ProviderError("We couldn't copy this voice. Try a longer, clearer sample, or press Retry."), { said: await failedJobWords(job.response_url, st.error) });
break;
}
- if (Date.now() + wait > until) throw new ProviderError("Cloning the voice took too long. Try again.");
+ if (Date.now() + wait > until) {
+ // Still queued or running: cancelled on fal.ai (its queue API: PUT cancel_url), so it isn't billed while the run fails
+ // and a retry clones the sample again.
+ if (job.cancel_url) await falFetch(job.cancel_url, { method: "PUT" }).catch(() => {});
+ throw new ProviderError("Cloning the voice took too long. Try again.");
+ }
await new Promise((r) => setTimeout(r, wait));
}
const result = (await falFetch(job.response_url)) as Record<string, unknown>;
@@ -262,10 +328,13 @@ export const falProvider: ProviderAdapter = {
// extension (fal's LTX-2.3 quality takes only .safetensors URLs) refuse.
const blob = fileName(name) ? new File([new Uint8Array(data)], fileName(name)!, { type: contentType }) : new Blob([new Uint8Array(data)], { type: contentType });
try {
- return await client.storage.upload(blob);
+ // Kept on fal.ai's CDN as long as Fuobe keeps an upload, not for ever (the client sends it with the upload's start).
+ return await client.storage.upload(blob, { lifecycle: { expiresIn: FAL_KEEP_S.upload } });
} catch (e) {
const status = (e as { status?: number }).status ?? 0;
- const said = redactKey(`fal ${status || "upload"}: ${(e as Error).message}`, k);
+ // fal.ai's reason is in the error body's `detail`; the client's message is only `message` or the status text.
+ const body = (e as { body?: unknown }).body;
+ const said = redactKey(`fal ${status || "upload"}: ${body != null && typeof body === "object" ? describeError(body) : (e as Error).message}`, k);
throw accountKeyError("fal", status, said, k) ?? new ProviderError(said, status || undefined);
}
},
@@ -301,7 +370,7 @@ export const falProvider: ProviderAdapter = {
}
let res: { request_id: string; status_url: string; response_url: string; cancel_url: string };
try {
- res = (await falFetch(`${falQueue()}/${endpoint}`, { method: "POST", body: JSON.stringify(payload) })) as typeof res;
+ res = (await falFetch(`${falQueue()}/${endpoint}`, { method: "POST", body: JSON.stringify(payload), headers: RESULT_LIFECYCLE })) as typeof res;
} catch (e) {
// The voice it cloned (a billed step) goes with the error: a try again of this run uses it, never clones twice.
throw embedding && e && typeof e === "object" ? Object.assign(e, { voiceEmbedding: embedding }) : e;
@@ -319,6 +388,7 @@ export const falProvider: ProviderAdapter = {
queue_position?: number;
logs?: { message: string }[];
error?: string;
+ error_type?: string;
};
if (status.status === "IN_QUEUE") {
return { state: "queued", ...(status.queue_position != null && { position: status.queue_position }), message: status.queue_position != null ? `In queue · position ${status.queue_position + 1}` : "In queue" };
@@ -329,7 +399,9 @@ export const falProvider: ProviderAdapter = {
return { state: "running", progress: pct ? Number(pct) / 100 : undefined, message: last ?? "Generating" };
}
if (status.status === "COMPLETED") {
- if (status.error) return { state: "failed", error: status.error };
+ // A failed or cancelled job is COMPLETED too, with `error` and `error_type`, its category (fal.ai docs: Request Error
+ // Types). Its result holds fal.ai's words for it (never asked again: the job won't change).
+ if (status.error) return { state: "failed", error: await failedJobWords(meta.responseUrl, status.error + errorKind(status.error_type)) };
try {
const result = await falFetch(meta.responseUrl as string);
// A song's stems come back as one zip (Mureka): each track becomes a result of its own.
@@ -342,6 +414,10 @@ export const falProvider: ProviderAdapter = {
const draftId = /"draft_id"\s*:\s*"([^"]+)"/.exec(JSON.stringify(result))?.[1];
return { state: "succeeded", outputs: draftId ? outputs.map((o) => ({ ...o, draftId })) : outputs };
} catch (e) {
+ // A finished job whose result fal.ai no longer has: 404, kept 1 hour after it ends (6 minutes from 10 KB) when the
+ // fal.ai account doesn't store payloads, or the job is another fal.ai account's (the key was replaced meanwhile).
+ // Made, maybe paid, and gone: asking again can't bring it back (fal.ai docs: Queue API, Get request result).
+ if (e instanceof ProviderError && e.status === 404) return { state: "failed", error: e.message, trouble: resultExpired() };
// An account's finished (and paid) job isn't failed for a passing problem collecting it (busy, down, no answer):
// the runner asks again with a growing wait (generations.ts healPoll).
const s = (e as { status?: number }).status;
@@ -355,8 +431,21 @@ export const falProvider: ProviderAdapter = {
return { state: "running", message: status.status };
},
- async cancel({ meta }) {
- if (meta.cancelUrl) await falFetch(meta.cancelUrl as string, { method: "PUT" }).catch(() => {});
+ async cancel({ meta }): Promise<CancelOutcome | void> {
+ if (!meta.cancelUrl) return;
+ // fal.ai's answer says what happened (fal.ai docs: Queue, "Cancel a Request"): 200 OK took it off the queue (it never
+ // runs); 202 CANCELLATION_REQUESTED sent a stop to a running job, which may still finish (and be charged); 400
+ // ALREADY_COMPLETED: it finished before the cancel came, so its result is there to collect; 404 NOT_FOUND: no such job
+ // for this key.
+ try {
+ const said = (await falFetch(meta.cancelUrl as string, { method: "PUT" })) as { status?: unknown } | null;
+ return said?.status === "OK" ? "removed" : "requested";
+ } catch (e) {
+ const status = (e as { status?: unknown } | null)?.status;
+ if (status === 400 && /ALREADY_COMPLETED/.test(String((e as Error).message))) return "finished";
+ if (status === 404) return "gone";
+ return "unknown";
+ }
},
async test() {
diff --git a/src/server/providers/types.ts b/src/server/providers/types.ts
index a2fba474..dbb8c2ff 100644
--- a/src/server/providers/types.ts
+++ b/src/server/providers/types.ts
@@ -77,7 +77,8 @@ export interface ProviderAdapter {
prepareFile(data: Buffer, contentType: string, name: string, route?: ModelRoute): Promise<string>;
submit(ctx: SubmitContext): Promise<SubmitResult>;
poll(ctx: PollContext): Promise<PollResult>;
- cancel?(ctx: PollContext): Promise<void>;
+ /** Stop the job there. fal.ai says what it did (CancelOutcome); the other providers say nothing. */
+ cancel?(ctx: PollContext): Promise<CancelOutcome | void>;
/**
* Lightweight connectivity check for the settings page. `focus` is the setting the person is
* checking (the Anthropic key, the isolated worker's address…), for a provider whose settings
@@ -86,6 +87,13 @@ export interface ProviderAdapter {
test?(opts?: { focus?: string }): Promise<{ ok: boolean; detail: string }>;
}
+/**
+ * What a provider did with a cancel, when it says (fal.ai): took the job off its queue (it never runs), asked a running job
+ * to stop (it may still finish, and be charged), found it finished already (its result is there), had no such job for this
+ * key, or answered something else.
+ */
+export type CancelOutcome = "removed" | "requested" | "finished" | "gone" | "unknown";
+
export class ProviderError extends Error {
constructor(
message: string,
diff --git a/src/server/training.ts b/src/server/training.ts
index 180fde6a..610ac2a0 100644
--- a/src/server/training.ts
+++ b/src/server/training.ts
@@ -86,6 +86,8 @@ interface Row {
interface Meta {
statusUrl?: string;
responseUrl?: string;
+ /** fal's cancel address (PUT): a queued training is removed, a running one is told to stop. */
+ cancelUrl?: string;
name?: string;
family?: TrainingFamily;
photos?: number;
@@ -393,10 +395,11 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:
request_id: string;
status_url: string;
response_url: string;
+ cancel_url?: string;
};
update(id, {
external_id: res.request_id,
- meta_json: JSON.stringify({ ...meta, statusUrl: res.status_url, responseUrl: res.response_url }),
+ meta_json: JSON.stringify({ ...meta, statusUrl: res.status_url, responseUrl: res.response_url, ...(res.cancel_url && { cancelUrl: res.cancel_url }) }),
status: "running",
message: "Queued on fal",
cost_usd: t.costUsd,
@@ -521,9 +524,16 @@ function trainedLora(r: Row, t: TrainingTarget, file: string, fields: Partial<El
async function pollOne(r: Row) {
const t = getTrainingTarget(r.target);
if (!t) return fail(r.id, r.element_id, retiredTraining(r.target) ?? `Unknown training target ${r.target}`);
- if (Date.now() - r.created_at > MAX_TRAINING_MS) return fail(r.id, r.element_id, `Training didn't finish within ${MAX_TRAINING_MS / 3_600_000} hours`);
const meta = metaOf(r);
const el = getElement(r.element_id);
+ // A fal training Fuobe gives up on (too long, or its element was deleted) is stopped on fal too: fal removes a queued
+ // request and signals a running one (PUT cancel_url), so it isn't trained and billed for a LoRA nobody collects.
+ const giveUp =
+ Date.now() - r.created_at > MAX_TRAINING_MS ? `Training didn't finish within ${MAX_TRAINING_MS / 3_600_000} hours` : r.provider === "fal" && !el ? "Its element was deleted" : undefined;
+ if (giveUp) {
+ if (r.provider === "fal" && meta.cancelUrl) await falFetch(meta.cancelUrl, { method: "PUT" }).catch(() => {});
+ return fail(r.id, r.element_id, giveUp);
+ }
const file = trainedFileName(el?.handle ?? r.element_id, r.id);
if (r.provider === "demo") {
@@ -542,8 +552,9 @@ async function pollOne(r: Row) {
if (r.provider === "fal") {
const s = (await falFetch(`${meta.statusUrl}?logs=1`)) as { status: string; logs?: { message: string }[]; error?: string };
+ // A failed or cancelled job is COMPLETED too, with `error` (the queue's only statuses are IN_QUEUE, IN_PROGRESS and
+ // COMPLETED: fal.ai docs, Queue API, QueueStatus).
if (s.error) return fail(r.id, r.element_id, `fal couldn't train this: ${s.error}`);
- if (s.status === "FAILED" || s.status === "ERROR" || s.status === "CANCELLED") return fail(r.id, r.element_id, `fal training ${s.status.toLowerCase()}`);
if (s.status !== "COMPLETED") {
const last = s.logs?.at(-1)?.message;
const step = last && /(\d+)\s*\/\s*(\d+)/.exec(last);
diff --git a/tests/fal-403-reason.test.ts b/tests/fal-403-reason.test.ts
index cd1681b6..3be0aa28 100644
--- a/tests/fal-403-reason.test.ts
+++ b/tests/fal-403-reason.test.ts
@@ -49,8 +49,7 @@ async function refusedSubmit(type: string, asAccount: boolean) {
return e;
}
-// Skipped until the server side lands: src/server/providers/fal.ts describeError keeps a 403's type, and src/lib/diagnose.ts reads permission_denied and resource_restricted. It fails without that change.
-describe.skip("fal.ai's 403 keeps its reason", () => {
+describe("fal.ai's 403 keeps its reason", () => {
it("the owner's error names it", async () => {
const e = await refusedSubmit("permission_denied", false);
expect(e.message).toBe("fal 403: Forbidden (permission_denied)");
diff --git a/tests/fal-account-queue-spec.test.ts b/tests/fal-account-queue-spec.test.ts
new file mode 100644
index 00000000..7293dc79
--- /dev/null
+++ b/tests/fal-account-queue-spec.test.ts
@@ -0,0 +1,117 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => ({ delete: () => {}, get: () => undefined }) }));
+
+/**
+ * An account's runs on its own fal.ai key, against fal.ai's documented queue (spec audit, 2026-11-06). Stand-in fal.ai
+ * (tests/helpers/fake-cloud.ts): no real key, no paid call.
+ * Status 404: https://fal.ai/docs/api-reference/inference-api/queue/status ("The request does not exist, or it belongs
+ * to a different account"): asking again can't bring it back.
+ * Concurrency: https://fal.ai/docs/documentation/model-apis/concurrency-limits (a key's jobs start a few at a time, 2 on
+ * a new account; "additional requests wait in the queue and are dispatched as soon as a slot frees up. Requests are
+ * never rejected due to concurrency limits").
+ */
+const dir = tempDir("fuobe-fal-account-queue-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FAL_KEY;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const generationsRoute = await import("@/app/api/generations/route");
+await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const { resetRates } = await import("@/server/rate");
+
+let fal: FakeCloud;
+let cookie = "";
+
+beforeAll(async () => {
+ fal = await startFakeFal();
+ globalThis.__fuobeTestFalUrl = fal.url;
+ fal.keys["owner-fal"] = "good";
+ fal.keys["acct-fal"] = "good";
+ setSetting("falKey", "owner-fal");
+ auth.setPassword("install password");
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(id, "fal", "acct-fal");
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+});
+afterAll(async () => {
+ fal.script = null;
+ globalThis.__fuobeTestFalUrl = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fal.close();
+});
+beforeEach(async () => {
+ resetRates();
+ fal.script = null;
+ fal.pollsToFinish = Infinity;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ await new Promise((r) => setTimeout(r, 150));
+});
+
+const run = async () => {
+ const text = JSON.stringify({ feature: "image", prompt: "a quiet harbour at dawn", modelId: "nano-banana-pro", engine: "cloud" });
+ const r = await generationsRoute.POST(
+ new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }),
+ );
+ const json = await r.json();
+ if (r.status !== 201) throw new Error(`${r.status}: ${JSON.stringify(json)}`);
+ return (json.items[0] as { id: string }).id;
+};
+const row = (id: string) => db().prepare("SELECT status, error, message, external_id FROM generations WHERE id = ?").get(id) as { status: string; error: string | null; message: string | null; external_id: string | null };
+const started = (id: string) => !!db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").pluck().get(id);
+async function handedOver(id: string) {
+ for (let i = 0; i < 300 && !row(id).external_id && ["queued", "running"].includes(row(id).status); i++) await new Promise((r) => setTimeout(r, 10));
+ return row(id).external_id!;
+}
+async function ticks(n: number) {
+ for (let i = 0; i < n; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((r) => setTimeout(r, 30));
+ }
+}
+const going = (id: string) => ["queued", "running"].includes(row(id).status);
+
+describe("an account's run on its fal.ai key, as fal.ai's queue documents it", () => {
+ it("a status fal.ai no longer has for the key (404 NOT_FOUND) ends the run at once, in words about the run", async () => {
+ const id = await run();
+ const ext = await handedOver(id);
+ fal.script = (r) => (r.method === "GET" && r.path.split("?")[0].endsWith(`/requests/${ext}/status`) ? { status: 404, body: { status: "NOT_FOUND" } } : null);
+ for (let i = 0; i < 40 && going(id); i++) await ticks(1);
+ // Not "This model isn't available", not "Waiting for your GPU", and not waited out to "fal.ai was busy for 30 minutes".
+ expect(row(id)).toMatchObject({ status: "failed", error: "fal.ai no longer has this run for your key. Press Retry to run it again." });
+ });
+
+ it("a job waiting behind the account's own started fal.ai jobs (its concurrency limit) isn't stopped as 'fal.ai was busy'", async () => {
+ const a = await run();
+ const b = await run();
+ const ahead = new Set([await handedOver(a), await handedOver(b)]);
+ // a and b run at fal.ai; any other job of the key waits at the front of its queue (its place never moves).
+ fal.script = (r) => {
+ const m = /\/requests\/([^/?]+)\/status/.exec(r.path);
+ if (r.method !== "GET" || !m) return null;
+ return { status: 200, body: ahead.has(m[1]) ? { status: "IN_PROGRESS", request_id: m[1], logs: [] } : { status: "IN_QUEUE", request_id: m[1], queue_position: 0 } };
+ };
+ for (let i = 0; i < 40 && !(started(a) && started(b)); i++) await ticks(1);
+ expect(started(a) && started(b)).toBe(true);
+ const c = await run();
+ await handedOver(c);
+ // Sent 31 minutes ago, before its first poll: the 30 minutes an account's job may wait without moving are over.
+ db().prepare("UPDATE generation_runs SET submitted_at = ? WHERE id = ?").run(Date.now() - 31 * 60_000, c);
+ await ticks(4);
+ expect(row(c).status).not.toBe("failed");
+ expect(going(c)).toBe(true);
+ // Once the account's own jobs there are over, a place that still hasn't moved is fal.ai being busy, as before.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id IN (?, ?)").run(a, b);
+ for (let i = 0; i < 20 && going(c); i++) await ticks(1);
+ expect(row(c)).toMatchObject({ status: "failed", error: "fal.ai was busy for 31 minutes, so this run stopped. Press Retry in a few minutes." });
+ });
+});
diff --git a/tests/fal-clone-voice-cancel.test.ts b/tests/fal-clone-voice-cancel.test.ts
new file mode 100644
index 00000000..c0537ad2
--- /dev/null
+++ b/tests/fal-clone-voice-cancel.test.ts
@@ -0,0 +1,42 @@
+/**
+ * Qwen3-TTS's clone step (FieldMap.cloneFirst, src/server/providers/fal.ts cloneVoice) waits on fal.ai's queue for at most
+ * its limit. A clone still queued or running then is cancelled on fal.ai (PUT its cancel_url: fal.ai's queue API, "Cancel a
+ * request", https://fal.ai/docs/api-reference/inference-api/queue/cancel), not left to run and be billed while the run fails
+ * and a retry clones the sample again.
+ */
+import { afterEach, expect, it, vi } from "vitest";
+
+process.env.FAL_KEY = "test-fal-key";
+
+const Q = "https://queue.fal.run/fal-ai/qwen-3-tts";
+const cf = { endpoint: "fal-ai/qwen-3-tts/clone-voice/1.7b", audio: "audio_url", text: "reference_text", output: "speaker_embedding" };
+
+afterEach(() => vi.unstubAllGlobals());
+
+function fakeQueue(status: () => Record<string, unknown>) {
+ const calls: { url: string; method: string }[] = [];
+ vi.stubGlobal("fetch", async (url: string | URL, init: RequestInit = {}) => {
+ const method = init.method ?? "GET";
+ calls.push({ url: String(url), method });
+ const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200, headers: { "content-type": "application/json" } });
+ if (method === "POST") return json({ request_id: "r1", status_url: `${Q}/requests/r1/status`, response_url: `${Q}/requests/r1`, cancel_url: `${Q}/requests/r1/cancel` });
+ if (method === "PUT") return json({ status: "CANCELLATION_REQUESTED" });
+ if (String(url).endsWith("/status")) return json(status());
+ return json({ speaker_embedding: { url: "https://v3b.fal.media/files/b/t/clone_out.safetensors" } });
+ });
+ return calls;
+}
+
+it("a clone that runs past its limit is cancelled on fal.ai", async () => {
+ const calls = fakeQueue(() => ({ status: "IN_QUEUE", queue_position: 4 }));
+ const { cloneVoice } = await import("@/server/providers/fal");
+ await expect(cloneVoice(cf, "https://v3b.fal.media/files/b/t/voice.wav", undefined, 700)).rejects.toThrow(/too long/);
+ expect(calls.filter((c) => c.method === "PUT").map((c) => c.url)).toEqual([`${Q}/requests/r1/cancel`]);
+});
+
+it("a clone that finishes in time is not cancelled, and its file comes back", async () => {
+ const calls = fakeQueue(() => ({ status: "COMPLETED" }));
+ const { cloneVoice } = await import("@/server/providers/fal");
+ await expect(cloneVoice(cf, "https://v3b.fal.media/files/b/t/voice.wav", "What it says.", 5000)).resolves.toBe("https://v3b.fal.media/files/b/t/clone_out.safetensors");
+ expect(calls.some((c) => c.method === "PUT")).toBe(false);
+});
diff --git a/tests/fal-error-types.test.ts b/tests/fal-error-types.test.ts
index 83c4a801..4c0451de 100644
--- a/tests/fal-error-types.test.ts
+++ b/tests/fal-error-types.test.ts
@@ -53,8 +53,7 @@ async function refusedSubmit(status: number, body: unknown, asAccount: boolean)
const PARTNER_REFUSAL = { detail: [{ loc: ["body", "prompt"], msg: "Request rejected by the partner.", type: "content_policy_violation", url: "https://docs.fal.ai/errors#content_policy_violation" }] };
-// Skipped until the server side lands: src/server/providers/fal.ts describeError (each detail's type, a request's error_type) and src/lib/diagnose.ts (content_policy_violation). It fails without that change.
-describe.skip("fal.ai's error kinds are kept", () => {
+describe("fal.ai's error kinds are kept", () => {
it("the owner's 422 names each error's type", async () => {
const e = await refusedSubmit(422, PARTNER_REFUSAL, false);
expect(e.message).toBe("fal 422: body.prompt: Request rejected by the partner. (content_policy_violation)");
diff --git a/tests/fal-failed-job-words.test.ts b/tests/fal-failed-job-words.test.ts
index e21f5bd3..1300bb5b 100644
--- a/tests/fal-failed-job-words.test.ts
+++ b/tests/fal-failed-job-words.test.ts
@@ -67,8 +67,7 @@ async function failedRun() {
return falProvider.poll({ externalId: sent.externalId, meta: sent.meta!, route, model, createdAt: Date.now() });
}
-// Skipped until the server side lands: src/server/providers/fal.ts poll() and cloneVoice() read a failed job's result for the model's own error. It fails without that change.
-describe.skip("a job fal.ai finished as failed keeps fal.ai's reason", () => {
+describe("a job fal.ai finished as failed keeps fal.ai's reason", () => {
it("the owner's run says what the model refused", async () => {
failingJobs({ status: 422, body: FLAGGED });
const r = await failedRun();
diff --git a/tests/fal-queue-spec.test.ts b/tests/fal-queue-spec.test.ts
new file mode 100644
index 00000000..8223a182
--- /dev/null
+++ b/tests/fal-queue-spec.test.ts
@@ -0,0 +1,137 @@
+import http from "node:http";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * fal.ai's queue and storage, as fal.ai documents them (spec audit, 2026-11-06). A stand-in on 127.0.0.1 answers with
+ * the documented shapes; no real key, no paid call.
+ * Cancel answers: https://fal.ai/docs/documentation/model-apis/inference/queue ("Cancel a Request": 200 OK, 202
+ * CANCELLATION_REQUESTED, 400 ALREADY_COMPLETED, 404 NOT_FOUND).
+ * File lifetime: https://fal.ai/docs/documentation/model-apis/common-parameters (X-Fal-Object-Lifecycle-Preference,
+ * default "forever and publicly readable if not configured") and the JS client's storage reference (lifecycle).
+ * Typed errors: https://fal.ai/docs/documentation/model-apis/errors (detail[].type is the category; "Client code should not
+ * parse and rely on the msg field") and .../model-apis/request-errors (error_type).
+ * Result 404: https://fal.ai/docs/api-reference/inference-api/queue/result ("the result expired, or the request belongs
+ * to a different account"); status 404: .../queue/status ("does not exist, or it belongs to a different account").
+ */
+const dir = tempDir("fuobe-fal-queue-spec-");
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FAL_KEY;
+
+const { setSetting } = await import("@/server/settings");
+const { falProvider } = await import("@/server/providers/fal");
+const { getModel } = await import("@/lib/catalog");
+const { diagnoseKey } = await import("@/lib/diagnose");
+
+type Rec = { method: string; path: string; headers: http.IncomingHttpHeaders };
+type Answer = { status: number; body?: unknown };
+const log: Rec[] = [];
+let script: ((r: Rec) => Answer | undefined) | null = null;
+let base = "";
+const ID = "019a1b2c-3d4e-7f80-9a1b-2c3d4e5f6a7b";
+
+function documented(r: Rec): Answer {
+ if (r.method === "POST" && r.path === "/storage/upload/initiate") return { status: 200, body: { upload_url: `${base}/signed/one?sig=x`, file_url: `${base}/files/one.png` } };
+ if (r.method === "PUT" && r.path.startsWith("/signed/")) return { status: 200, body: {} };
+ const m = /^\/([^/]+)\/([^/]+)\/requests\/([^/]+)(\/status|\/cancel)?$/.exec(r.path);
+ if (m) {
+ if (m[4] === "/status") return { status: 200, body: { status: "COMPLETED", request_id: m[3], logs: [], metrics: {} } };
+ if (m[4] === "/cancel") return { status: 202, body: { status: "CANCELLATION_REQUESTED" } };
+ return { status: 200, body: { images: [{ url: `${base}/files/out.png`, content_type: "image/png" }], seed: 1 } };
+ }
+ const [owner, app] = r.path.split("/").slice(1, 3);
+ const at = `${base}/${owner}/${app}/requests/${ID}`;
+ return { status: 200, body: { status: "IN_QUEUE", request_id: ID, response_url: at, status_url: `${at}/status`, cancel_url: `${at}/cancel`, queue_position: 0 } };
+}
+
+let server: http.Server;
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ req.resume();
+ req.on("end", () => {
+ const r: Rec = { method: req.method ?? "", path: new URL(req.url ?? "/", "http://x").pathname, headers: req.headers };
+ log.push(r);
+ const a = script?.(r) ?? documented(r);
+ res.writeHead(a.status, { "Content-Type": "application/json" });
+ res.end(a.body === undefined ? "" : JSON.stringify(a.body));
+ });
+ });
+ await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ globalThis.__fuobeTestFalUrl = base;
+ setSetting("falKey", "fal_spec_key:secret");
+});
+afterAll(async () => {
+ globalThis.__fuobeTestFalUrl = undefined;
+ server.closeAllConnections?.();
+ await new Promise<void>((ok) => server.close(() => ok()));
+});
+
+const t2i = () => {
+ const model = getModel("nano-banana-pro")!;
+ return { model, route: model.routes.find((r) => r.provider === "fal" && r.op === "t2i")! };
+};
+const ctx = () => {
+ const { model, route } = t2i();
+ const at = `${base}/fal-ai/nano-banana-pro/requests/${ID}`;
+ return { externalId: ID, meta: { statusUrl: `${at}/status`, responseUrl: at, cancelUrl: `${at}/cancel` }, route, model, createdAt: 0 } as never;
+};
+const lifecycle = (h: http.IncomingHttpHeaders | undefined) =>
+ JSON.parse(String(h?.["x-fal-object-lifecycle-preference"] ?? h?.["x-fal-object-lifecycle"] ?? "{}")) as { expiration_duration_seconds?: number };
+
+describe("fal.ai queue and storage, as documented", () => {
+ it("a cancel says what fal.ai did: taken off the queue, asked to stop, already finished (its result is there), or no such job", async () => {
+ const said: Record<string, unknown> = {};
+ for (const [status, body] of [
+ [200, { status: "OK" }],
+ [202, { status: "CANCELLATION_REQUESTED" }],
+ [400, { status: "ALREADY_COMPLETED" }],
+ [404, { status: "NOT_FOUND" }],
+ ] as const) {
+ script = (r) => (r.method === "PUT" ? { status, body } : undefined);
+ said[body.status] = await falProvider.cancel!(ctx());
+ }
+ expect(said).toEqual({ OK: "removed", CANCELLATION_REQUESTED: "requested", ALREADY_COMPLETED: "finished", NOT_FOUND: "gone" });
+ });
+
+ it("a run's results and uploads get an expiry on fal.ai's CDN (unset, they stay public forever)", async () => {
+ script = null;
+ const { model, route } = t2i();
+ let from = log.length;
+ await falProvider.submit({ route, model, input: { prompt: "a sunset" } } as never);
+ const submit = log.slice(from).find((r) => r.method === "POST");
+ expect(lifecycle(submit?.headers).expiration_duration_seconds).toBeGreaterThan(0);
+ from = log.length;
+ await falProvider.prepareFile(Buffer.from("x".repeat(100)), "image/png", "face.png");
+ const initiate = log.slice(from).find((r) => r.path === "/storage/upload/initiate");
+ expect(lifecycle(initiate?.headers).expiration_duration_seconds).toBeGreaterThan(0);
+ });
+
+ it("a finished run whose result fal.ai no longer has (404) reads as an expired result, not as a run fal.ai couldn't finish", async () => {
+ script = (r) => (r.method === "GET" && !r.path.endsWith("/status") ? { status: 404, body: { detail: "Request not found" } } : undefined);
+ const res = (await falProvider.poll(ctx())) as { state: string; trouble?: { cause: string } };
+ expect(res.state).toBe("failed");
+ expect(res.trouble?.cause).toBe("result-expired");
+ });
+
+ it("a 404 on a run's status (no such request for this key) is not 'this model isn't available', and isn't waited out", () => {
+ const d = diagnoseKey({ stage: "poll", status: 404, text: 'fal 404: {"status":"NOT_FOUND"}' }, { provider: "fal" });
+ expect(d.cause).not.toBe("model-unavailable");
+ expect(d.retryable).toBe(false);
+ // At submit a 404 is still the model (queue submit: "The model does not exist").
+ expect(diagnoseKey({ stage: "submit", status: 404, text: "fal 404: Application not found" }, { provider: "fal" }).cause).toBe("model-unavailable");
+ });
+
+ it("fal.ai's typed errors keep their category: a partner's moderation (content_policy_violation) reads as the safety check", async () => {
+ const detail = [{ loc: ["body", "prompt"], msg: "Your request was rejected by the partner's moderation.", type: "content_policy_violation", url: "https://docs.fal.ai/errors#content_policy_violation", categories: ["model_moderated"] }];
+ script = (r) => (r.method === "POST" && !r.path.startsWith("/storage") ? { status: 422, body: { detail } } : undefined);
+ const { model, route } = t2i();
+ const e = (await falProvider.submit({ route, model, input: { prompt: "a sunset" } } as never).catch((x: unknown) => x)) as { message: string; status: number };
+ expect(e.status).toBe(422);
+ expect(diagnoseKey({ stage: "submit", status: 422, text: e.message }, { provider: "fal" }).cause).toBe("content-flag");
+ // A failed job's status: its error_type goes with its words.
+ script = (r) => (r.path.endsWith("/status") ? { status: 200, body: { status: "COMPLETED", request_id: ID, error: "No runner could take the request", error_type: "runner_scheduling_failure", logs: [], metrics: {} } } : undefined);
+ expect(await falProvider.poll(ctx())).toMatchObject({ state: "failed", error: expect.stringContaining("runner_scheduling_failure") });
+ script = null;
+ });
+});
diff --git a/tests/fal-training-queue-spec.test.ts b/tests/fal-training-queue-spec.test.ts
new file mode 100644
index 00000000..7ed751d1
--- /dev/null
+++ b/tests/fal-training-queue-spec.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * A LoRA training on fal.ai's queue, as the queue documents it (spec audit, 2026-11-06). The network is faked; no real key,
+ * no paid call.
+ * https://fal.ai/docs/api-reference/inference-api/openapi/queue.json: QueueStatus.status is IN_QUEUE, IN_PROGRESS or
+ * COMPLETED ("A failed or cancelled request also has the status COMPLETED", with `error`).
+ * https://fal.ai/docs/documentation/model-apis/inference/queue ("Cancel a Request"): a job runs, and is charged, until it
+ * is cancelled with PUT cancel_url.
+ */
+vi.mock("@/server/providers/fal", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@/server/providers/fal")>();
+ return { ...real, falProvider: { ...real.falProvider, prepareFile: async (_d: Buffer, _t: string, name?: string) => `https://fal.test/upload/${name ?? "file"}` } };
+});
+
+const dir = tempDir("fuobe-fal-training-queue-");
+process.env.FUOBE_DATA_DIR = dir;
+const { db } = await import("@/server/db");
+const { createElement, updateElement } = await import("@/server/elements");
+const { startTraining, pollTrainings, listTrainings } = await import("@/server/training");
+const { setSetting } = await import("@/server/settings");
+
+interface Call {
+ url: string;
+ method: string;
+}
+let calls: Call[] = [];
+let routes: Record<string, (c: Call) => Response> = {};
+const realFetch = globalThis.fetch;
+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+beforeEach(() => {
+ calls = [];
+ routes = {};
+ globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
+ const call = { url: String(input), method: init?.method ?? "GET" };
+ calls.push(call);
+ const hit = Object.keys(routes)
+ .sort((a, b) => b.length - a.length)
+ .find((k) => call.url.startsWith(k));
+ return hit ? routes[hit](call) : json({ detail: "not here" }, 404);
+ }) as typeof fetch;
+ setSetting("falKey", "test-key");
+ setSetting("engineMode", "both");
+ setSetting("demoMode", "auto");
+});
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+const PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
+const character = () => createElement({ name: `Maya ${Math.random().toString(36).slice(2, 6)}`, kind: "character", references: Array.from({ length: 6 }, () => PNG) });
+
+describe("a LoRA training on fal.ai's queue", () => {
+ it("keeps the cancel address fal.ai gives, and stops the job there when Fuobe gives up on it", async () => {
+ const at = "https://queue.fal.run/fal-ai/flux-lora-fast-training/requests/req-1";
+ routes["https://queue.fal.run/"] = (c) => (c.method === "POST" ? json({ status: "IN_QUEUE", request_id: "req-1", status_url: `${at}/status`, response_url: at, cancel_url: `${at}/cancel`, queue_position: 0 }) : json({ status: "IN_QUEUE", request_id: "req-1", queue_position: 0 }, 202));
+ const el = character();
+ const t = startTraining(el.id, "fal-z-image", { consent: true });
+ for (let i = 0; i < 200 && !calls.some((c) => c.method === "POST" && c.url.startsWith("https://queue.fal.run/")); i++) await new Promise((r) => setTimeout(r, 10));
+ for (let i = 0; i < 100 && !db().prepare("SELECT external_id FROM trainings WHERE id = ?").pluck().get(t.id); i++) await new Promise((r) => setTimeout(r, 10));
+ const meta = JSON.parse(db().prepare("SELECT meta_json FROM trainings WHERE id = ?").pluck().get(t.id) as string) as Record<string, unknown>;
+ expect(meta.cancelUrl).toBe(`${at}/cancel`);
+ // Past Fuobe's longest training (8 hours) it fails here, and fal.ai is told to stop (it would run on, and charge).
+ db().prepare("UPDATE trainings SET created_at = ? WHERE id = ?").run(Date.now() - 9 * 3_600_000, t.id);
+ routes[`${at}/cancel`] = () => json({ status: "CANCELLATION_REQUESTED" }, 202);
+ await pollTrainings();
+ expect(listTrainings(el.id).find((x) => x.id === t.id)?.status).toBe("failed");
+ expect(calls.filter((c) => c.url === `${at}/cancel`).map((c) => c.method)).toEqual(["PUT"]);
+ updateElement(el.id, { status: "ready" });
+ });
+});
diff --git a/tests/fal-upload-error-detail.test.ts b/tests/fal-upload-error-detail.test.ts
new file mode 100644
index 00000000..74861ae2
--- /dev/null
+++ b/tests/fal-upload-error-detail.test.ts
@@ -0,0 +1,50 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * A refused file upload keeps fal.ai's reason. fal.ai's errors carry `detail` (its DetailError, docs: Queue submit), and
+ * the fal client's ApiError.message reads only `message`, else the status text ("Forbidden"). An exhausted balance must
+ * read as one: the owner sees fal.ai's words, an account the empty-balance message, not "didn't accept your key".
+ * Stand-in fal.ai (tests/helpers/fake-cloud.ts): no real key, no paid call.
+ */
+const dir = tempDir("fuobe-fal-upload-error-");
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const { setSetting } = await import("@/server/settings");
+const { runAsTenant } = await import("@/server/tenant");
+const { falProvider } = await import("@/server/providers/fal");
+const { balanceMessage } = await import("@/lib/your-keys");
+
+let fal: FakeCloud;
+let A = "";
+beforeAll(async () => {
+ fal = await startFakeFal();
+ globalThis.__fuobeTestFalUrl = fal.url;
+ fal.keys["owner-broke"] = "broke";
+ fal.keys["acct-broke"] = "broke";
+ setSetting("falKey", "owner-broke");
+ auth.setPassword("install password");
+ A = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(A, "fal", "acct-broke");
+});
+afterAll(async () => {
+ globalThis.__fuobeTestFalUrl = undefined;
+ await fal.close();
+});
+
+describe("a refused fal.ai upload keeps fal.ai's reason", () => {
+ it("the owner's run says the balance is exhausted", async () => {
+ const e = (await falProvider.prepareFile(Buffer.from("png"), "image/png", "in.png").catch((x: unknown) => x)) as Error;
+ expect(e).toBeInstanceOf(Error);
+ expect(e.message).toMatch(/^fal 403: User is locked\. Reason: Exhausted balance/);
+ });
+
+ it("an account's run reads as an empty balance, not a refused key", async () => {
+ const e = (await runAsTenant({ kind: "account", id: A }, () => falProvider.prepareFile(Buffer.from("png"), "image/png", "in.png")).catch((x: unknown) => x)) as Error;
+ expect(e.message).toBe(balanceMessage("fal"));
+ });
+});
diff --git a/tests/training-lora-hosted.test.ts b/tests/training-lora-hosted.test.ts
new file mode 100644
index 00000000..47cd5265
--- /dev/null
+++ b/tests/training-lora-hosted.test.ts
@@ -0,0 +1,103 @@
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { LoraRef } from "@/lib/catalog/types";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * What fal's queue and Replicate's file store document, for a training and a LoRA copy:
+ * - fal: PUT cancel_url removes a queued request and signals a running one (Queue API, "Cancel a request");
+ * - Replicate: an upload expires 24 h after it is made (POST /v1/files answers expires_at; replicate-javascript README:
+ * "Files uploaded to Replicate using this endpoint expire after 24 hours"), and takes files under 100 MB
+ * (https://api.replicate.com/openapi.json: POST /files answers 413 "Files must be less than 100MB in size").
+ * fetch is answered here: no key, no paid call, no network.
+ */
+process.env.FUOBE_DATA_DIR = tempDir("fuobe-training-lora-hosted-");
+
+const { setSetting } = await import("@/server/settings");
+const { createElement, deleteElement } = await import("@/server/elements");
+const { startTraining, listTrainings, pollTrainings } = await import("@/server/training");
+const { prepareCloudLoras, lorasPath, TRAINED_DIR } = await import("@/server/loras");
+
+const JPEG = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0xff, 0xd9]).toString("base64")}`;
+
+type Call = { url: string; method: string };
+function answerAsFal(calls: Call[]): typeof fetch {
+ return (async (input: string | URL | Request, init: RequestInit = {}) => {
+ const url = input instanceof Request ? input.url : String(input);
+ calls.push({ url, method: init.method ?? "GET" });
+ if (url.includes("/storage/upload/initiate")) return Response.json({ upload_url: "https://upload.example/dataset.zip", file_url: "https://v3b.fal.media/files/b/0a9/dataset.zip" });
+ if (url.startsWith("https://upload.example/")) return new Response("");
+ if (url.startsWith("https://queue.fal.run/") && !url.includes("/requests/")) {
+ return Response.json({ request_id: "r1", status_url: `${url}/requests/r1/status`, response_url: `${url}/requests/r1`, cancel_url: `${url}/requests/r1/cancel` });
+ }
+ if (url.endsWith("/requests/r1/cancel")) return Response.json({ status: "CANCELLATION_REQUESTED" }, { status: 202 });
+ if (url.includes("/requests/r1/status")) return Response.json({ status: "IN_PROGRESS", request_id: "r1", logs: [{ message: "Step 10/2000", timestamp: "2026-11-06T00:00:00Z" }] }, { status: 202 });
+ return new Response("not here", { status: 404 });
+ }) as typeof fetch;
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("a fal training Fuobe stops waiting for is cancelled on fal", () => {
+ it("deleting the element of a running training sends PUT cancel_url and fails the training", async () => {
+ setSetting("falKey", "test-id:test-secret");
+ setSetting("demoMode", "off");
+ const real = globalThis.fetch;
+ const calls: Call[] = [];
+ globalThis.fetch = answerAsFal(calls);
+ try {
+ const el = createElement({ name: "Maya cancel", kind: "character", description: "short dark hair", references: Array.from({ length: 6 }, () => JPEG) });
+ const tr = startTraining(el.id, "fal-z-image", { consent: true });
+ for (let i = 0; i < 500 && listTrainings().find((x) => x.id === tr.id)?.status === "queued"; i++) await new Promise((r) => setTimeout(r, 10));
+ expect(listTrainings().find((x) => x.id === tr.id)?.status).toBe("running");
+ deleteElement(el.id);
+ await pollTrainings();
+ expect(calls.filter((c) => c.method === "PUT" && c.url.endsWith("/requests/r1/cancel"))).toHaveLength(1);
+ expect(listTrainings().find((x) => x.id === tr.id)).toMatchObject({ status: "failed" });
+ } finally {
+ globalThis.fetch = real;
+ }
+ }, 30_000);
+});
+
+describe("a LoRA copied to Replicate is copied again before Replicate deletes it", () => {
+ it("reuses the copy within the day, and makes a new one in the last hour of its 24 h", async () => {
+ const file = "fuobe/maya-ttl.safetensors";
+ const p = lorasPath(TRAINED_DIR, file);
+ fs.mkdirSync(path.dirname(p), { recursive: true });
+ fs.writeFileSync(p, Buffer.alloc(1_500_000, 3));
+ const lora: LoraRef = { file, own: true, strength: 1 };
+ let n = 0;
+ const upload = vi.fn(async () => `https://api.replicate.com/v1/files/f${++n}`);
+ vi.useFakeTimers({ toFake: ["Date"] });
+ const t0 = new Date("2026-11-06T10:00:00Z").getTime();
+ vi.setSystemTime(t0);
+ expect((await prepareCloudLoras([lora], "replicate", upload))?.[0].hostedUrl).toBe("https://api.replicate.com/v1/files/f1");
+ vi.setSystemTime(t0 + 2 * 3_600_000);
+ expect((await prepareCloudLoras([lora], "replicate", upload))?.[0].hostedUrl).toBe("https://api.replicate.com/v1/files/f1");
+ // 23 h 30 min after the upload: Replicate deletes the file in 30 min, so a run sent now gets a new copy.
+ vi.setSystemTime(t0 + 23.5 * 3_600_000);
+ expect((await prepareCloudLoras([lora], "replicate", upload))?.[0].hostedUrl).toBe("https://api.replicate.com/v1/files/f2");
+ expect(upload).toHaveBeenCalledTimes(2);
+ });
+
+ it("a trained LoRA of 100 MB or more goes to Replicate by its fal URL, never through the Files API (it takes files under 100 MB)", async () => {
+ const file = "fuobe/maya-big.safetensors";
+ const p = lorasPath(TRAINED_DIR, file);
+ fs.mkdirSync(path.dirname(p), { recursive: true });
+ // A sparse file: 120 MB long, nothing written.
+ fs.closeSync(fs.openSync(p, "w"));
+ fs.truncateSync(p, 120_000_000);
+ const url = "https://v3b.fal.media/files/b/big/pytorch_lora_weights.safetensors";
+ const upload = vi.fn(async () => "https://api.replicate.com/v1/files/big");
+ const sent = await prepareCloudLoras([{ file, url, own: true, strength: 1 }], "replicate", upload);
+ expect(sent?.[0].hostedUrl).toBe(url);
+ expect(upload).not.toHaveBeenCalled();
+ // fal takes it as before (Fuobe's own copy, sent once).
+ const falUpload = vi.fn(async () => "https://v3b.fal.media/files/b/copy/maya-big.safetensors");
+ expect((await prepareCloudLoras([{ file, url, own: true, strength: 1 }], "fal", falUpload))?.[0].hostedUrl).toBe("https://v3b.fal.media/files/b/copy/maya-big.safetensors");
+ }, 60_000);
+});