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.

Runs on your own GPU or key: a cut-off send is never sent twice, a waiting batch moves to a key once, smaller copies are bounded

Adarshaf3aca45e195
diff --git a/src/app/api/generations/[id]/smaller/route.ts b/src/app/api/generations/[id]/smaller/route.ts
index 35d867c1..1f7dad60 100644
--- a/src/app/api/generations/[id]/smaller/route.ts
+++ b/src/app/api/generations/[id]/smaller/route.ts
@@ -1,8 +1,8 @@
import { requestAccount } from "@/server/auth";
import { generationAccount } from "@/server/account-library";
import { getGeneration } from "@/server/generations";
-import { hit } from "@/server/rate";
-import { SmallerCopyError, withSmallerCopy } from "@/server/smaller-copy";
+import { hit, unhit } from "@/server/rate";
+import { SmallerCopyBusy, SmallerCopyError, withSmallerCopy } from "@/server/smaller-copy";
/**
* "Send a smaller copy" (an account's own failed run whose file was too big, or too slow, to send to its GPU): a smaller
@@ -17,13 +17,30 @@ export async function POST(request: Request, ctx: RouteContext<"/api/generations
if (!g) return Response.json({ error: "We can't find that run." }, { status: 404 });
const cause = g.status === "failed" ? g.trouble?.cause : undefined;
if (cause !== "gpu-too-big" && cause !== "gpu-slow-upload") return Response.json({ error: "This run's files weren't too big. Press Retry." }, { status: 409 });
- const rate = hit(`smaller:${account.id}`, 6, 60_000);
- if (!rate.ok) return Response.json({ error: "Making smaller copies takes a moment. Try again in a minute." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+ // A copy is real work (a clip is encoded again): a few for each run, and a few more for the account, each hour.
+ const keys = [`smaller:${account.id}:${id}`, `smaller:${account.id}`];
+ const limits = [SMALLER_RATE.perRun, SMALLER_RATE.perAccount];
+ for (let i = 0; i < keys.length; i++) {
+ const rate = hit(keys[i], limits[i], 60 * 60_000);
+ if (!rate.ok) {
+ for (const k of keys.slice(0, i)) unhit(k);
+ const minutes = Math.max(1, Math.ceil(rate.retryAfterS / 60));
+ return Response.json({ error: `You've made a few smaller copies already. Try again in ${minutes} minute${minutes === 1 ? "" : "s"}.` }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+ }
+ }
try {
const { request: again, bytes } = await withSmallerCopy(account.id, g.request);
return Response.json({ request: again, note: `Sent a smaller copy (${Math.max(1, Math.round(bytes / 2 ** 20))} MB).` });
} catch (e) {
+ // Busy (its last copy, or the server's few at once): not counted, and said with when to try again.
+ if (e instanceof SmallerCopyBusy) {
+ for (const k of keys) unhit(k);
+ return Response.json({ error: e.message }, { status: 429, headers: { "Retry-After": "30" } });
+ }
if (e instanceof SmallerCopyError) return Response.json({ error: e.message }, { status: 422 });
throw e;
}
}
+
+/** Smaller copies an account may ask for in an hour: of one run, and in all. */
+const SMALLER_RATE = { perRun: 3, perAccount: 12 };
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 3fa9d1ab..0e8e787a 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -47,41 +47,83 @@ export async function GET(request: Request) {
return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: viewer.kind === "account" ? viewer.account.id : undefined }) });
}
-/** A run waiting for the account's own GPU or key to come back: no job yet, its wait kept with it (generations.ts `heal`). */
-const WAITING = "(external_id IS NULL AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.heal') IS NOT NULL)";
+/**
+ * A run waiting for the account's own GPU to come back: no job yet, its wait kept with it (generations.ts `heal`). A run
+ * waiting on a key (its provider busy or down) isn't one: it counts among the runs going now, so a provider that is down
+ * can't gather more of them than that.
+ */
+const WAITING = "(provider = 'comfyui' AND external_id IS NULL AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.heal') IS NOT NULL)";
+
+/** Leave out the runs a new one takes the place of (a JSON list of ids). */
+const NOT_REPLACED = "id NOT IN (SELECT value FROM json_each(?))";
/**
* An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. Runs
- * waiting for its own GPU or key are counted apart (`waiting`): they use neither while they wait. `except`: a run the new
- * one takes the place of ("Run with your key" on a waiting run).
+ * waiting for its own GPU are counted apart (`waiting`): they use nothing while they wait. `except`: the runs the new one
+ * takes the place of ("Run with your key" on a waiting run).
*/
-function activeRuns(accountId: string, except?: string): number {
+function activeRuns(accountId: string, except: readonly string[] = []): number {
const r = db()
.prepare(
- `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ? AND NOT ${WAITING} AND id IS NOT ?`,
+ `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ? AND NOT ${WAITING} AND ${NOT_REPLACED}`,
)
- .get(accountId, except ?? null) as { n: number };
+ .get(accountId, JSON.stringify(except)) as { n: number };
return r.n;
}
-function waitingRuns(accountId: string, except?: string): number {
+function waitingRuns(accountId: string, except: readonly string[] = []): number {
const r = db()
- .prepare(`SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status = 'queued' AND json_extract(request_json, '$.account') = ? AND ${WAITING} AND id IS NOT ?`)
- .get(accountId, except ?? null) as { n: number };
+ .prepare(`SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status = 'queued' AND json_extract(request_json, '$.account') = ? AND ${WAITING} AND ${NOT_REPLACED}`)
+ .get(accountId, JSON.stringify(except)) as { n: number };
return r.n;
}
+/** What a new run takes the place of: the rows that stop once it is made, and how many outputs they were to make. */
+interface Replaced {
+ ids: string[];
+ /** The outputs the stopped rows were to make (none: the request's own count stays). */
+ outputs?: number;
+}
+
+/** A `replaces` for a run that can't be taken over any more: started on its GPU meanwhile, or stopped already. */
+const NOT_REPLACEABLE = "This run has already started or stopped, so nothing new was run.";
+
/**
* Beside the request: the account's own run (waiting for its GPU or key, or failed) this one takes the place of ("Run
- * with your fal.ai key" on it): it stops once this one is made.
+ * with your fal.ai key" on it). A waiting run takes its whole batch with it: every job of the same request not handed
+ * over yet stops once this one is made, and this one makes their outputs (never the whole batch again). Undefined: no
+ * `replaces`; null: one that can't be taken over any more (asked again just before the run is made, nothing awaited).
*/
-function replacedRun(body: unknown, accountId: string): string | undefined {
+function replacedRun(body: unknown, accountId: string): Replaced | null | undefined {
const id = (body as { replaces?: unknown } | null)?.replaces;
- if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,40}$/.test(id)) return undefined;
- const row = db().prepare("SELECT status, external_id FROM generations WHERE id = ? AND json_extract(request_json, '$.account') = ?").get(id, accountId) as { status: string; external_id: string | null } | undefined;
- return row && (row.status === "failed" || (row.status === "queued" && !row.external_id)) ? id : undefined;
+ if (id === undefined || id === null) return undefined;
+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,40}$/.test(id)) return null;
+ const row = db()
+ .prepare("SELECT status, external_id, batch_id, request_json FROM generations WHERE id = ? AND json_extract(request_json, '$.account') = ?")
+ .get(id, accountId) as { status: string; external_id: string | null; batch_id: string | null; request_json: string } | undefined;
+ if (!row) return null;
+ if (row.status === "failed") return { ids: [id] };
+ if (row.status !== "queued" || row.external_id) return null;
+ if (!row.batch_id) return { ids: [id] };
+ // Its batch's jobs (the same request; a chain's later steps have their own), and those not handed over yet.
+ const jobs = db()
+ .prepare("SELECT id, status, external_id FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL")
+ .all(row.batch_id, row.request_json) as { id: string; status: string; external_id: string | null }[];
+ const ids = jobs.filter((j) => j.status === "queued" && !j.external_id).map((j) => j.id);
+ if (!ids.includes(id)) ids.push(id);
+ let asked = 1;
+ try {
+ asked = Math.max(1, Number((JSON.parse(row.request_json) as { params?: { numOutputs?: unknown } }).params?.numOutputs) || 1);
+ } catch {}
+ // Each job made its share of the outputs asked for.
+ const outputs = Math.min(asked, ids.length * Math.ceil(asked / Math.max(1, jobs.length)));
+ return { ids, ...(outputs !== asked && { outputs }) };
}
+/** The request with the outputs of the runs it takes the place of (their count, not the whole batch's again). */
+const withReplacedOutputs = <R extends { params?: { numOutputs?: number } }>(req: R, r: Replaced | undefined): R =>
+ r?.outputs ? { ...req, params: { ...req.params, numOutputs: r.outputs } } : req;
+
/** What the sign-in proxy passes on of a request body (next.config.ts proxyClientMaxBodySize). */
const PROXY_BODY_BYTES = 4 * 1024 * 1024;
const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first (POST /api/uploads), then send their /api/files/ paths.";
@@ -152,12 +194,17 @@ export async function POST(request: Request) {
return refuse(r.status, r.body.error, r.body, r.headers);
};
const notes: string[] = [];
- const replaces = account && !preview ? replacedRun(body, account.id) : undefined;
+ const replacing = account && !preview ? replacedRun(body, account.id) : undefined;
+ // A run that started or stopped meanwhile (another tile's press took it already): nothing new runs.
+ if (replacing === null) return refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });
+ let replaces = replacing;
+ // It makes the outputs of the jobs it stops, not its whole batch's again.
+ req = withReplacedOutputs(req, replaces);
if (account && !preview) {
// Room on the server, room in the account's files, and a fair share of runs.
if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);
if (accountUsage(account.id).total >= accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));
- if (activeRuns(account.id, replaces) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
+ if (activeRuns(account.id, replaces?.ids) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });
if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {
@@ -209,7 +256,7 @@ export async function POST(request: Request) {
if (account && onPool && billingConfigured()) {
// The billing service's limits for runs on this install's GPUs (never above the studio's own).
const lim = onPool.policy.limits;
- if (lim.activeRuns > 0 && activeRuns(account.id, replaces) >= lim.activeRuns) {
+ if (lim.activeRuns > 0 && activeRuns(account.id, replaces?.ids) >= lim.activeRuns) {
unhit(`run:${account.id}`);
return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
}
@@ -287,10 +334,24 @@ export async function POST(request: Request) {
stamp = held.stamp;
} else if (mod.checkOutputs) stamp = { checkOutputs: true };
}
+ // The run this one takes the place of, asked again with nothing awaited from here until it stops: a press on another
+ // of its batch's tiles meanwhile took it already (or it started on its GPU), so nothing new runs.
+ if (replaces && account) {
+ const now = replacedRun(body, account.id);
+ if (!now) {
+ unhit(`run:${account.id}`);
+ if (stamp?.hold) queueRelease(stamp.hold);
+ return refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });
+ }
+ // Fewer of its jobs left to stop (one was handed over meanwhile): fewer outputs. A run on this install's GPUs keeps
+ // the count it was priced and set aside for.
+ if (!onPool && now.outputs !== undefined && now.outputs !== replaces.outputs) req = { ...req, params: { ...req.params, numOutputs: Math.min(now.outputs, req.params?.numOutputs ?? now.outputs) } };
+ replaces = now;
+ }
// Counted again just before the run is stored, with nothing awaited in between: requests that arrived together all
// passed the first count while the checks above waited.
- const waitingFull = !onPool && goesTo === "comfyui" && waitingRuns(account?.id ?? "", replaces) >= ACCOUNT_LIMITS.waitingRuns;
- if (account && (activeRuns(account.id, replaces) >= ACCOUNT_LIMITS.activeRuns || waitingFull)) {
+ const waitingFull = !onPool && goesTo === "comfyui" && waitingRuns(account?.id ?? "", replaces?.ids) >= ACCOUNT_LIMITS.waitingRuns;
+ if (account && (activeRuns(account.id, replaces?.ids) >= ACCOUNT_LIMITS.activeRuns || waitingFull)) {
unhit(`run:${account.id}`);
if (stamp?.hold) queueRelease(stamp.hold);
return refuse(429, waitingFull ? ACCOUNT_MESSAGES.waitingRuns : ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
@@ -304,8 +365,9 @@ export async function POST(request: Request) {
if (stamp?.hold) queueRelease(stamp.hold);
throw e;
}
- // The run this one takes the place of stops now (it was waiting, or it failed): never two of the same.
- if (replaces) await cancelGeneration(replaces);
+ // The runs this one takes the place of stop now (they were waiting, or it failed): never two of the same. Each is
+ // marked stopped as it is called (a job not handed over yet awaits nothing first), before another request is read.
+ if (replaces) await Promise.all(replaces.ids.map((id) => cancelGeneration(id)));
// A script's open-source run while ComfyUI is on the owner's computer: it waits for the owner's Fuobe tab there.
if (viewer.kind === "owner" && token && getSetting("comfyWhere") === "computer" && items.some((g) => g.provider === "comfyui")) notes.push(RUNS_ON_COMPUTER_NOTE);
// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index 4c536c1d..82a301d1 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -46,7 +46,7 @@ export const ACCOUNT_LIMITS = {
diskFreeBytes: 20 * GB,
/** Runs: at once (queued or running), per hour, and outputs per run. */
activeRuns: 4,
- /** Runs waiting for the account's own GPU or key to come back (they use neither meanwhile): counted apart. */
+ /** Runs waiting for the account's own GPU to come back (they use nothing meanwhile): counted apart. A run waiting on a key counts among the runs at once. */
waitingRuns: 4,
runsPerHour: 60,
outputsPerRun: 4,
diff --git a/src/server/generations.ts b/src/server/generations.ts
index f79079f4..95241177 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -305,6 +305,11 @@ interface HealState {
/** The words of the last try (the run fails in them when the wait is over), and what helps meanwhile. */
words?: string;
trouble?: RunTrouble;
+ /**
+ * When a try began sending the job itself (markSending): an instance that takes the wait over later (this one cut off
+ * in the middle of that send) doesn't send it again. Cleared when the try fails and the run waits again (markWaiting).
+ */
+ sending?: number;
}
const readMeta = (json: string | null | undefined): PendingMeta & Record<string, unknown> => {
@@ -2008,6 +2013,9 @@ async function submitNow(
// instead of sending files to an address that answers nothing.
const known = link && !resume ? cachedGpuState(account!, link.url) : undefined;
for (;;) {
+ // A try again (its wait kept with the run) while this server stops: nothing more is sent from here, and the run
+ // is left as it is, for the next instance to go on with.
+ if ((heal.tries > 0 || resume) && draining()) return;
let error: unknown;
if (heal.tries === 0 && !resume && known && !known.online && known.trouble?.retryable) error = troubleError(known.trouble);
else if (link && (heal.tries > 0 || lookFirst)) {
@@ -2023,6 +2031,8 @@ async function submitNow(
if (account && heal.tries > 0) recordOwnRun({ run: id, account, ...facts({ attempt: heal.tries, waitedMs: Date.now() - heal.since }), hostKind: hostKindOf(gpu), outcome: "healed" });
return;
} catch (e) {
+ // Another instance holds the run now, or this server is stopping: left as it is, for the instance that goes on.
+ if (e instanceof LetGo) return;
error = e;
// A voice the provider cloned for this run (a billed step) is kept for the next try.
const voice = (e as { voiceEmbedding?: unknown } | null)?.voiceEmbedding;
@@ -2078,9 +2088,43 @@ async function submitNow(
}
} finally {
submitting().delete(id);
+ // This server is stopping: a run still waiting here is let go of now, so the next instance takes it at its next
+ // look instead of after the hold runs out.
+ if (draining()) letGo(id);
}
}
+/** handOver stopped before the send: another instance holds the run, or this server is stopping while the run waited. */
+class LetGo extends Error {}
+
+/** Give up this instance's hold on a run still waiting for its hand-over (another instance may take it at once). */
+function letGo(id: string): void {
+ db()
+ .prepare(
+ `UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.lease')
+ WHERE id = @id AND ${PENDING} AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.lease.by') = @me`,
+ )
+ .run({ id, me: instance() });
+}
+
+/**
+ * Just before a run's job is sent. A run that waited (its `heal` kept with it) is marked as being sent: an instance that
+ * takes the wait over later (this one cut off in the middle of the send, by a restart or a deploy) then doesn't send it
+ * a second time. Throws LetGo when another instance holds the run, or when this server is stopping and the run waited
+ * (the next instance goes on with its wait, and sends it).
+ */
+function markSending(id: string): void {
+ const r = db().prepare(`SELECT external_meta_json FROM generations WHERE id = ? AND ${PENDING}`).get(id) as Pick<Row, "external_meta_json"> | undefined;
+ if (!r) throw new Error("Stopped");
+ if (heldElsewhere(r.external_meta_json)) throw new LetGo("Held by another instance");
+ // A first try (nothing waited): a send cut off here fails at the next instance's look (sweepInterrupted).
+ if (!readMeta(r.external_meta_json).heal) return;
+ if (draining()) throw new LetGo("Stopping");
+ db()
+ .prepare(`UPDATE generations SET external_meta_json = json_set(external_meta_json, '$.heal.sending', @now) WHERE id = @id AND ${PENDING} AND json_type(external_meta_json, '$.heal') = 'object'`)
+ .run({ id, now: Date.now() });
+}
+
/** Self-healing's clock: tests make it faster (0.001: a 30-minute wait takes 1.8 s). */
export const SELF_HEAL = { scale: 1 };
@@ -2094,6 +2138,8 @@ function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: numb
heal.next = next;
heal.words = trouble.words;
heal.trouble = troubleOf(trouble);
+ // The try that was sending failed: the next one may send.
+ delete heal.sending;
return (
db()
.prepare(
@@ -2336,6 +2382,8 @@ const FINAL_AT_POLL: ReadonlySet<string> = new Set(["key-rejected", "key-balance
/** 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 };
+/** The growing wait between an account's polls that keep failing. */
+const POLL_BACKOFF = { budgetMs: 0, firstMs: 5_000, maxMs: 60_000 };
/** Polls that fail in a row before the tile says it is waiting. */
const POLL_MISSES_SAID = 3;
/** How long a made result's copy is tried again (a GPU or provider that dropped the connection for a while). */
@@ -2406,7 +2454,12 @@ async function healPoll(r: Row, ctx: PollContext, account: string, pollError: un
const now = Date.now();
const h = pollHeals().get(r.id) ?? { first: now, n: 0, next: 0 };
h.n++;
- h.next = now + backoffMs(h.n, { budgetMs: 0, firstMs: 5_000, maxMs: 60_000 }, d.retryAfterMs) * SELF_HEAL.scale;
+ // What the other side asked for (Retry-After) is kept to, up to twice the longest wait: a run's own clocks (its GPU's
+ // budget below, a run's time in pollOne) are read at each poll, so a day-long Retry-After can't hold the run.
+ const ask = Math.min(backoffMs(h.n, POLL_BACKOFF, d.retryAfterMs), POLL_BACKOFF.maxMs * 2) * SELF_HEAL.scale;
+ // A run on its own GPU asks once more when its budget ends, whatever the wait said.
+ const budgetLeft = r.provider === "comfyui" ? Math.max(0, h.first + POLL_HEAL_MS.comfyui * SELF_HEAL.scale - now) : Infinity;
+ h.next = now + Math.min(ask, budgetLeft);
pollHeals().set(r.id, h);
if (h.n === 1) ownEvent(r.id, account, pollError, d, factsOf(r, { stage: "poll", attempt: 1 }), "waiting");
if (r.provider === "comfyui" && now - h.first >= POLL_HEAL_MS.comfyui * SELF_HEAL.scale) {
@@ -2782,6 +2835,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, p
if (cloned && route.map?.cloneFirst && !input.voiceEmbedding) input.voiceEmbedding = cloned;
// Nothing is sent once the run stopped being this one's to send (cancelled, failed, or taken by another instance).
if (!going()) throw new Error("Stopped");
+ markSending(id);
const res = await adapter.submit({ generationId: id, model: plan.model, route, input });
// A saved voice the cloud just cloned keeps the embedding (the owner's runs only), so its next line skips the clone.
if (typeof res.meta?.voiceEmbedding === "string" && !req.account) void keepVoiceEmbedding(req.inputs?.voiceAudio, res.meta.voiceEmbedding).catch(() => {});
@@ -2913,8 +2967,8 @@ function startRunner(): void {
function sweepInterrupted(): void {
const now = Date.now();
const rows = db()
- .prepare("SELECT id, request_json, external_meta_json FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")
- .all(now - STALE_SUBMIT.ms) as Pick<Row, "id" | "request_json" | "external_meta_json">[];
+ .prepare("SELECT id, provider, request_json, external_meta_json FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")
+ .all(now - STALE_SUBMIT.ms) as Pick<Row, "id" | "provider" | "request_json" | "external_meta_json">[];
const busy = submitting();
for (const r of rows) {
if (busy.has(r.id)) continue;
@@ -2922,15 +2976,22 @@ function sweepInterrupted(): void {
// An instance that is alive holds it (this one's renewals included).
if (meta.lease && typeof meta.lease.until === "number" && meta.lease.until > now) continue;
if (meta.heal && takeOver(r, meta.heal)) continue;
- updateIfGoing(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null }, " AND external_id IS NULL");
+ // A run that waited and was cut off in the middle of its send may have reached its GPU or provider: never sent twice.
+ const words = meta.heal && typeof meta.heal.sending === "number" ? CUT_OFF_SENDING : "This run stopped before it started. Press Retry.";
+ updateIfGoing(r.id, { status: "failed", error: words, completed_at: Date.now(), message: null }, " AND external_id IS NULL");
}
}
+/** A waiting run whose instance was cut off while it sent the job (its GPU or provider may have it): not sent again. */
+const CUT_OFF_SENDING = "This run was interrupted while it was being sent. Press Retry.";
+
/**
* A waiting run no instance holds any more: taken by this one, planned again as its account runs now (its GPU, its keys),
- * and its wait goes on where it was (its budget and its tries kept). False: it isn't one this can take.
+ * and its wait goes on where it was (its budget and its tries kept). False: it isn't one this can take (one cut off in
+ * the middle of its send among them: it fails, rather than being sent twice).
*/
-function takeOver(r: Pick<Row, "id" | "request_json">, h: HealState): boolean {
+function takeOver(r: Pick<Row, "id" | "provider" | "request_json">, h: HealState): boolean {
+ if (typeof h.sending === "number") return false;
let stored: GenerationRequest;
try {
stored = JSON.parse(r.request_json) as GenerationRequest;
@@ -2950,6 +3011,16 @@ function takeOver(r: Pick<Row, "id" | "request_json">, h: HealState): boolean {
updateIfGoing(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL");
return true;
}
+ // Planned for another provider now (its GPU disconnected, another key): its polls would ask the provider it was made
+ // for, so it stops, as a run whose GPU changed while it waited does.
+ if (p.providerId !== r.provider) {
+ if (r.provider === "comfyui") {
+ const gpu = accountGpu(account);
+ const end = diagnoseGpuJob({ kind: gpu ? "moved" : "disconnected" }, { kind: "link", url: gpuLink(gpu)?.url ?? "" });
+ failRun(r.id, new Error("moved"), end, account, { provider: r.provider, model: p.plan.model.id, op: p.plan.op, stage: "submit" });
+ } else updateIfGoing(r.id, { status: "failed", error: "This run stopped because your keys changed while it waited. Press Retry.", completed_at: Date.now(), message: null }, " AND external_id IS NULL");
+ return true;
+ }
submitting().add(r.id);
void submit(r.id, p.route, p.providerId, p.plan, p.req, typeof h.index === "number" ? h.index : 0, h);
return true;
diff --git a/src/server/run-events.ts b/src/server/run-events.ts
index a9f367e6..f5fbde13 100644
--- a/src/server/run-events.ts
+++ b/src/server/run-events.ts
@@ -42,8 +42,16 @@ export interface OwnRunNote {
said?: string;
}
+/** The most kept of a GPU's or provider's own words: 2 KB (in bytes, as stored). */
const MAX_SAID = 2048;
+/** Text cut to at most `max` bytes in UTF-8, never in the middle of a character. */
+export function capBytes(t: string, max = MAX_SAID): string {
+ if (Buffer.byteLength(t) <= max) return t;
+ // A character cut in two decodes as U+FFFD at the end: left out.
+ return Buffer.from(t).subarray(0, max).toString("utf8").replace(/�+$/u, "");
+}
+
/** A network failure's message as a short code. */
export function networkCode(text: string): string {
if (/ECONNREFUSED|connection refused/i.test(text)) return "refused";
@@ -61,7 +69,7 @@ export function keptText(text: string | undefined, o: { url?: string; secret?: s
let t = withoutSecrets(withoutAddress(String(text), o.url));
if (o.secret && o.secret.length >= 4) t = t.split(o.secret).join("••••");
t = t.replace(/\s+/g, " ").trim();
- return t ? t.slice(0, MAX_SAID) : undefined;
+ return t ? capBytes(t) : undefined;
}
/** One line for the server's log (JSON). Any kind of run event goes through here. */
@@ -79,7 +87,7 @@ export function recordOwnRun(e: OwnRunEvent, said?: string): void {
const place: RunPlace = e.provider === "comfyui" ? "own-gpu" : "own-key";
recordRunEvent("own-run", { run: e.run, account: e.account, place, provider: e.provider, model: e.model, op: e.op, stage: e.stage, code: e.code, hostKind: e.hostKind, cause: e.cause, attempt: e.attempt, waitedMs: e.waitedMs, outcome: e.outcome }, e.outcome === "failed" ? "warn" : "info");
if (e.outcome !== "failed") return;
- const note: OwnRunNote = { at: Date.now(), cause: e.cause, stage: e.stage, code: e.code, hostKind: e.hostKind, ...(said && { said: said.slice(0, MAX_SAID) }) };
+ const note: OwnRunNote = { at: Date.now(), cause: e.cause, stage: e.stage, code: e.code, hostKind: e.hostKind, ...(said && { said: capBytes(said) }) };
try {
db()
.prepare("UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.ownRun', json(?)) WHERE id = ?")
diff --git a/src/server/smaller-copy.ts b/src/server/smaller-copy.ts
index bb18cdca..4399005d 100644
--- a/src/server/smaller-copy.ts
+++ b/src/server/smaller-copy.ts
@@ -6,7 +6,9 @@ import { nanoid } from "nanoid";
import sharp from "sharp";
import type { GenerationRequest } from "@/lib/catalog/types";
import { accountTotalBytes, accountUsage } from "./account-files";
-import { adoptFile, readRef, scratchDir } from "./storage";
+import { exampleStat, isExampleRef } from "./example-files";
+import { absolutePath, adoptFile, contentTypeFor, filesRel, getAsset, guardRef, readRef, scratchDir } from "./storage";
+import { runAsTenant } from "./tenant";
/**
* "Send a smaller copy": a run whose file was too big for the account's GPU address (its tunnel's or its pod's size
@@ -30,12 +32,50 @@ function slots(req: GenerationRequest): Slot[] {
export class SmallerCopyError extends Error {}
+/** Copies are being made already (the account's own, or as many as the server makes at once): try again in a moment. */
+export class SmallerCopyBusy extends SmallerCopyError {}
+
+/**
+ * How many copies the server makes at once (each account one at a time), and how many cores a clip's encode may use: a
+ * copy is real work (a clip is encoded again), and the server is shared.
+ */
+export const SMALLER_COPY_LIMITS = { atOnce: 2, threads: 2 };
+
+declare global {
+ /** The smaller copies being made now: by account, and in all. */
+ var __fuobeSmallerCopies: { total: number; accounts: Set<string> } | undefined;
+}
+const making = () => (globalThis.__fuobeSmallerCopies ??= { total: 0, accounts: new Set<string>() });
+
+/** A stored input's size and type, read from the disk without reading the file. Null: not a file stored here. */
+function storedSize(ref: string): { bytes: number; contentType: string } | null {
+ try {
+ if (ref.startsWith("/api/files/")) {
+ const rel = filesRel(ref);
+ if (rel === null) return null;
+ const abs = absolutePath(rel);
+ return { bytes: fs.statSync(abs).size, contentType: contentTypeFor(abs) };
+ }
+ if (isExampleRef(ref)) {
+ const st = exampleStat(ref);
+ return st ? { bytes: st.bytes, contentType: st.type } : null;
+ }
+ const asset = getAsset(ref);
+ return asset ? { bytes: fs.statSync(absolutePath(asset.relPath)).size, contentType: asset.contentType } : null;
+ } catch {
+ return null;
+ }
+}
+
const CANT = "We couldn't make a smaller copy of this file. Trim the clip, or pick a smaller file.";
+const FILES_FULL = "Your files are full, so a smaller copy can't be kept. Delete a few results, then try again.";
/** A clip re-encoded at 720p at most (ffmpeg), into `out`. */
function shrinkClip(input: string, out: string): Promise<void> {
return new Promise((resolve, reject) => {
- const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", input, "-vf", "scale=-2:'min(720,ih)'", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out];
+ // A few cores at most (decoding, scaling and encoding), so one copy never takes the whole server.
+ const threads = String(SMALLER_COPY_LIMITS.threads);
+ const args = ["-hide_banner", "-loglevel", "error", "-y", "-filter_threads", threads, "-threads", threads, "-i", input, "-vf", "scale=-2:'min(720,ih)'", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-threads", threads, "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out];
let child;
try {
child = spawn(process.env.FFMPEG_PATH || "ffmpeg", args, { stdio: ["ignore", "ignore", "ignore"] });
@@ -57,20 +97,50 @@ function shrinkClip(input: string, out: string): Promise<void> {
/**
* The run's request again with a smaller copy of its biggest file (saved as a new file of the account's), and that copy's
- * size. Throws SmallerCopyError in plain words when no copy can be made (or it isn't smaller).
+ * size. Throws SmallerCopyError in plain words when no copy can be made (or it isn't smaller), SmallerCopyBusy when the
+ * account's last copy is still being made or the server makes as many as it does at once.
*/
export async function withSmallerCopy(accountId: string, req: GenerationRequest): Promise<{ request: GenerationRequest; bytes: number }> {
- const files: { slot: Slot; data: Buffer; contentType: string; name: string }[] = [];
+ const now = making();
+ if (now.accounts.has(accountId)) throw new SmallerCopyBusy("Your last smaller copy is still being made. Try again once it's done.");
+ if (now.total >= SMALLER_COPY_LIMITS.atOnce) throw new SmallerCopyBusy("Smaller copies are busy right now. Try again in a minute.");
+ now.accounts.add(accountId);
+ now.total++;
+ try {
+ return await runAsTenant({ kind: "account", id: accountId }, () => makeSmaller(accountId, req));
+ } finally {
+ now.accounts.delete(accountId);
+ now.total--;
+ }
+}
+
+const isPictureOrClip = (contentType: string) => contentType.startsWith("image/") || contentType.startsWith("video/");
+
+async function makeSmaller(accountId: string, req: GenerationRequest): Promise<{ request: GenerationRequest; bytes: number }> {
+ // The biggest picture or clip, by its size on the disk: only that one is read.
+ const sized: { slot: Slot; bytes: number }[] = [];
for (const slot of slots(req)) {
try {
- const f = await readRef(slot.ref);
- files.push({ slot, data: f.data, contentType: f.contentType, name: f.name });
+ // Only the account's own files (one that is gone, or another's, can't be made smaller here).
+ guardRef(slot.ref);
} catch {
- // A file that is gone: the run can't be made again with it, whatever its size.
+ continue;
}
+ const s = storedSize(slot.ref);
+ if (s && isPictureOrClip(s.contentType)) sized.push({ slot, bytes: s.bytes });
+ }
+ const pick = sized.sort((a, b) => b.bytes - a.bytes)[0];
+ if (!pick) throw new SmallerCopyError(CANT);
+ // Room for the copy (at most four fifths of the file, or it isn't kept) before any work is done.
+ if (accountUsage(accountId).total + Math.ceil(pick.bytes * 0.8) > accountTotalBytes(accountId)) throw new SmallerCopyError(FILES_FULL);
+ let f: { data: Buffer; contentType: string; name: string };
+ try {
+ f = await readRef(pick.slot.ref);
+ } catch {
+ throw new SmallerCopyError(CANT);
}
- const biggest = files.filter((f) => /^(image|video)\//.test(f.contentType)).sort((a, b) => b.data.length - a.data.length)[0];
- if (!biggest) throw new SmallerCopyError(CANT);
+ if (!isPictureOrClip(f.contentType)) throw new SmallerCopyError(CANT);
+ const biggest = { slot: pick.slot, data: f.data, contentType: f.contentType, name: f.name };
const work = path.join(scratchDir(), `smaller-${nanoid(8)}`);
const video = biggest.contentType.startsWith("video/");
const out = `${work}-out.${video ? "mp4" : "jpg"}`;
@@ -85,7 +155,7 @@ export async function withSmallerCopy(accountId: string, req: GenerationRequest)
const bytes = fs.statSync(out).size;
// Only a copy that is clearly smaller helps.
if (!bytes || bytes > biggest.data.length * 0.8) throw new SmallerCopyError("This file is as small as we can make it here. Trim the clip, or pick a smaller file.");
- if (accountUsage(accountId).total + bytes > accountTotalBytes(accountId)) throw new SmallerCopyError("Your files are full, so a smaller copy can't be kept. Delete a few results, then try again.");
+ if (accountUsage(accountId).total + bytes > accountTotalBytes(accountId)) throw new SmallerCopyError(FILES_FULL);
const name = `${biggest.name.replace(/\.[^.]+$/, "") || "file"}-smaller.${video ? "mp4" : "jpg"}`;
const asset = adoptFile({ from: out, contentType: video ? "video/mp4" : "image/jpeg", name, source: "upload", accountId });
const inputs = { ...req.inputs };
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index f0ce0070..3f3c8f2c 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -54,6 +54,11 @@ export interface FakeComfyOptions {
* web page): its status, body, content type and any headers (a redirect's location). Undefined: the request goes on as usual.
*/
answer?: (method: string, path: string) => { status: number; body?: string; contentType?: string; headers?: Record<string, string> } | undefined;
+ /**
+ * True: the request is taken (logged, with the graph a /prompt sent) and never answered, as when the server that sent
+ * it is cut off before the answer comes. Its connection stays open until `dropHeld()` or `close()`.
+ */
+ hold?: (method: string, path: string) => boolean;
}
/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */
@@ -105,6 +110,8 @@ export interface FakeComfy {
url: string;
log: FakeLogEntry[];
opts: FakeComfyOptions;
+ /** Ends every request `hold` kept open (their senders see the connection close). */
+ dropHeld: () => void;
close: () => Promise<void>;
}
@@ -191,6 +198,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
const jobs = new Map<string, number>();
const graphs = new Map<string, Record<string, unknown> | undefined>();
let lastUpload: Buffer | undefined;
+ const held: http.ServerResponse[] = [];
const server = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
@@ -204,6 +212,15 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
res.end(JSON.stringify(value));
};
const p = url.pathname;
+ if (opts.hold?.(entry.method, p)) {
+ if (p === "/prompt") {
+ try {
+ entry.prompt = (JSON.parse(body.toString("utf8")) as { prompt?: Record<string, unknown> }).prompt;
+ } catch {}
+ }
+ held.push(res);
+ return;
+ }
const said = opts.answer?.(entry.method, p);
if (said) {
res.writeHead(said.status, { "content-type": said.contentType ?? "text/html", ...said.headers });
@@ -335,6 +352,9 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
url: `http://127.0.0.1:${at}`,
log,
opts,
+ dropHeld: () => {
+ for (const r of held.splice(0)) r.destroy();
+ },
close: () =>
new Promise<void>((done) => {
server.closeAllConnections?.();
diff --git a/tests/own-gpu-graceful.test.ts b/tests/own-gpu-graceful.test.ts
index b3f98234..985a483c 100644
--- a/tests/own-gpu-graceful.test.ts
+++ b/tests/own-gpu-graceful.test.ts
@@ -64,7 +64,7 @@ afterAll(async () => {
beforeEach(() => {
resetRates();
SELF_HEAL.scale = 0.001;
- Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined });
+ Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined, hold: undefined });
fake.log.length = 0;
auth.setAccountGpu(a, { url: fake.url });
globalThis.__fuobeTestGpuHosts = undefined;
@@ -360,6 +360,20 @@ describe("a run on an account's own GPU heals itself, or fails in plain words wi
expect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu"]));
});
+ it("a GPU that asks to be asked again tomorrow (Retry-After) still stops within the run's own budget", async () => {
+ fake.opts.delayMs = 60_000;
+ const id = await startRun();
+ for (let i = 0; i < 300 && !db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(id); i++) await new Promise((r) => setTimeout(r, 10));
+ // Its address now answers every look with "too many requests, ask again in a day".
+ fake.opts.answer = () => ({ status: 429, body: "slow down", contentType: "text/plain", headers: { "retry-after": "86400" } });
+ const started = Date.now();
+ const g = await settle(id, 10_000);
+ expect(g?.status).toBe("failed");
+ // 15 minutes at this test's clock (1.8 s here at most), never the day it asked for.
+ expect(Date.now() - started).toBeLessThan(8_000);
+ plainWords(g?.error);
+ });
+
it("a made result whose copy breaks off is copied again at a later look, the tile saying so, and never made twice", async () => {
let refused = 0;
fake.opts.answer = (_m, p) => (p === "/view" && refused++ < 4 ? html(502) : undefined);
@@ -505,6 +519,18 @@ describe("the reported case, end to end: a RunPod pod that is stopped (its addre
});
describe("what the owner learns of an account's failed run on its own GPU", () => {
+ it("keeps at most 2 KB of what the GPU said, counted in bytes, never cutting a character in two", async () => {
+ const { keptText } = await import("@/server/run-events");
+ const wide = "é".repeat(3000);
+ const kept = keptText(wide)!;
+ expect(Buffer.byteLength(kept)).toBeLessThanOrEqual(2048);
+ expect(kept).toBe("é".repeat(1024));
+ const emoji = "a" + "😀".repeat(1000);
+ expect(Buffer.byteLength(keptText(emoji)!)).toBeLessThanOrEqual(2048);
+ expect(keptText(emoji)).not.toMatch(/�/u);
+ expect(keptText("short")).toBe("short");
+ });
+
it("one log line and a note kept with the run (no address, no token), never in the account's own answers", async () => {
const warn = vi.spyOn(console, "warn");
try {
@@ -595,6 +621,33 @@ describe("runs that wait, and a file too big for the address", () => {
for (const g of ((await instead.json()) as { items: { id: string }[] }).items) await cancelGeneration(g.id);
});
+ it("a run that takes the place of one tile of a waiting batch takes the batch's place, once, for the jobs not handed over", async () => {
+ SELF_HEAL.scale = 0.01;
+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);
+ const pic = await uploadPng();
+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] }, params: { numOutputs: 3 } };
+ const first = await generationsRoute.POST(json("/api/generations", "POST", body));
+ expect(first.status, await first.clone().text()).toBe(201);
+ const jobs = ((await first.json()) as { items: { id: string }[] }).items.map((g) => g.id);
+ expect(jobs).toHaveLength(3);
+ for (let i = 0; i < 500 && jobs.some((id) => !getGeneration(id)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));
+ // One of its jobs reached the GPU meanwhile: it goes on there, and isn't made a second time.
+ db().prepare("UPDATE generations SET external_id = 'kept-job', status = 'running', external_meta_json = '{}' WHERE id = ?").run(jobs[2]);
+ const instead = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: jobs[0] }));
+ expect(instead.status, await instead.clone().text()).toBe(201);
+ const made = ((await instead.json()) as { items: { id: string }[] }).items.map((g) => g.id);
+ // The two jobs that hadn't started: two outputs, never the batch's three again.
+ expect(made).toHaveLength(2);
+ expect(getGeneration(jobs[0])?.status).toBe("canceled");
+ expect(getGeneration(jobs[1])?.status).toBe("canceled");
+ expect(getGeneration(jobs[2])?.status).toBe("running");
+ // The same button on the batch's other waiting tile, pressed a moment later: nothing new runs.
+ const again = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: jobs[1] }));
+ expect(again.status).toBe(409);
+ expect(((await again.json()) as { error: string }).error).toBe("This run has already started or stopped, so nothing new was run.");
+ for (const id of [...jobs, ...made]) await cancelGeneration(id);
+ });
+
it("a file the address refuses as too big: Send a smaller copy makes one, and the run made again with it runs", async () => {
// A big picture (noise: it doesn't shrink as a PNG).
const sharp = (await import("sharp")).default;
@@ -629,6 +682,31 @@ describe("runs that wait, and a file too big for the address", () => {
const sentBytes = fake.log.filter((e) => e.path === "/upload/image").at(-1)?.upload?.length ?? 0;
expect(sentBytes).toBeGreaterThan(0);
expect(sentBytes).toBeLessThan(big.length * 0.8);
+
+ // A copy is real work: one at a time for an account, a few at once on the server, a few an hour for a run.
+ const ask = async () => {
+ const r = await smallerRoute.POST(new Request(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: headers() }), { params: Promise.resolve({ id }) });
+ return { status: r.status, error: ((await r.json()) as { error?: string }).error };
+ };
+ globalThis.__fuobeSmallerCopies = { total: 1, accounts: new Set([a]) };
+ expect(await ask()).toEqual({ status: 429, error: "Your last smaller copy is still being made. Try again once it's done." });
+ globalThis.__fuobeSmallerCopies = { total: 2, accounts: new Set(["someone-else", "another"]) };
+ expect(await ask()).toEqual({ status: 429, error: "Smaller copies are busy right now. Try again in a minute." });
+ globalThis.__fuobeSmallerCopies = undefined;
+ // Files that are full say so before any copy is made.
+ const { ACCOUNT_LIMITS } = await import("@/server/account-files");
+ const limits = ACCOUNT_LIMITS as { newAccountBytes: number };
+ const was = limits.newAccountBytes;
+ limits.newAccountBytes = 1;
+ try {
+ expect(await ask()).toEqual({ status: 422, error: "Your files are full, so a smaller copy can't be kept. Delete a few results, then try again." });
+ } finally {
+ limits.newAccountBytes = was;
+ }
+ // Three for this run this hour (the busy answers aren't counted, the full one is), then none.
+ expect((await ask()).status).toBe(200);
+ expect((await ask()).status).toBe(429);
+ expect((await ask()).error).toMatch(/^You've made a few smaller copies already\. Try again in \d+ minutes?\.$/);
});
});
@@ -655,6 +733,31 @@ describe("a wait survives a restart or a deploy", () => {
}
});
+ it("a waiting run another instance takes over is never sent to a provider other than the one it was made for", async () => {
+ SELF_HEAL.scale = 0.01;
+ STALE_SUBMIT.ms = 0;
+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);
+ const shut = (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });
+ try {
+ const id = await startRun();
+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));
+ // This instance stops waiting on it (as when it stops), and the run's row says another provider made it.
+ shut.draining = true;
+ for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await new Promise((r) => setTimeout(r, 10));
+ shut.draining = false;
+ db().prepare("UPDATE generations SET provider = 'fal' WHERE id = ?").run(id);
+ fake.opts.answer = undefined;
+ fake.log.length = 0;
+ const g = await settle(id, 5_000);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe("This run stopped because your keys changed while it waited. Press Retry.");
+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);
+ } finally {
+ shut.draining = false;
+ STALE_SUBMIT.ms = 2 * 60_000;
+ }
+ });
+
it("a deploy's old instance hands its waiting run to the new one, which goes on with it and runs it once", async () => {
SELF_HEAL.scale = 0.01;
LEASE.ms = 400;
@@ -669,6 +772,10 @@ describe("a wait survives a restart or a deploy", () => {
for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await new Promise((r) => setTimeout(r, 10));
expect(globalThis.__fuobeSubmitting?.has(id)).toBe(false);
expect(getGeneration(id)?.status).toBe("queued");
+ // It let go of its hold at once (the new instance needn't wait for it to run out), and kept the wait.
+ const kept = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { lease?: unknown; heal?: unknown };
+ expect(kept.lease).toBeUndefined();
+ expect(kept.heal).toBeTruthy();
// It is gone: its timers, its runs in hand, its name. A new instance starts on the same database.
const old = globalThis.__fuobeRunner;
if (old) {
@@ -697,4 +804,61 @@ describe("a wait survives a restart or a deploy", () => {
expect(g?.error ?? "").not.toMatch(/stopped before it started/);
expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
});
+
+ it("an instance cut off while it sends a run that waited: the next one never sends it a second time", async () => {
+ // The module the runner runs now (the test above started another instance of it): its knobs and the first one's.
+ const now = await import("@/server/generations");
+ for (const m of [{ SELF_HEAL, LEASE, STALE_SUBMIT }, now]) {
+ m.SELF_HEAL.scale = 0.01;
+ m.LEASE.ms = 400;
+ m.LEASE.renewMs = 100;
+ m.STALE_SUBMIT.ms = 0;
+ }
+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);
+ const id = await startRun();
+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));
+ expect(getGeneration(id)?.waiting).toBeTruthy();
+ // The GPU is back: the run's next try sends its job, and the GPU takes it; the answer never comes back to this
+ // instance, which is cut off (a restart, a deploy's old instance) before it can note the job.
+ fake.log.length = 0;
+ fake.opts.hold = (m, p) => m === "POST" && p === "/prompt";
+ fake.opts.answer = undefined;
+ for (let i = 0; i < 1000 && !fake.log.some((e) => e.path === "/prompt"); i++) await new Promise((r) => setTimeout(r, 10));
+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
+ const meta = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { heal?: { sending?: number } };
+ expect(typeof meta.heal?.sending).toBe("number");
+ const old = globalThis.__fuobeRunner;
+ if (old) {
+ clearInterval(old.timer);
+ if (old.fastTimer) clearInterval(old.fastTimer);
+ }
+ globalThis.__fuobeRunner = undefined;
+ if (globalThis.__fuobeLeaseTimer) clearTimeout(globalThis.__fuobeLeaseTimer);
+ globalThis.__fuobeLeaseTimer = undefined;
+ globalThis.__fuobeSubmitting = new Set();
+ globalThis.__fuobeInstance = undefined;
+ vi.resetModules();
+ const next = await import("@/server/generations");
+ next.SELF_HEAL.scale = 0.01;
+ next.STALE_SUBMIT.ms = 0;
+ next.LEASE.ms = 400;
+ try {
+ // The cut-off instance's hold runs out; the next instance looks.
+ await new Promise((r) => setTimeout(r, 500));
+ next.ensureRunner();
+ const g = await settle(id, 10_000);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");
+ // Exactly one job across both instances, also once the first instance's send ends.
+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
+ fake.dropHeld();
+ await new Promise((r) => setTimeout(r, 200));
+ await settle(id, 1_000);
+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
+ expect(getGeneration(id)?.status).toBe("failed");
+ } finally {
+ fake.opts.hold = undefined;
+ fake.dropHeld();
+ }
+ });
});
diff --git a/tests/own-keys-graceful.test.ts b/tests/own-keys-graceful.test.ts
index 7fea1566..cbfc7bb2 100644
--- a/tests/own-keys-graceful.test.ts
+++ b/tests/own-keys-graceful.test.ts
@@ -196,6 +196,17 @@ describe("an account's run on its own key waits out a busy or down provider", ()
expect(JSON.parse(tts[1].body)).toMatchObject({ speaker_voice_embedding_file_url: expect.stringMatching(/voice-fal-\d+\.safetensors$/) });
});
+ it("runs waiting while fal.ai is busy count among the runs at once: a provider that is down gathers no more", async () => {
+ gens.SELF_HEAL.scale = 0.1;
+ fal.script = (r) => (isSubmit(r) ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "5" } } : null);
+ const ids: string[] = [];
+ for (let i = 0; i < 4; i++) ids.push((await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" })).id);
+ for (let i = 0; i < 500 && ids.some((id) => !gens.getGeneration(id)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));
+ expect(ids.every((id) => gens.getGeneration(id)?.waiting)).toBe(true);
+ await expect(run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" })).rejects.toThrow(/^429: .*You have 4 runs going/);
+ for (const id of ids) await gens.cancelGeneration(id);
+ });
+
it("a 502 at submit may have started a job already: never sent twice", async () => {
fal.script = (r) => (isSubmit(r) ? { status: 502, body: "<!DOCTYPE html><html><head><title>502 Bad gateway</title></head></html>" } : null);
const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });