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 step of a longer run stays with its run

Adarsh51fdfdadfa9c
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 0e8e787a..47f34cf9 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -19,7 +19,7 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, disk
import { accountInputProblem } from "@/server/account-inputs";
import { db } from "@/server/db";
import { findView, requestViewKey } from "@/server/any-angle";
-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";
+import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, CHAINED_RUN, createGenerations, getGeneration, inChain, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { hit, unhit } from "@/server/rate";
import { GenerationRequestSchema } from "@/server/request-schema";
@@ -88,22 +88,27 @@ interface Replaced {
/** 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.";
+/** A `replaces` for a waiting step of a longer run: moving it alone would cancel it and leave the rest of the run without it. */
+const CHAINED = "chained";
+
/**
* 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). 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).
+ * `replaces`; null: one that can't be taken over any more (asked again just before the run is made, nothing awaited);
+ * CHAINED: a waiting step of a longer run (it waits for an earlier step, or a later one waits for it), never moved alone.
*/
-function replacedRun(body: unknown, accountId: string): Replaced | null | undefined {
+function replacedRun(body: unknown, accountId: string): Replaced | typeof CHAINED | null | undefined {
const id = (body as { replaces?: unknown } | null)?.replaces;
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;
+ .prepare("SELECT status, external_id, batch_id, request_json, depends_on 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; depends_on: string | null } | undefined;
if (!row) return null;
if (row.status === "failed") return { ids: [id] };
if (row.status !== "queued" || row.external_id) return null;
+ if (inChain({ id, depends_on: row.depends_on })) return CHAINED;
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()
@@ -111,6 +116,8 @@ function replacedRun(body: unknown, accountId: string): Replaced | null | undefi
.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);
+ // A job of the batch that a later step waits for: the batch is part of a longer run too.
+ if (ids.some((j) => j !== id && inChain(j))) return CHAINED;
let asked = 1;
try {
asked = Math.max(1, Number((JSON.parse(row.request_json) as { params?: { numOutputs?: unknown } }).params?.numOutputs) || 1);
@@ -197,6 +204,8 @@ export async function POST(request: Request) {
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" });
+ // A waiting step of a longer run: it goes on as it is (moved alone, the rest of the run would go without it).
+ if (replacing === CHAINED) return refuse(409, CHAINED_RUN, { code: "chained-run" });
let replaces = replacing;
// It makes the outputs of the jobs it stops, not its whole batch's again.
req = withReplacedOutputs(req, replaces);
@@ -338,10 +347,10 @@ export async function POST(request: Request) {
// 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) {
+ if (!now || now === CHAINED) {
unhit(`run:${account.id}`);
if (stamp?.hold) queueRelease(stamp.hold);
- return refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });
+ return now === CHAINED ? refuse(409, CHAINED_RUN, { code: "chained-run" }) : 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.
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 95241177..378816bf 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -230,9 +230,10 @@ export function toGeneration(r: Row): Generation {
...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),
...(r.status === "failed" && r.fix_json && parseTrouble(r.fix_json)),
// Waiting for its own GPU or key to come back: why, the buttons that help, and until when (never the owner's note).
- ...(r.status === "queued" && !r.external_id && r.external_meta_json && waitingOf(r.external_meta_json)),
- // Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed.
- ...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),
+ ...(r.status === "queued" && !r.external_id && r.external_meta_json && waitingOf(r)),
+ // Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed. Not
+ // said of a run whose send was under way when it stopped: the provider may have the job.
+ ...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && !maybeSent(r) && { notBilled: true as const }),
// On this install's GPUs (hosted runs): what it cost, or that it cost nothing.
...(stored.place === "pool" && { place: "pool" as const }),
...(stored.charge && r.status === "succeeded" && { charge: stored.charge }),
@@ -269,12 +270,37 @@ function parseTrouble(json: string): { trouble: RunTrouble } | Record<string, ne
}
}
-/** A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. */
-function waitingOf(json: string): { waiting: RunTrouble & { until?: number } } | Record<string, never> {
- const h = readMeta(json).heal;
- return h?.trouble && typeof h.trouble.cause === "string" && Array.isArray(h.trouble.actions) ? { waiting: { ...h.trouble, ...(h.deadline && { until: h.deadline }) } } : {};
+/**
+ * A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. A step of a longer run never offers
+ * Run with your key (moving it alone would leave the rest of the run without it), also when its wait was kept before.
+ */
+function waitingOf(r: Pick<Row, "id" | "depends_on" | "external_meta_json">): { waiting: RunTrouble & { until?: number } } | Record<string, never> {
+ const h = readMeta(r.external_meta_json).heal;
+ if (!h?.trouble || typeof h.trouble.cause !== "string" || !Array.isArray(h.trouble.actions)) return {};
+ const t = h.trouble.actions.some((a) => a.kind === "run-with-key") && inChain(r) ? withoutKeyOffer(h.trouble) : h.trouble;
+ return { waiting: { ...t, ...(h.deadline && { until: h.deadline }) } };
}
+/** A run whose job was being sent when it stopped (a server cut off in the middle of the send): its provider may have it. */
+const maybeSent = (r: Pick<Row, "error" | "external_meta_json">): boolean => r.error === CUT_OFF_SENDING || typeof readMeta(r.external_meta_json).heal?.sending === "number";
+
+/**
+ * A run that is one step of a longer one: it waits for an earlier step, or a later step (queued or running) waits for it.
+ * Run with your key can't move such a step alone (the route answers 409 CHAINED_RUN, and its tile doesn't offer it).
+ */
+export function inChain(r: string | Pick<Row, "id" | "depends_on">): boolean {
+ const id = typeof r === "string" ? r : r.id;
+ const dependsOn = typeof r === "string" ? (db().prepare("SELECT depends_on FROM generations WHERE id = ?").pluck().get(id) as string | null | undefined) : r.depends_on;
+ if (dependsOn) return true;
+ return !!db().prepare(`SELECT 1 FROM generations WHERE status IN ('queued', 'running') AND ${DEPENDENTS_OF} LIMIT 1`).get({ id, quoted: JSON.stringify(id) });
+}
+
+/** What a step of a longer run that can't move to a key alone says (POST /api/generations with `replaces` on it). */
+export const CHAINED_RUN = "This step is part of a longer run, so it can't move to your key on its own. It goes on by itself, or cancel it and run the tool again with your key.";
+
+/** A trouble's buttons without Run with your key (a step of a longer run). */
+const withoutKeyOffer = <T extends { actions: TroubleAction[] }>(t: T): T => ({ ...t, actions: t.actions.filter((a) => a.kind !== "run-with-key") });
+
/**
* What a run keeps in external_meta_json before its provider has it (external_id NULL): which instance is handing it
* over or waiting on it (`lease`, renewed while it does), and, while it waits for its own GPU or key, how the wait goes
@@ -1602,8 +1628,10 @@ async function advanceDependents(): Promise<void> {
(id) => db().prepare("SELECT status, provider, outputs_json, request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json" | "request_json"> | undefined,
);
const earlier = stored.frame ? "The previous frame" : "An earlier step";
- const fail = (error: string) => {
+ const fail = (error: string, cause = "earlier-step") => {
update(r.id, { status: "failed", error, message: null, completed_at: Date.now() });
+ // An account's own step: the owner's log line and note, as for any of its runs.
+ ownFailed(r.id, ownAccountOf(stored), factsOf(r, { stage: "chain" }), cause);
// Steps waiting only to feed this one (the other lanes of a per-frame render) are dropped before they are paid for.
dropUnused(allIds);
};
@@ -1630,6 +1658,13 @@ async function advanceDependents(): Promise<void> {
}
// Another instance (a deploy's other one) launching this step already: left to it.
if (!claim(r.id)) continue;
+ // A step that waited for its own GPU or key, taken over after a restart or a deploy (its wait is kept with it, as a
+ // run's is: takeOver). One cut off in the middle of its send may have reached its GPU or provider: never sent twice.
+ const heal = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null).heal;
+ if (heal && typeof heal.sending === "number") {
+ fail(CUT_OFF_SENDING, "interrupted-sending");
+ continue;
+ }
submitting().add(r.id);
let handedOff = false;
// An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI and its own
@@ -1686,6 +1721,8 @@ async function advanceDependents(): Promise<void> {
const mode = chainMode(prepared, deps as Pick<Row, "provider">[], original);
if (mode.error) throw new Error(mode.error);
const p = mode.forceDemo ? { ...prepared, demo: true, providerId: "mock" as const, cost: 0 } : prepared;
+ // Its wait goes on with what is left of it (its tries and its time), where it still goes; its tile keeps its words.
+ const resume = heal && !mode.forceDemo && p.providerId === r.provider ? heal : undefined;
update(r.id, {
...(moved.note && { model_id: p.plan.model.id, engine: p.plan.model.engine }),
provider: p.providerId,
@@ -1694,13 +1731,13 @@ async function advanceDependents(): Promise<void> {
prompt: p.plan.prompt,
cost_usd: p.cost,
request_json: JSON.stringify(original),
- message: mode.forceDemo ? "Demo — an earlier step ran as a demo" : p.demo ? "Demo mode — no provider connected" : "Submitting",
+ ...(!resume && { message: mode.forceDemo ? "Demo — an earlier step ran as a demo" : p.demo ? "Demo mode — no provider connected" : "Submitting" }),
});
// In the background: an upload must not hold up the runner's other polls.
handedOff = true;
- void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);
+ void submit(r.id, p.route, p.providerId, p.plan, p.req, 0, resume);
} catch (e) {
- fail((e as Error).message);
+ fail((e as Error).message, e instanceof AccountRunError ? e.refusal.code : "chain");
} finally {
if (!handedOff) submitting().delete(r.id);
}
@@ -1946,7 +1983,9 @@ function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: Ret
}
const own = accountRun(req.account, providerId, "submit");
if ("error" in own) {
- updateIfGoing(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ if (updateIfGoing(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null })) {
+ ownFailed(id, req.account, { provider: providerId, model: plan.model.id, op: plan.op, stage: "submit" }, own.code);
+ }
// A chained step advanceDependents marked as being handed over isn't any more.
submitting().delete(id);
return Promise.resolve();
@@ -2055,8 +2094,10 @@ async function submitNow(
if (now + wait <= heal.deadline) {
if (link) noteGpuState(account!, link.url, false, { trouble: asStatus(error, trouble, link) });
// Kept with the run (another instance goes on with it after a restart or a deploy), the tile saying what it
- // waits for and showing what helps.
- if (!markWaiting(id, heal, trouble, now + wait, waitingWords(trouble, isCloudProvider(providerId) ? providerId : undefined, pod))) return;
+ // waits for and showing what helps. A step of a longer run doesn't offer Run with your key: moving it alone
+ // would leave the rest of the run without it.
+ const shown = trouble.actions.some((a) => a.kind === "run-with-key") && inChain(id) ? withoutKeyOffer(trouble) : trouble;
+ if (!markWaiting(id, heal, shown, now + wait, waitingWords(shown, isCloudProvider(providerId) ? providerId : undefined, pod))) return;
if (heal.tries === 1 || heal.firstSeen[trouble.cause] === now) ownEvent(id, account!, error, trouble, facts({ attempt: heal.tries, waitedMs: now - heal.since }), "waiting");
if (!(await pause(id, wait))) return;
// The account changed its GPU meanwhile (a new address or password, this computer, or none): this run goes there.
@@ -2183,6 +2224,33 @@ function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account
return true;
}
+/** An account's own run (its GPU or key), never one on this install's GPUs: its account, else undefined. */
+const ownAccountOf = (req: Pick<GenerationRequest, "account" | "place"> | null | undefined): string | undefined => (req?.account && req.place !== "pool" ? req.account : undefined);
+
+/** ownAccountOf for a stored request (unreadable: none). */
+const ownAccountIn = (requestJson: string): string | undefined => {
+ try {
+ return ownAccountOf(JSON.parse(requestJson) as GenerationRequest);
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * An account's own run that failed in this server's own words (cut off by a restart, refused as its account runs now, an
+ * earlier step that didn't finish): the owner's log line and note, as failRun writes them for a GPU's or key's failure.
+ * `cause` says which. Nothing for the owner's runs or runs on this install's GPUs (`account` undefined).
+ */
+function ownFailed(id: string, account: string | undefined, f: RunFacts, cause: string): void {
+ if (!account) return;
+ try {
+ const hostKind = f.provider === "comfyui" ? hostKindOf(accountGpu(account)) : undefined;
+ recordOwnRun({ run: id, account, ...f, hostKind, cause, outcome: "failed" });
+ } catch {
+ // A log line never stops a run.
+ }
+}
+
/** generations.fix_json: what the GPU was missing (GenerationFix) and, for an account, what its GPU or key ran into. */
const keptFix = (fix: GenerationFix | undefined, trouble: Diagnosis | undefined): string | undefined =>
fix || trouble ? JSON.stringify({ ...(fix ?? {}), ...(trouble && { trouble: troubleOf(trouble) }) }) : undefined;
@@ -2967,8 +3035,8 @@ function startRunner(): void {
function sweepInterrupted(): void {
const now = Date.now();
const rows = db()
- .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">[];
+ .prepare("SELECT id, provider, model_id, op, 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" | "model_id" | "op" | "request_json" | "external_meta_json">[];
const busy = submitting();
for (const r of rows) {
if (busy.has(r.id)) continue;
@@ -2977,8 +3045,11 @@ function sweepInterrupted(): void {
if (meta.lease && typeof meta.lease.until === "number" && meta.lease.until > now) continue;
if (meta.heal && takeOver(r, meta.heal)) continue;
// 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");
+ const cutOff = !!meta.heal && typeof meta.heal.sending === "number";
+ const words = cutOff ? CUT_OFF_SENDING : "This run stopped before it started. Press Retry.";
+ if (updateIfGoing(r.id, { status: "failed", error: words, completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {
+ ownFailed(r.id, ownAccountIn(r.request_json), factsOf(r, { stage: "submit" }), cutOff ? "interrupted-sending" : "interrupted");
+ }
}
}
@@ -2990,7 +3061,7 @@ const CUT_OFF_SENDING = "This run was interrupted while it was being sent. Press
* 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" | "provider" | "request_json">, h: HealState): boolean {
+function takeOver(r: Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json">, h: HealState): boolean {
if (typeof h.sending === "number") return false;
let stored: GenerationRequest;
try {
@@ -3008,7 +3079,9 @@ function takeOver(r: Pick<Row, "id" | "provider" | "request_json">, h: HealState
} catch (e) {
// It can't run as the account runs now (its key removed, its model switched off): said in its own words.
const refusal = e instanceof AccountRunError ? e.refusal.error : (e as Error).message;
- updateIfGoing(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL");
+ if (updateIfGoing(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {
+ ownFailed(r.id, account, factsOf(r, { stage: "submit" }), e instanceof AccountRunError ? e.refusal.code : "refused");
+ }
return true;
}
// Planned for another provider now (its GPU disconnected, another key): its polls would ask the provider it was made
@@ -3018,7 +3091,9 @@ function takeOver(r: Pick<Row, "id" | "provider" | "request_json">, h: HealState
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");
+ } else if (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")) {
+ ownFailed(r.id, account, { provider: r.provider, model: p.plan.model.id, op: p.plan.op, stage: "submit" }, "keys-changed");
+ }
return true;
}
submitting().add(r.id);
@@ -3066,7 +3141,10 @@ async function pollGuarded(r: Row): Promise<void> {
const onPool = account ? poolOf(r) : false;
const own = account && !onPool ? accountRun(account, r.provider, "poll") : undefined;
if (onPool) await runOnPool(account!, () => pollOne(r));
- else if (own && "error" in own) update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ else if (own && "error" in own) {
+ update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ ownFailed(r.id, account!, factsOf(r, { stage: "poll" }), own.code);
+ }
else if (own) await own.run(() => pollOne(r));
else await pollOne(r);
} catch (e) {
@@ -3223,15 +3301,25 @@ async function pollOne(r: Row): Promise<void> {
const ownQueue = !!own && !onPool;
let movedAt = typeof ctx.meta.queueMovedAt === "number" ? ctx.meta.queueMovedAt : run.submitted_at;
const pos = res?.state === "queued" && typeof res.position === "number" ? res.position : undefined;
- if (ownQueue && pos !== undefined && (typeof ctx.meta.queuePos !== "number" || pos < ctx.meta.queuePos)) {
- // Its place first seen is where it starts; only a place nearer the front is a queue that moves.
- if (typeof ctx.meta.queuePos === "number") movedAt = now;
+ // The job its GPU runs now (another one): a new one there is a queue that moves too.
+ const busyWith = res?.state === "queued" && typeof res.busyWith === "string" ? res.busyWith : undefined;
+ const wasBusyWith = typeof ctx.meta.busyWith === "string" ? ctx.meta.busyWith : undefined;
+ const nearer = pos !== undefined && (typeof ctx.meta.queuePos !== "number" || pos < ctx.meta.queuePos);
+ if (ownQueue && pos !== undefined && (nearer || busyWith !== wasBusyWith)) {
+ // Its place first seen is where it starts; a place nearer the front, or another job running ahead of it, is a
+ // queue that moves.
+ if (typeof ctx.meta.queuePos === "number" && (nearer || (busyWith !== undefined && wasBusyWith !== undefined))) movedAt = now;
+ const place = nearer ? pos : ctx.meta.queuePos;
db()
- .prepare("UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.queuePos', @pos, '$.queueMovedAt', @movedAt) WHERE id = @id AND external_id IS NOT NULL")
- .run({ id: r.id, pos, movedAt });
+ .prepare(
+ "UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.queuePos', @place, '$.queueMovedAt', @movedAt, '$.busyWith', @busyWith) WHERE id = @id AND external_id IS NOT NULL",
+ )
+ .run({ id: r.id, place, movedAt, busyWith: busyWith ?? null });
}
+ // 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 queueOver = ownQueue
- ? now - Math.max(run.submitted_at, movedAt) > queueMs * OWN_QUEUE.scale || now - run.submitted_at > OWN_QUEUE_CAP_MS * OWN_QUEUE.scale
+ ? 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;
const overdue = run.started_at ? now - run.started_at > runMs : !startsNow && queueOver;
if (overdue) {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 98cb3ba3..b420ac9e 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -557,6 +557,18 @@ function forget(promptId: string) {
globalThis.__fuobeComfyMisses?.delete(promptId);
}
+/**
+ * A job's place in ComfyUI's queue (`/queue` queue_pending): how many jobs go before it (0: next), or -1 when it isn't
+ * there. The list is ComfyUI's heap, not in order: the jobs before it are the ones with a lower number.
+ */
+export function queuePlace(pending: unknown[][], promptId: string): number {
+ const mine = pending.find((q) => q[1] === promptId);
+ if (!mine) return -1;
+ const n = mine[0];
+ if (typeof n !== "number") return pending.indexOf(mine);
+ return pending.filter((q) => typeof q[0] === "number" && q[0] < n).length;
+}
+
// ---------------------------------------------------------------------------
// Outputs
@@ -2961,7 +2973,7 @@ export const comfyProvider: ProviderAdapter = {
const p = progress.get(externalId);
const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue", worker);
const running = queue.queue_running?.some((q) => q[1] === externalId);
- const pendingIdx = queue.queue_pending?.findIndex((q) => q[1] === externalId) ?? -1;
+ const pendingIdx = queuePlace(queue.queue_pending ?? [], externalId);
if (!running && pendingIdx < 0 && !entry) {
// It may have finished between the two requests (ComfyUI moves it from the queue to the history at once).
const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${encodeURIComponent(externalId)}`, worker))[externalId];
@@ -2980,7 +2992,11 @@ export const comfyProvider: ProviderAdapter = {
return { state: "failed", error: "ComfyUI restarted and lost this run. Press Retry." };
}
globalThis.__fuobeComfyMisses?.delete(externalId);
- if (pendingIdx >= 0) return { state: "queued", position: pendingIdx, message: pendingIdx === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${pendingIdx} ahead` };
+ if (pendingIdx >= 0) {
+ // The job the GPU runs now (another one), by its name there: a new one is a queue that moves.
+ const busy = queue.queue_running?.[0]?.[1];
+ return { state: "queued", position: pendingIdx, ...(typeof busy === "string" && { busyWith: busy.slice(0, 64) }), message: pendingIdx === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${pendingIdx} ahead` };
+ }
const total = Number(meta.nodeCount ?? 0);
const stepFrac = p && p.max ? p.value / p.max : 0;
const progressValue = total ? Math.min(0.99, ((p?.nodesDone ?? 0) - 1 + stepFrac) / total) : stepFrac || undefined;
diff --git a/src/server/providers/types.ts b/src/server/providers/types.ts
index c57009a7..77e98749 100644
--- a/src/server/providers/types.ts
+++ b/src/server/providers/types.ts
@@ -35,7 +35,17 @@ export interface RemoteOutput {
* what was missing when it failed (`fix`: the tile's "Fix it").
*/
export type PollResult =
- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; /** Jobs ahead of it in the queue (0: next). */ position?: number }
+ | {
+ state: "queued";
+ progress?: number;
+ message?: string;
+ sentAt?: number;
+ timeoutError?: string;
+ /** Jobs ahead of it in the queue (0: next). */
+ position?: number;
+ /** The job its GPU runs now (another one): a new one there is a queue that moves, and one job may take its own time. */
+ busyWith?: string;
+ }
| { state: "running"; progress?: number; message?: string; sentAt?: number }
| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }
/**
diff --git a/tests/own-gpu-graceful.test.ts b/tests/own-gpu-graceful.test.ts
index 985a483c..381b0189 100644
--- a/tests/own-gpu-graceful.test.ts
+++ b/tests/own-gpu-graceful.test.ts
@@ -35,10 +35,10 @@ const uploadsRoute = await import("@/app/api/uploads/route");
const gpuRoute = await import("@/app/api/account/gpu/route");
const generationRoute = await import("@/app/api/generations/[id]/route");
const smallerRoute = await import("@/app/api/generations/[id]/smaller/route");
-const { cancelGeneration, getGeneration, LEASE, OWN_QUEUE, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");
+const { asAccount, CHAINED_RUN, cancelGeneration, createGenerations, getGeneration, LEASE, OWN_QUEUE, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");
const { ownRunNote } = await import("@/server/run-events");
const { cleanGpuAddress, checkGpuAddress, visitorStatus } = await import("@/server/account-gpu");
-const { comfyProvider, onOwnGpu } = await import("@/server/providers/comfyui");
+const { comfyProvider, onOwnGpu, queuePlace } = await import("@/server/providers/comfyui");
const { db } = await import("@/server/db");
const { resetRates } = await import("@/server/rate");
const { runAsTenant } = await import("@/server/tenant");
@@ -95,6 +95,13 @@ async function startRun(): Promise<string> {
expect(r.status, await r.clone().text()).toBe(201);
return ((await r.json()) as { items: { id: string }[] }).items[0].id;
}
+/** A later step of the run `first`: it waits for that run's result, as a relight's clip waits for its still. */
+function laterStep(first: string, pic: string): string {
+ const [g] = asAccount(a, () => createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } } as Parameters<typeof createGenerations>[0], { dependsOn: first }));
+ return g.id;
+}
+/** A run's kept state before its job is sent (its wait, and which instance holds it). */
+const setPending = (id: string, meta: object) => db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify(meta), id);
/** Tick the runner until the row is done (or the time is up), noting every message the tile showed on the way. */
async function settle(id: string, ms = 15_000, seen: string[] = []) {
const end = Date.now() + ms;
@@ -519,6 +526,27 @@ 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("a GPU disconnected while its job runs: the run stops in plain words, and the owner gets its line", async () => {
+ const warn = vi.spyOn(console, "warn");
+ fake.opts.delayMs = 60_000;
+ try {
+ const id = await startRun();
+ for (let i = 0; i < 500 && getGeneration(id)?.status !== "running"; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ auth.setAccountGpu(a, null);
+ const g = await settle(id);
+ expect(g?.status).toBe("failed");
+ plainWords(g?.error);
+ expect(ownRunNote(id)).toMatchObject({ cause: "connect-gpu", stage: "poll" });
+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(id));
+ expect(JSON.parse(line!)).toMatchObject({ run: id, account: a, place: "own-gpu", stage: "poll", cause: "connect-gpu", outcome: "failed" });
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
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);
@@ -598,6 +626,48 @@ describe("a busy GPU: a queue that keeps moving is waited out", () => {
fake.opts.promptId = undefined;
}
});
+
+ it("counts its place by ComfyUI's queue numbers: the list ComfyUI answers isn't in order", async () => {
+ expect(queuePlace([[1, "a"], [4, "mine"], [2, "b"], [5, "c"], [3, "d"]], "mine")).toBe(3);
+ expect(queuePlace([[7, "mine"], [9, "a"]], "mine")).toBe(0);
+ expect(queuePlace([[1, "a"]], "mine")).toBe(-1);
+ fake.opts.promptId = "job-heap";
+ const heap = { status: 200, body: JSON.stringify({ queue_running: [[0, "someone-else"]], queue_pending: [[1, "a"], [4, "job-heap"], [2, "b"], [5, "c"], [3, "d"]] }), contentType: "application/json" };
+ fake.opts.answer = (m, p) => (p === "/queue" && m === "GET" ? heap : p.startsWith("/history/") ? empty : undefined);
+ try {
+ const id = await startRun();
+ for (let i = 0; i < 500 && !/ahead/.test(getGeneration(id)?.message ?? ""); i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ expect(getGeneration(id)?.message).toBe("In ComfyUI's queue · 3 ahead");
+ await cancelGeneration(id);
+ } finally {
+ fake.opts.promptId = undefined;
+ }
+ });
+
+ it("next in line behind one long job: waits while that job runs (up to one job's own time), then runs", async () => {
+ OWN_QUEUE.scale = 0.001; // the 30 minutes without moving: 1.8 s; one job's 45 minutes: 2.7 s
+ fake.opts.promptId = "job-next";
+ const started = Date.now();
+ // One render runs ahead of it for about 2.3 s (past the 30 minutes), then it is this job's turn.
+ fake.opts.answer = (m, p) => {
+ if (Date.now() - started > 2300) return undefined;
+ if (p === "/queue" && m === "GET") return { status: 200, body: JSON.stringify({ queue_running: [[0, "long-render"]], queue_pending: [[1, "job-next"]] }), contentType: "application/json" };
+ if (p.startsWith("/history/")) return empty;
+ return undefined;
+ };
+ try {
+ const seen: string[] = [];
+ const g = await settle(await startRun(), 20_000, seen);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(seen).toContain("Next in ComfyUI's queue");
+ } finally {
+ OWN_QUEUE.scale = 1;
+ fake.opts.promptId = undefined;
+ }
+ });
});
describe("runs that wait, and a file too big for the address", () => {
@@ -648,6 +718,31 @@ describe("runs that wait, and a file too big for the address", () => {
for (const id of [...jobs, ...made]) await cancelGeneration(id);
});
+ it("Run with your key on a waiting step of a longer run: refused in plain words, and the whole run goes on as it was", async () => {
+ SELF_HEAL.scale = 0.01;
+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);
+ const first = await startRun();
+ for (let i = 0; i < 500 && !getGeneration(first)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));
+ const pic = await uploadPng();
+ const second = laterStep(first, pic);
+ const made = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();
+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", engine: "cloud", prompt: "", inputs: { images: [pic] } };
+ // The step that waits, and the one that waits for it: neither moves alone.
+ for (const id of [first, second]) {
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: id }));
+ expect(r.status).toBe(409);
+ const said = (await r.json()) as { error: string; code: string };
+ expect(said).toEqual({ error: CHAINED_RUN, code: "chained-run" });
+ plainWords(said.error);
+ }
+ expect(CHAINED_RUN).toBe("This step is part of a longer run, so it can't move to your key on its own. It goes on by itself, or cancel it and run the tool again with your key.");
+ // Nothing stopped and nothing new was made: the first step still waits, the second still waits for it.
+ expect(getGeneration(first)).toMatchObject({ status: "queued", waiting: expect.anything() });
+ expect(getGeneration(second)?.status).toBe("queued");
+ expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(made);
+ for (const id of [first, second]) 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;
@@ -710,6 +805,65 @@ describe("runs that wait, and a file too big for the address", () => {
});
});
+describe("a step of a longer run that waited, taken over after a restart", () => {
+ /** The run's first step, done on the GPU, with a picture for the next step to start from. */
+ async function firstStepDone(): Promise<{ first: string; pic: string }> {
+ fake.opts.output = "both";
+ const first = await startRun();
+ expect((await settle(first))?.status).toBe("succeeded");
+ return { first, pic: await uploadPng() };
+ }
+
+ it("goes on with what is left of its wait (its tries and its time), and runs once", async () => {
+ const info = vi.spyOn(console, "info");
+ try {
+ const { first, pic } = await firstStepDone();
+ fake.log.length = 0;
+ const second = laterStep(first, pic);
+ // It waited for the GPU on an instance that is gone (its hold ran out): seven tries, two minutes.
+ const since = Date.now() - 2 * 60_000;
+ setPending(second, {
+ heal: { since, deadline: Date.now() + 60_000, firstSeen: { "gpu-starting": since }, tries: 7, next: 0, index: 0, words: "Waiting for your GPU to start up", trouble: { cause: "gpu-starting", actions: [] } },
+ lease: { by: "gone", until: Date.now() - 1 },
+ });
+ const g = await settle(second, 20_000);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
+ // Healed on its seventh try, its wait counted from when it began.
+ const healed = info.mock.calls
+ .map((c) => String(c[0]))
+ .filter((l) => l.includes('"evt":"own-run"') && l.includes(`"run":"${second}"`) && l.includes('"outcome":"healed"'))
+ .map((l) => JSON.parse(l) as { attempt: number; waitedMs: number });
+ expect(healed).toHaveLength(1);
+ expect(healed[0].attempt).toBe(7);
+ expect(healed[0].waitedMs).toBeGreaterThanOrEqual(2 * 60_000);
+ } finally {
+ info.mockRestore();
+ fake.opts.output = undefined;
+ }
+ });
+
+ it("one cut off in the middle of its send is never sent again, and the owner gets its line", async () => {
+ const warn = vi.spyOn(console, "warn");
+ try {
+ const { first, pic } = await firstStepDone();
+ fake.log.length = 0;
+ const second = laterStep(first, pic);
+ setPending(second, { heal: { since: Date.now() - 60_000, deadline: Date.now() + 60_000, firstSeen: {}, tries: 2, next: 0, index: 0, sending: Date.now() - 1000 }, lease: { by: "gone", until: Date.now() - 1 } });
+ const g = await settle(second);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");
+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);
+ expect(ownRunNote(second)).toMatchObject({ cause: "interrupted-sending", stage: "chain", hostKind: "web" });
+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(second));
+ expect(JSON.parse(line!)).toMatchObject({ run: second, account: a, place: "own-gpu", cause: "interrupted-sending", outcome: "failed" });
+ } finally {
+ warn.mockRestore();
+ fake.opts.output = undefined;
+ }
+ });
+});
+
// Last: the server's own state is replaced here (a new instance of the runner's module on the same database).
describe("a wait survives a restart or a deploy", () => {
it("another instance's look while this one holds a waiting run leaves it alone", async () => {
@@ -752,6 +906,7 @@ describe("a wait survives a restart or a deploy", () => {
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);
+ expect(ownRunNote(id)).toMatchObject({ cause: "keys-changed", stage: "submit" });
} finally {
shut.draining = false;
STALE_SUBMIT.ms = 2 * 60_000;
@@ -849,6 +1004,8 @@ describe("a wait survives a restart or a deploy", () => {
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.");
+ // The owner's note says why: a server cut off in the middle of the send.
+ expect(ownRunNote(id)).toMatchObject({ cause: "interrupted-sending", stage: "submit" });
// 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();
diff --git a/tests/own-keys-graceful.test.ts b/tests/own-keys-graceful.test.ts
index cbfc7bb2..d62bbe76 100644
--- a/tests/own-keys-graceful.test.ts
+++ b/tests/own-keys-graceful.test.ts
@@ -207,6 +207,34 @@ describe("an account's run on its own key waits out a busy or down provider", ()
for (const id of ids) await gens.cancelGeneration(id);
});
+ it("a waiting step of a longer run doesn't offer Run with your other key, and moving it alone is refused", async () => {
+ gens.SELF_HEAL.scale = 0.1;
+ fal.script = (r) => (isSubmit(r) ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "1" } } : null);
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ for (let i = 0; i < 500 && !gens.getGeneration(g.id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));
+ const offered = () => (gens.getGeneration(g.id)?.waiting?.actions ?? []).map((a) => a.kind);
+ // On its own, the run offers its other key.
+ expect(offered()).toContain("run-with-key");
+ // A later step waits for its result (as a relight's clip waits for its still).
+ const [later] = gens.asAccount(A, () => gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "the same harbour at night" }, { dependsOn: g.id }));
+ expect(offered()).not.toContain("run-with-key");
+ expect(offered()).toContain("retry");
+ // Its next try doesn't offer it either.
+ const heal = () => (JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(g.id))) as { heal: { tries: number; trouble: { actions: { kind: string }[] } } }).heal;
+ const tries = heal().tries;
+ for (let i = 0; i < 1000 && heal().tries === tries; i++) await new Promise((r) => setTimeout(r, 10));
+ expect(heal().tries).toBeGreaterThan(tries);
+ expect(heal().trouble.actions.map((a) => a.kind)).not.toContain("run-with-key");
+ // Pressed anyway (a tile drawn before): refused in plain words, and both steps go on as they were.
+ const text = JSON.stringify({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour at dawn", replaces: g.id });
+ const r = await generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));
+ expect(r.status).toBe(409);
+ expect(await r.json()).toEqual({ error: gens.CHAINED_RUN, code: "chained-run" });
+ expect(gens.getGeneration(g.id)?.status).toBe("queued");
+ expect(gens.getGeneration(later.id)?.status).toBe("queued");
+ for (const id of [g.id, later.id]) 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" });
@@ -218,6 +246,23 @@ describe("an account's run on its own key waits out a busy or down provider", ()
});
});
+describe("Not billed", () => {
+ it("isn't said of a run cut off while it was being sent (fal.ai may have the job)", async () => {
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await settle(g.id);
+ const stopped = (error: string, meta: object) =>
+ db().prepare("UPDATE generations SET status = 'failed', external_id = NULL, error = ?, external_meta_json = ? WHERE id = ?").run(error, JSON.stringify(meta), g.id);
+ // Refused before fal.ai took it: nothing was billed.
+ stopped("fal.ai didn't accept your key. Check it in Settings → Your keys.", {});
+ expect(gens.getGeneration(g.id)!.notBilled).toBe(true);
+ // Its server was cut off in the middle of the send.
+ stopped("This run was interrupted while it was being sent. Press Retry.", { heal: { since: 1, deadline: 2, firstSeen: {}, tries: 1, next: 0, index: 0, sending: Date.now() } });
+ expect(gens.getGeneration(g.id)!.notBilled).toBeUndefined();
+ stopped("fal.ai is having trouble right now. Press Retry in a few minutes.", { heal: { since: 1, deadline: 2, firstSeen: {}, tries: 1, next: 0, index: 0, sending: Date.now() } });
+ expect(gens.getGeneration(g.id)!.notBilled).toBeUndefined();
+ });
+});
+
describe("what waiting can't fix fails at once, in plain words, with what helps", () => {
it("a model gone (404): pick another, the provider's words in the details, not billed", async () => {
fal.script = (r) => (isSubmit(r) ? { status: 404, body: { detail: "Application 'fal-ai/nano-banana-pro' not found" } } : null);