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.

Workers: a ComfyUI that stops answering starts again, and a job taken back stops at once

Adarshfe1c1b92dffc
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjs
index d78c1dbc..ce256fc6 100644
--- a/bin/lib/worker/comfy.mjs
+++ b/bin/lib/worker/comfy.mjs
@@ -242,6 +242,8 @@ export class OwnComfy {
this.onCrash = null;
/** The task its ComfyUI runs now (the worker says), so a crash counts against it. */
this.task = null;
+ /** When it last answered anything (a ComfyUI that stops answering is stuck). */
+ this.answeredAt = 0;
this.log = null;
}
@@ -291,7 +293,10 @@ export class OwnComfy {
fetch(url, init = {}) {
const headers = new Headers(init.headers);
for (const [k, v] of Object.entries(this.headers())) headers.set(k, v);
- return (this.o.fetch ?? fetch)(this.rebase(url), { ...init, headers });
+ return (this.o.fetch ?? fetch)(this.rebase(url), { ...init, headers }).then((res) => {
+ this.answeredAt = (this.o.now ?? Date.now)();
+ return res;
+ });
}
/** A ComfyUI left running by a worker that stopped without stopping it (its pid file says): stop it. True when it did. */
@@ -392,6 +397,7 @@ export class OwnComfy {
}
}
this.ready = true;
+ this.answeredAt = (this.o.now ?? Date.now)();
return;
}
}
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index 6a550343..2eaa9926 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -18,6 +18,8 @@ export const DEFAULTS = {
port: null,
/** A job that makes no progress for this many minutes goes back to the line, and a stuck ComfyUI is started again. */
stallMin: 10,
+ /** Its ComfyUI answering nothing for this many minutes is stuck: the worker stops it and starts it again. */
+ hungMin: 3,
/** ffmpeg, which makes every clip and sound again before its ComfyUI reads them. None: the worker takes pictures only. */
ffmpeg: null,
/** Another program's VRAM above this pauses the worker. */
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 32f9ec54..fc18d096 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -38,6 +38,8 @@ export function loadRequirements(file = path.join(ROOT, "workflows/comfyui/requi
return JSON.parse(fs.readFileSync(file, "utf8"));
}
+const HOUR = 3_600_000;
+
/** The worker looks at its model folders again this often (a folder that comes back after a restart counts). */
export const RESCAN_MS = 10 * 60_000;
@@ -117,6 +119,7 @@ export async function runWorker(cfg, deps) {
let busyJob = false;
let job = Promise.resolve();
let lastTask = null;
+ let guardMissingAt = -Infinity;
// How often its ComfyUI stopped while running each task (a task that stops it twice fails, not the worker).
const crashFile = path.join(cfg.workDir, "crashes.json");
@@ -308,7 +311,13 @@ export async function runWorker(cfg, deps) {
if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
}
}
- if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t)) comfyTrouble = null;
+ if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t) && t - guardMissingAt >= HOUR) comfyTrouble = null;
+ // A ComfyUI that stopped answering (hung) is stopped; the next turn starts it again. Every beat looks at it (its
+ // /system_stats), so one that answers anything at all is never taken for hung.
+ if (comfy.alive() && comfy.ready && t - comfy.answeredAt > (cfg.hungMin ?? 3) * 60_000) {
+ log("Its ComfyUI stopped answering: starting it again.");
+ await comfy.stop();
+ }
const next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };
const changed = next.paused !== pause.paused || next.why !== pause.why;
pause = next;
@@ -352,8 +361,10 @@ export async function runWorker(cfg, deps) {
troubleAt = t;
log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
} else if (e instanceof GuardMissing) {
+ // Not again for an hour: it would only start the same ComfyUI again.
comfyTrouble = "comfy-crashes";
- log(`${e.message}: it won't use it.`);
+ guardMissingAt = t;
+ log(`${e.message}: it won't use it, and pauses for an hour.`);
} else log(`ComfyUI didn't start: ${e.message}`);
}
}
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 29db94d0..e97fe7ec 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -116,8 +116,8 @@ the environment, removes it from there, and puts a check in front of every reque
Before the worker sends the key, the process on the port must prove two things. It signs a random challenge with the
key (`GET /fuobe-worker/hello`, HMAC-SHA-256), and it names its process id, which must be the one that the worker
started. A program that took the port first learns nothing. When ComfyUI is ready, the worker also checks that a
-request without the key is refused. If it is not refused, the guard is missing, and the worker does not use that
-ComfyUI.
+request without the key is refused. If it is not refused, the guard is missing. The worker then stops that ComfyUI,
+does not use it, and pauses itself for an hour ("comfy-crashes").
**A ComfyUI left running.** The worker writes its ComfyUI's process id to `comfyui.pid` in the worker folder. If the
worker stops without stopping ComfyUI (a crash), the next start finds that file. It stops that process, but only when
@@ -258,6 +258,9 @@ The worker keeps its jobs going by itself:
run limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps
its place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and
starts it again. A job that is given back counts as an attempt; the third time, it fails.
+- **A ComfyUI that stops answering** for `hungMin` minutes (3) is stopped and started again.
+- **A job that the studio took back** (its token for the job no longer works, for example after the worker was out of
+ touch) is stopped in its ComfyUI at once, so it never keeps the GPU busy for nothing.
- **Out of memory.** The worker frees its ComfyUI's memory (`/free`) and sends the job once more. Only a second time
fails the job.
- **Inputs are read once.** The worker keeps a copy of each input (by its SHA-256) while its job runs, so a job that
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 4036108b..db62468e 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -581,7 +581,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
const asked = JSON.parse(body.toString("utf8") || "{}") as { prompt_id?: string };
entry.body = asked;
const id = asked.prompt_id;
- if (id && running?.id === id) cancel(id);
+ // ComfyUI's own: a prompt id stops that prompt; none stops whatever runs.
+ if (running && (!id || running.id === id)) cancel(running.id);
return reply(200, {});
}
if (p.startsWith("/history/")) {
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index c74b7d5c..551af51e 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -7,6 +7,8 @@
* - The worker stops after the render and before the upload (or before the studio heard it finished): the output
* arrives after the next start, and its ComfyUI got exactly one prompt. Paused here, it still sends kept results.
* - Its ComfyUI hangs: the job is given back within the stall limit, and then runs to the end.
+ * - A job the studio took back mid-run stops in its ComfyUI at once.
+ * - A ComfyUI that stops answering is stopped and started again; one that answers without its guard is not used.
* - A request to its ComfyUI with another Host or without the key is refused.
* - A clip is made again by ffmpeg before its ComfyUI sees it; without ffmpeg, the job goes back to the line.
* - A model file that turns up later is reported within one look at its folders.
@@ -146,7 +148,7 @@ function pc(): Pc {
}
/** Start `fuobe worker run` in this process (its ComfyUI a stand-in process of its own). */
-function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; ffmpeg?: string | null; rescanMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string> } = {}) {
+function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[] } = {}) {
const ctrl = new AbortController();
const cfg = {
site: SITE,
@@ -154,13 +156,14 @@ function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; fai
comfyDir: p.comfyDir,
workDir: p.workDir,
modelDirs: o.modelDirs ?? [],
- comfyCommand: [
+ comfyCommand: o.command ?? [
process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off",
"--steps", String(o.steps ?? 4), "--step-ms", String(o.stepMs ?? 40), "--worker-guard", "1", "--count-file", p.countFile,
...(o.failNext ? ["--fail-next", o.failNext] : []),
],
comfyGuard: true,
stallMin: o.stallMin ?? 10,
+ hungMin: o.hungMin ?? 3,
ffmpeg: o.ffmpeg ?? null,
};
const done = runWorker(cfg, {
@@ -313,6 +316,74 @@ describe("a worker keeps its jobs going", () => {
expect(prompts(p)).toBe(2);
});
+ it("a job taken from it mid-run (its lease no longer works): its prompt stops at once, and the job runs again", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ start(w, s, p, { steps: 30, stepMs: 200 });
+ const comfy = await until(async () => {
+ const c = comfyOf(p);
+ return c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 3 ? c : null;
+ });
+ // The studio puts the job back in line (as when it lost touch with the worker): its next report gets 409.
+ pool.backInLine(state(id), { blame: false });
+ const stopped = await until(async () => {
+ const st = await fakeStats(comfy.port);
+ return st.running === null || (st.step !== null && st.step < 3) ? st : null;
+ }, 10_000);
+ expect(stopped).toBeTruthy();
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(prompts(p)).toBe(2);
+ });
+
+ it("its ComfyUI stops answering: the worker stops it and starts it again", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const hung = path.join(p.comfyDir, "hung.mjs");
+ // Answers as a guarded ComfyUI for a few seconds, then never again (hung).
+ fs.writeFileSync(
+ hung,
+ `import http from "node:http"; import crypto from "node:crypto";
+const key = process.env.FUOBE_WORKER_GUARD_KEY; const port = Number(process.argv[2]); const until = Date.now() + 3000;
+http.createServer((q, s) => {
+ if (Date.now() > until) return;
+ if (q.headers.host !== "127.0.0.1:" + port) { s.writeHead(403); return s.end(); }
+ if (q.url.startsWith("/fuobe-worker/hello") && !q.headers["x-fuobe-worker-key"]) {
+ s.writeHead(200, { "content-type": "application/json" });
+ return s.end(JSON.stringify({ proof: crypto.createHmac("sha256", key).update(String(q.headers["x-fuobe-worker-challenge"])).digest("hex"), pid: process.pid }));
+ }
+ if (q.headers["x-fuobe-worker-key"] !== key) { s.writeHead(403); return s.end(); }
+ s.writeHead(200, { "content-type": "application/json" }); s.end(JSON.stringify({ system: {}, devices: [] }));
+}).listen(port, "127.0.0.1");`,
+ );
+ start(w, s, p, { command: [process.execPath, hung, "{port}"], hungMin: 0.05 });
+ await until(() => p.logs.some((l) => /stopped answering/.test(l)), 60_000);
+ await until(() => p.logs.filter((l) => /Starting its own ComfyUI/.test(l)).length >= 2, 30_000);
+ });
+
+ it("a ComfyUI that answers without its guard is stopped and not started again for an hour", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const open = path.join(p.comfyDir, "open.mjs");
+ // Proves itself with the key, but answers every request without it: the guard isn't there.
+ fs.writeFileSync(
+ open,
+ `import http from "node:http"; import crypto from "node:crypto"; const key = process.env.FUOBE_WORKER_GUARD_KEY;
+http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/json" });
+ s.end(JSON.stringify(q.url.startsWith("/fuobe-worker/hello") ? { proof: crypto.createHmac("sha256", key).update(String(q.headers["x-fuobe-worker-challenge"])).digest("hex"), pid: process.pid } : { system: {}, devices: [] })); }).listen(Number(process.argv[2]), "127.0.0.1");`,
+ );
+ start(w, s, p, { command: [process.execPath, open, "{port}"] });
+ await until(() => p.logs.some((l) => /without the worker's guard/.test(l)), 60_000);
+ await sleep(3_000);
+ expect(p.logs.filter((l) => /Starting its own ComfyUI/.test(l))).toHaveLength(1);
+ expect(comfyOf(p)).toBeNull();
+ expect(p.logs.some((l) => /comfy-crashes/.test(l))).toBe(true);
+ });
+
it("stops when the studio no longer knows its token, and says so", async () => {
const w = addWorker();
const s = studio();