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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: a run keeps its line's clocks when a look at it fails, times each attempt on its own, and the line changes in one locked step
Adarshd0f79168baac
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 03e01de9..fa848e2b 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -146,6 +146,8 @@ export function cleanBeat(b: unknown): WorkerBeat {export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAnswer & { worker: WorkerAnswer } {const d = db();const device = `wkr-${w.id}`;+ // With the write lock from the start (IMMEDIATE): what it reads of the line is still so when it writes, even while+ // another app process on the same database (a deploy's overlap) writes too.return d.transaction(() => {// A worker back after going silent finds its task back in line first (its lease no longer works).sweepPool(now);@@ -206,7 +208,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA...(nextToken && { token: nextToken }),},};- })();+ }).immediate();}/**@@ -283,7 +285,7 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now()):if (held.length || !eligible(fresh, now)) return null;const t = pick(fresh, now);return t ? claimed(t, fresh, device, now) : null;- })();+ }).immediate();}function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {@@ -415,31 +417,40 @@ export function lineOrder(rows: TaskRow[], fairShare: boolean): TaskRow[] {* A task goes back in line: its worker let it go (`blame: false`: a pause, at no cost to anyone) or lost it (silent,* its ComfyUI down: the worker is noted in tried_json and it counts as an attempt). The third lost attempt fails it.* The old worker's lease stops working, so its late calls get 409.+ *+ * Only the task as `t` read it: one that has moved on since (another app process put it back in line, or a worker took+ * it again with a new lease) stays as it is now, and no attempt is counted. Returns whether it changed.*/-export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): void {- const tried = json<string[]>(t.tried_json, []);- const requeues = t.requeues + (o.blame ? 1 : 0);- if (o.blame && requeues >= MAX_ATTEMPTS) {- endTask(t.id, "failed", { error: o.why ?? "The GPUs couldn't finish this run. Press Retry.", requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);- return;- }- if (t.worker_id) logWorkerJob("requeued", t, t.worker_id);- // A live worker that let it go hears the stop in its beat answer; one that went silent finds its lease gone when it- // comes back (409), and takes the prompt off its own ComfyUI. It keeps its rank, so it keeps its place in line, and- // its wait limit no longer applies (a worker took it once).- setTask(t.id, {- state: "waiting",- lease_hash: null,- worker_id: null,- requeues,- sent_at: null,- started_at: null,- down_at: null,- down_why: null,- note: "resent",- ...(o.blame && t.worker_id && { tried_json: JSON.stringify([...new Set([...tried, t.worker_id])]) }),- });- db().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);+export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): boolean {+ const d = db();+ return d.transaction((): boolean => {+ const now = taskById(t.id);+ if (!now || now.state !== t.state || now.worker_id !== t.worker_id || now.lease_hash !== t.lease_hash || now.requeues !== t.requeues) return false;+ const tried = json<string[]>(t.tried_json, []);+ const requeues = t.requeues + (o.blame ? 1 : 0);+ if (o.blame && requeues >= MAX_ATTEMPTS) {+ endTask(t.id, "failed", { error: o.why ?? "The GPUs couldn't finish this run. Press Retry.", requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);+ return true;+ }+ if (t.worker_id) logWorkerJob("requeued", t, t.worker_id);+ // A live worker that let it go hears the stop in its beat answer; one that went silent finds its lease gone when it+ // comes back (409), and takes the prompt off its own ComfyUI. It keeps its rank, so it keeps its place in line, and+ // its wait limit no longer applies (a worker took it once).+ setTask(t.id, {+ state: "waiting",+ lease_hash: null,+ worker_id: null,+ requeues,+ sent_at: null,+ started_at: null,+ down_at: null,+ down_why: null,+ note: "resent",+ ...(o.blame && t.worker_id && { tried_json: JSON.stringify([...new Set([...tried, t.worker_id])]) }),+ });+ d.prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);+ return true;+ }).immediate();}/**@@ -450,6 +461,12 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): voi*/export function sweepPool(now = Date.now()): void {const d = db();+ // One step with the write lock (IMMEDIATE), on every path (the runner's look at a run too): what it reads is still so+ // when it writes, even while another app process on the same database claims or requeues.+ d.transaction(() => sweepLine(d, now)).immediate();+}++function sweepLine(d: ReturnType<typeof db>, now: number): void {const held = d.prepare(`SELECT t.*, w.seen_at AS w_seen, w.revoked_at AS w_revoked FROM relay_tasks t LEFT JOIN relay_workers w ON w.id = t.worker_iddiff --git a/src/server/generations.ts b/src/server/generations.tsindex d0c27591..b3d45834 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -2244,6 +2244,14 @@ function runningLimitMs(r: Pick<Row, "provider">, meta: Record<string, unknown>,return runCeilingMs(wf ? poolLane(wf) : null);}+/**+ * Is the run's job a task for the workers? An account's run on this install's GPUs that went to the workers, or one the+ * provider marked so when it handed the job over (the owner's jobs on the workers too).+ */+function workersTask(meta: Record<string, unknown>, onPool: boolean): boolean {+ return typeof meta.relay === "string" && (onPool || meta.workers === true);+}+/** Order by: the owner's rows (no account in the request) before accounts'. */const ACCOUNT_LAST = "(json_extract(request_json, '$.account') IS NOT NULL)";@@ -2297,12 +2305,18 @@ async function pollOne(r: Row): Promise<void> {run = { submitted_at: res.sentAt, started_at: null };}// A job for the workers keeps its task's own clocks (its wait limit until a worker first takes it): back in line- // after an attempt, its next attempt gets its own running time, and no wait limit of the runner's ends it.- const ownClocks = !!res && (res.state === "queued" || res.state === "running") && !!res.ownClocks;+ // after an attempt, its next attempt gets its own running time, and no wait limit of the runner's ends it. A poll that+ // failed (a busy database in a deploy's overlap) changes none of that: the next poll looks again.+ const ownClocks = res ? (res.state === "queued" || res.state === "running") && !!res.ownClocks : workersTask(ctx.meta, onPool);if (ownClocks && res?.state === "queued" && run.started_at) {db().prepare("UPDATE generation_runs SET started_at = NULL WHERE id = ?").run(r.id);run = { ...run, started_at: null };}+ // Each attempt is timed on its own: one a worker took (or sent again) after the running clock started restarts it.+ if (ownClocks && res?.state === "running" && res.attemptAt && run.started_at && res.attemptAt > run.started_at) {+ db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(res.attemptAt, r.id);+ run = { ...run, started_at: res.attemptAt };+ }// A job that has just left the queue gets its full running time from now.const startsNow = res?.state === "running" && !run.started_at;const limitMs = runningLimitMs(r, ctx.meta, account, onPool);diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 9a731871..0c774c18 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -2435,9 +2435,14 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,// an attempt (a worker paused, went quiet, restarted), it keeps its place.const res: PollResult = t.state === "waiting" ? { state: "queued", message: t.note === "resent" ? "Back in line for another GPU" : poolWaitWords(t) } : await pollTask(principal, t, meta, manifest, made);if (res.state !== "queued" && res.state !== "running") return res;+ // The attempt now running started when a worker took it (a claim) or sent it again (its ComfyUI lost it): its running+ // time counts from then, whatever the attempts before it took.+ const attempt = t.state !== "waiting" && t.claimed_at ? { attemptAt: t.claimed_at } : {};// An account's run says only where it is: in line, or working on it (the owner's own runs keep the workers' words).- if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ownClocks: true };- return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ownClocks: true } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ownClocks: true };+ if (!tenantAccount()) {+ return res.state === "running" ? { state: "running", progress: res.progress, message: res.message, ownClocks: true, ...attempt } : { state: "queued", progress: res.progress, message: res.message, ownClocks: true };+ }+ return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ownClocks: true } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ownClocks: true, ...attempt };}/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */@@ -2577,7 +2582,8 @@ export const comfyProvider: ProviderAdapter = {poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs() }),}),});- return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };+ // (`workers`: a task for the workers, whose own clocks time it even when a poll of it fails.)+ return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id, ...(forPool && { workers: true }) }, payload: wf };}// A run on this install's workers with no account behind it is never sent anywhere.if (onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);diff --git a/src/server/providers/types.ts b/src/server/providers/types.tsindex 259b09ed..a8e77f62 100644--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@ -32,11 +32,12 @@ export interface RemoteOutput {* What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the* queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and* what was missing when it failed (`fix`: the tile's "Fix it"). A job for the workers keeps its task's own clocks- * (`ownClocks`): the runner then sets no wait limit of its own, and its running time counts from the attempt now running.+ * (`ownClocks`): the runner then sets no wait limit of its own, and its running time counts from the attempt now running+ * (`attemptAt`: when a worker took it this time, or sent it again after its ComfyUI lost it).*/export type PollResult =| { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true }- | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true }+ | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true; attemptAt?: number }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }| { state: "failed"; error: string; fix?: GenerationFix };diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex f9a76951..6c357363 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -313,7 +313,11 @@ describe("the run ceiling", () => {tasks.setTask(t!.id, { state: "running", started_at: Date.now() });await globalThis.__fuobeRunner?.tick();expect(getGeneration(id)?.status).toBe("running");- const startedAgo = (ms: number) => db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);+ // The worker took it this long ago, and the run has been going since.+ const startedAgo = (ms: number) => {+ db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);+ db().prepare("UPDATE relay_tasks SET claimed_at = ? WHERE id = ?").run(Date.now() - ms, t!.id);+ };startedAgo(50 * MIN);beatAs(w);await globalThis.__fuobeRunner?.tick();diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 986c7985..e38f8af5 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -59,7 +59,7 @@ const pool = await import("@/server/computer/pool");const billing = await import("@/server/billing");const outbox = await import("@/server/billing-outbox");const qs = await import("@/server/queue-settings");-const { loadManifest } = await import("@/server/providers/comfyui");+const { comfyProvider, loadManifest } = await import("@/server/providers/comfyui");const { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");const { getModel } = await import("@/lib/catalog");@@ -546,6 +546,35 @@ describe("the worker steps aside for another program", () => {delete process.env.FUOBE_POOL_WAIT_MIN;}});++ it("a look at the run that fails while it waits back in line past its wait limit changes nothing: it stays In line in its place, and its output arrives", async () => {+ clock();+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ stepAsideWhenRunning(d, watch, "gpu-busy:game.exe");+ await workAll(d);+ expect(taskOf(id)!.state).toBe("waiting");+ // The game runs 25 minutes, past the run's 20 minute wait limit.+ await pass(25 * MIN, [d], watch);+ expect(getGeneration(id)?.status).toBe("queued");+ // One look of the runner's fails (a busy database in a deploy's overlap, say).+ const spy = vi.spyOn(comfyProvider, "poll").mockRejectedValueOnce(new Error("database is locked"));+ try {+ await tick();+ expect(spy).toHaveBeenCalled();+ } finally {+ spy.mockRestore();+ }+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ expect(taskOf(id)!.state).toBe("waiting");+ // The game ends: it runs, and nothing was lost.+ d.pause(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ });});describe("retries", () => {@@ -728,6 +757,39 @@ describe("the run ceiling per lane", () => {expect(after[0]).toBe("failed");await expectFreeFailure(id);});++ it("each attempt has the lane's ceiling to itself: 7 minutes into a 10 minute ceiling its ComfyUI loses the job, the worker sends it again, and the output arrives once", async () => {+ clock();+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 600 } } });+ const w = standInWorker();+ const { id, task } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ let crashed = false;+ let resent = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running") return;+ if (!crashed) {+ // The first attempt runs 7 minutes, then its ComfyUI restarts and loses the job.+ crashed = true;+ await pass(7 * MIN, [d], watch);+ await comfy.crash();+ await comfy.start();+ } else if (!resent && d.steps.includes("gone")) {+ // The worker sent it again: 4 minutes into this attempt (11 since the first began), it is still working.+ resent = true;+ await pass(4 * MIN, [d], watch);+ expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.working });+ }+ });+ await workAll(d);+ expect(crashed && resent).toBe(true);+ await expectOnce(id, watch, { place: 1 });+ // Its ComfyUI got the job twice (once per attempt), under the task's one prompt id.+ expect(comfy.postsOf(task.prompt_id)).toBe(2);+ });});describe("a deploy while results are being sent", () => {diff --git a/tests/worker-queue.test.ts b/tests/worker-queue.test.tsindex a9fca99b..204b1b88 100644--- a/tests/worker-queue.test.ts+++ b/tests/worker-queue.test.ts@@ -1,4 +1,5 @@import crypto from "node:crypto";+import Database from "better-sqlite3";import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { tempDir } from "./helpers/temp-dir";@@ -137,6 +138,44 @@ describe("one job at a time", () => {expect(rowOf(a.id).state).toBe("sending");expect(rowOf(a.id).requeues).toBe(0);});++ it("a requeue decided on an earlier read of a job changes nothing once its worker has taken it again with a new lease", () => {+ const w = standInWorker();+ const a = accountTask();+ beatAs(w);+ expect(claimAs(w)?.id).toBe(a.id);+ // What another app process read of the job a moment ago, as its sweep found the worker silent.+ const before = rowOf(a.id);+ // Meanwhile the worker came back and asked again: the same job, with a new lease.+ beatAs(w);+ expect(claimAs(w, [])?.id).toBe(a.id);+ const now = rowOf(a.id);+ expect(now.lease_hash).not.toBe(before.lease_hash);+ // The requeue from that earlier read lands late: the job stays with its worker, its lease works, no attempt counted.+ expect(pool.backInLine(before, { blame: true })).toBe(false);+ expect(rowOf(a.id)).toMatchObject({ state: now.state, worker_id: w.id, lease_hash: now.lease_hash, requeues: 0 });+ });++ it("the sweep reads and changes the line in one step with the write lock, so another process's claim never lands in between", () => {+ const w = standInWorker();+ accountTask();+ beatAs(w);+ // Another app process on the same database holds the write lock.+ const other = new Database(db().name);+ const wait = db().pragma("busy_timeout", { simple: true }) as number;+ other.exec("BEGIN IMMEDIATE");+ db().pragma("busy_timeout = 20");+ try {+ // The sweep waits for the lock before it reads anything (here, past its short wait: busy), never reading the line+ // while the other process may still change it.+ expect(() => pool.sweepPool()).toThrow(/busy|locked/i);+ } finally {+ other.exec("ROLLBACK");+ other.close();+ db().pragma(`busy_timeout = ${wait}`);+ }+ expect(() => pool.sweepPool()).not.toThrow();+ });});describe("back in line", () => {