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.

ComfyUI reachability: a busy server isn't taken for a down one

Claude0adf4ee3173b
diff --git a/src/server/generations.ts b/src/server/generations.ts
index dd99afaa..ada24794 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -909,9 +909,19 @@ export function withoutSkipped(req: GenerationRequest, slots: ChainSlot[], skipp
/** The chain slots a step fills: its own, less the optional ones left out (chainSkipped). */
const filledSlots = (req: GenerationRequest, n: number): ChainSlot[] => slotsFor(req, n).filter((_, i) => !req.chainSkipped?.slots.includes(i));
+/** When a step after real ComfyUI steps first found ComfyUI not answering, by step id (shared across hot reloads). */
+declare global {
+ var __fuobeComfyWaits: Map<string, number> | undefined;
+}
+const comfyWaits = (): Map<string, number> => (globalThis.__fuobeComfyWaits ??= new Map<string, number>());
+/** How long such a step waits for ComfyUI to answer again before chainMode fails it. */
+export const COMFY_WAIT = { ms: 60_000 };
+
/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */
async function advanceDependents(): Promise<void> {
const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];
+ // A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.
+ let lookedAgain: Promise<boolean> | undefined;
for (const r of rows) {
if (submitting().has(r.id)) continue;
const stored = JSON.parse(r.request_json) as GenerationRequest;
@@ -959,7 +969,20 @@ async function advanceDependents(): Promise<void> {
}
// Routing reads cached reachability: make sure it's fresh for local engines.
const model = getModel(request.modelId);
- if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();
+ if (model?.routes.some((x) => x.provider === "comfyui") && !(await probeComfy()) && deps.some((d) => d!.provider === "comfyui")) {
+ // The earlier steps ran for real on ComfyUI: one missed check (a server busy finishing them, or restarting)
+ // mustn't make this one a demo, which chainMode fails. Look again at once (one forced look a sweep), then wait
+ // for the next sweeps (COMFY_WAIT from the first miss) before chainMode has its say.
+ const first = comfyWaits().get(r.id);
+ const back = first === undefined && (await (lookedAgain ??= probeComfy(true)));
+ if (!back && first === undefined) {
+ comfyWaits().set(r.id, Date.now());
+ update(r.id, { message: "Waits for ComfyUI to answer" });
+ continue;
+ }
+ if (!back && Date.now() - first! < COMFY_WAIT.ms) continue;
+ }
+ comfyWaits().delete(r.id);
if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
// Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 529e4ec8..164309e6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -1,5 +1,6 @@
import "server-only";
import fs from "node:fs";
+import net from "node:net";
import path from "node:path";
import { Worker } from "node:worker_threads";
import { tracksFor, type MotionPaths } from "@/lib/motion-paths";
@@ -415,54 +416,126 @@ async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promi
// ---------------------------------------------------------------------------
// Reachability. Routing (chooseRoute) is synchronous, so the first check for a server URL is a blocking probe
// (a worker thread does the fetch); after that the cached result is refreshed in the background every 10 s.
+// A server that refuses the connection (or a name that doesn't resolve) is down at once. One that doesn't answer
+// GET /system_stats in time isn't: a CPU ComfyUI busy with a job can take seconds to, but it still takes the
+// connection. So a late answer keeps the server reachable when it answered lately or its port takes a connection;
+// only a server that does neither (a machine that is off, a firewall that drops) is unreachable.
declare global {
- /** Reachability of the ComfyUI server, and its RAM (bytes) when /system_stats said. */
- var __fuobeComfyReach: { ok: boolean; at: number; url: string; ram?: number } | undefined;
+ /** Reachability of the ComfyUI server, its RAM (bytes) when /system_stats said, and when it last answered. */
+ var __fuobeComfyReach: { ok: boolean; at: number; url: string; ram?: number; seen?: number } | undefined;
+ /** The check under way: callers in the meantime share its answer. */
+ var __fuobeComfyProbe: { url: string; done: Promise<boolean> } | undefined;
}
-export async function probeComfy(force = false): Promise<boolean> {
- const cur = globalThis.__fuobeComfyReach;
- if (!force && cur && cur.url === baseUrl() && Date.now() - cur.at < 10_000) return cur.ok;
- let ok = false;
- let ram: number | undefined;
+/** How long a check waits for /system_stats, then for the port to take a connection; how long an answer counts as recent. */
+export const REACH = { answerMs: 2000, connectMs: 3000, answeredLatelyMs: 2 * 60_000 };
+
+/** Host and port of a server address, for the connection check (undefined when it isn't a URL). */
+function hostPort(url: string): { host: string; port: number } | undefined {
try {
- const r = await fetch(`${baseUrl()}/system_stats`, { headers: authHeaders(), signal: AbortSignal.timeout(2000) });
- ok = r.ok;
- if (ok) {
- const total = ((await r.json().catch(() => null)) as { system?: { ram_total?: unknown } } | null)?.system?.ram_total;
- if (typeof total === "number" && total > 0) ram = total;
- }
- } catch {}
- globalThis.__fuobeComfyReach = { ok, at: Date.now(), url: baseUrl(), ...(ram ? { ram } : {}) };
+ const u = new URL(url);
+ return { host: u.hostname.replace(/^\[|\]$/g, ""), port: Number(u.port) || (u.protocol === "https:" ? 443 : 80) };
+ } catch {
+ return undefined;
+ }
+}
+
+/** Whether the server's port takes a TCP connection within `timeoutMs` (a refusal says no at once). */
+function takesConnection(url: string, timeoutMs: number): Promise<boolean> {
+ const at = hostPort(url);
+ if (!at) return Promise.resolve(false);
+ return new Promise((resolve) => {
+ const socket = net.connect(at);
+ const done = (ok: boolean) => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(ok);
+ };
+ const timer = setTimeout(() => done(false), timeoutMs);
+ socket.once("connect", () => done(true)).once("error", () => done(false));
+ });
+}
+
+/** What GET /system_stats got: an answer (with the RAM it says), a no (an HTTP error, a refused connection), or nothing in time. */
+async function askComfy(url: string): Promise<{ answer: "yes"; ram?: number } | { answer: "no" | "late" }> {
+ try {
+ const r = await fetch(`${url}/system_stats`, { headers: authHeaders(), signal: AbortSignal.timeout(REACH.answerMs) });
+ if (!r.ok) return { answer: "no" };
+ const total = ((await r.json().catch(() => null)) as { system?: { ram_total?: unknown } } | null)?.system?.ram_total;
+ return { answer: "yes", ...(typeof total === "number" && total > 0 ? { ram: total } : {}) };
+ } catch (e) {
+ return { answer: (e as Error)?.name === "TimeoutError" ? "late" : "no" };
+ }
+}
+
+async function checkComfy(url: string): Promise<boolean> {
+ const asked = await askComfy(url);
+ const prev = globalThis.__fuobeComfyReach?.url === url ? globalThis.__fuobeComfyReach : undefined;
+ // Late is busy, not down, when it answered lately or its port still takes a connection (the one longer look).
+ const busy = asked.answer === "late" && ((!!prev?.seen && Date.now() - prev.seen < REACH.answeredLatelyMs) || (await takesConnection(url, REACH.connectMs)));
+ const at = Date.now();
+ // A busy server keeps the RAM and the time of its last answer.
+ const ram = asked.answer === "yes" ? (asked.ram ?? prev?.ram) : prev?.ram;
+ const seen = asked.answer === "yes" ? at : prev?.seen;
+ const ok = asked.answer === "yes" || busy;
+ globalThis.__fuobeComfyReach = ok ? { ok, at, url, ...(ram ? { ram } : {}), ...(seen ? { seen } : {}) } : { ok, at, url };
return ok;
}
+/** Is the ComfyUI server reachable? Cached for 10 s (`force` checks now); one check runs at a time. */
+export async function probeComfy(force = false): Promise<boolean> {
+ const url = baseUrl();
+ const cur = globalThis.__fuobeComfyReach;
+ if (!force && cur && cur.url === url && Date.now() - cur.at < 10_000) return cur.ok;
+ const running = globalThis.__fuobeComfyProbe;
+ if (running?.url === url) return running.done;
+ const done: Promise<boolean> = checkComfy(url).finally(() => {
+ if (globalThis.__fuobeComfyProbe?.done === done) globalThis.__fuobeComfyProbe = undefined;
+ });
+ globalThis.__fuobeComfyProbe = { url, done };
+ return done;
+}
+
/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */
export function comfyRam(): number | undefined {
const cur = globalThis.__fuobeComfyReach;
return cur?.ok && cur.url === baseUrl() ? cur.ram : undefined;
}
+// flag[0]: the answer (1 yes, 2 no or refused, 3 none in time); flag[1]: 1 once the port took the connection.
const PROBE_WORKER = `const { workerData } = require("node:worker_threads");
const flag = new Int32Array(workerData.sab);
+if (workerData.at) {
+ const socket = require("node:net").connect(workerData.at);
+ socket.once("connect", () => (Atomics.store(flag, 1, 1), socket.destroy())).once("error", () => {});
+}
fetch(workerData.url, { headers: workerData.headers, signal: AbortSignal.timeout(workerData.timeout) })
- .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), () => Atomics.store(flag, 0, 2))
+ .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), (e) => Atomics.store(flag, 0, e && e.name === "TimeoutError" ? 3 : 2))
.finally(() => Atomics.notify(flag, 0));`;
-/** Blocking reachability check (a few ms for a refused port, at most `timeoutMs` for a host that doesn't answer). */
+/**
+ * Blocking reachability check: a few ms for a server that answers or a refused port, at most `timeoutMs` otherwise.
+ * A server that takes the connection but doesn't answer in time is busy, so reachable. One that doesn't even take it
+ * is unreachable for now, and the unhurried check (probeComfy) goes on in the background to say for sure.
+ */
export function probeComfySync(timeoutMs = 1500): boolean {
const url = baseUrl();
- let ok = false;
+ let answer = 0;
+ let connected = false;
try {
- const sab = new SharedArrayBuffer(4);
+ const sab = new SharedArrayBuffer(8);
const flag = new Int32Array(sab);
- const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/system_stats`, headers: authHeaders(), timeout: timeoutMs } });
+ const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/system_stats`, at: hostPort(url), headers: authHeaders(), timeout: timeoutMs } });
Atomics.wait(flag, 0, 0, timeoutMs + 1000);
- ok = Atomics.load(flag, 0) === 1;
+ answer = Atomics.load(flag, 0);
+ connected = Atomics.load(flag, 1) === 1;
void worker.terminate();
} catch {}
- globalThis.__fuobeComfyReach = { ok, at: Date.now(), url };
+ const at = Date.now();
+ const ok = answer === 1 || (answer !== 2 && connected);
+ globalThis.__fuobeComfyReach = { ok, at, url, ...(answer === 1 ? { seen: at } : {}) };
+ if (!ok && answer !== 2) void probeComfy(true).catch(() => false);
return ok;
}
@@ -1309,7 +1382,7 @@ export const comfyProvider: ProviderAdapter = {
const cur = globalThis.__fuobeComfyReach;
// First check for this server: wait for the answer, so a request right after start isn't sent to demo.
if (!cur || cur.url !== baseUrl()) return probeComfySync();
- if (Date.now() - cur.at > 10_000) void probeComfy();
+ if (Date.now() - cur.at > 10_000) void probeComfy().catch(() => false);
return cur.ok;
},
diff --git a/tests/comfy-reach.test.ts b/tests/comfy-reach.test.ts
new file mode 100644
index 00000000..ce89ea22
--- /dev/null
+++ b/tests/comfy-reach.test.ts
@@ -0,0 +1,209 @@
+import fs from "node:fs";
+import http from "node:http";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 30_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-reach-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { comfyProvider, comfyRam, probeComfy, REACH } = await import("@/server/providers/comfyui");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { saveFile } = await import("@/server/storage");
+
+const RAM = 16 * 2 ** 30;
+/** A stand-in ComfyUI: /system_stats answers `status` after `delay` ms (a busy CPU server answers late, but takes the connection). */
+let delay = 0;
+let status = 200;
+let asked = 0;
+const server = http.createServer((req, res) => {
+ if (req.url !== "/system_stats") return void res.writeHead(404).end();
+ asked++;
+ setTimeout(() => {
+ if (res.destroyed) return;
+ res.writeHead(status, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ system: { comfyui_version: "0.41.0", ram_total: RAM }, devices: [] }));
+ }, delay);
+});
+let comfyUrl = "";
+const reach = { ...REACH };
+
+/** A port nothing listens on: connecting is refused at once. */
+async function closedPort(): Promise<number> {
+ const s = net.createServer();
+ await new Promise<void>((r) => s.listen(0, "127.0.0.1", r));
+ const { port } = s.address() as net.AddressInfo;
+ await new Promise((r) => s.close(r));
+ return port;
+}
+
+/** Forget what the probes found, as a fresh start does. */
+const forget = () => {
+ globalThis.__fuobeComfyReach = undefined;
+ globalThis.__fuobeComfyProbe = undefined;
+};
+
+beforeAll(async () => {
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ comfyUrl = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`;
+ // Checks give up sooner here, so a late answer is quick to make.
+ Object.assign(REACH, { answerMs: 300, connectMs: 1000 });
+ setSetting("demoMode", "auto");
+});
+afterAll(() => {
+ Object.assign(REACH, reach);
+ server.closeAllConnections();
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+beforeEach(() => {
+ delay = 0;
+ status = 200;
+ setSetting("comfyUrl", comfyUrl);
+ forget();
+});
+
+describe("ComfyUI reachability under load", () => {
+ it("a busy server that answered before stays reachable, with its RAM", async () => {
+ expect(await probeComfy(true)).toBe(true);
+ expect(comfyRam()).toBe(RAM);
+ // Busy with a job: the answer comes long after the check gives up.
+ delay = 2000;
+ for (let i = 0; i < 2; i++) expect(await probeComfy(true)).toBe(true);
+ expect(comfyRam()).toBe(RAM);
+ expect(comfyProvider.isConfigured()).toBe(true);
+ // Back to answering: still reachable, and the answer counts again.
+ delay = 0;
+ expect(await probeComfy(true)).toBe(true);
+ expect(globalThis.__fuobeComfyReach?.seen).toBeGreaterThan(Date.now() - 1000);
+ });
+
+ it("a refused port is unreachable at once, in the blocking first check and the background one", async () => {
+ setSetting("comfyUrl", `http://127.0.0.1:${await closedPort()}`);
+ let t0 = Date.now();
+ expect(comfyProvider.isConfigured()).toBe(false);
+ expect(Date.now() - t0).toBeLessThan(1500);
+ t0 = Date.now();
+ expect(await probeComfy(true)).toBe(false);
+ expect(Date.now() - t0).toBeLessThan(500);
+ expect(comfyRam()).toBeUndefined();
+ });
+
+ it("no answer in time is busy when the server answered lately, unreachable when it didn't and its port refuses", async () => {
+ const url = `http://127.0.0.1:${await closedPort()}`;
+ setSetting("comfyUrl", url);
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new DOMException("The operation was aborted due to timeout", "TimeoutError");
+ }) as typeof fetch;
+ try {
+ expect(await probeComfy(true)).toBe(false);
+ // It answered a minute ago: busy, so still reachable.
+ globalThis.__fuobeComfyReach = { ok: true, at: Date.now() - 60_000, url, ram: RAM, seen: Date.now() - 60_000 };
+ expect(await probeComfy(true)).toBe(true);
+ expect(comfyRam()).toBe(RAM);
+ // Its last answer is long past, and nothing takes the connection.
+ globalThis.__fuobeComfyReach = { ok: true, at: Date.now() - 60_000, url, seen: Date.now() - REACH.answeredLatelyMs - 1000 };
+ expect(await probeComfy(true)).toBe(false);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ it("the first check of a slow but alive server says reachable (blocking, then in the background)", async () => {
+ delay = 3000;
+ // The routing question right after start: the server takes the connection while it's busy.
+ const t0 = Date.now();
+ expect(comfyProvider.isConfigured()).toBe(true);
+ expect(Date.now() - t0).toBeLessThan(3000);
+ forget();
+ expect(await probeComfy(true)).toBe(true);
+ // Callers while a check runs share it.
+ forget();
+ asked = 0;
+ expect(await Promise.all([probeComfy(true), probeComfy(true), probeComfy()])).toEqual([true, true, true]);
+ expect(asked).toBe(1);
+ });
+});
+
+describe("a chain step after real ComfyUI steps", () => {
+ const until = async <T>(f: () => T | undefined | null | false, ms = 20_000): Promise<T> => {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ };
+ const clip = () => saveFile({ data: Buffer.from("not really a video"), contentType: "video/mp4", source: "generation" }).url;
+ /** Two clips that ran on ComfyUI, and the join waiting for them. */
+ const join = () => {
+ const ids = ["a", "b"].map((k) => `comfy-clip-${k}-${Math.random().toString(36).slice(2, 8)}`);
+ for (const id of ids) {
+ db()
+ .prepare(
+ `INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, created_at, updated_at, completed_at)
+ VALUES (?, 'canvas', 'oss-fit-clip', 'open', 'comfyui', 'video-fit', 'video', 'succeeded', '{"feature":"canvas","modelId":"oss-fit-clip"}', ?, 'x', ?, ?, ?)`,
+ )
+ .run(id, JSON.stringify([{ url: clip(), kind: "video", contentType: "video/mp4" }]), Date.now(), Date.now(), Date.now());
+ }
+ return gens.createGenerations({ feature: "canvas", modelId: "oss-join-encoded", op: "concat", chain: [{ slot: "videos" }, { slot: "videos" }] }, { dependsOn: ids })[0];
+ };
+ /** A missed check, as a busy server that didn't answer in time left it. */
+ const missed = () => (globalThis.__fuobeComfyReach = { ok: false, at: Date.now(), url: comfyUrl });
+ const launched = (id: string) => until(() => {
+ const g = gens.getGeneration(id)!;
+ return (g.provider === "comfyui" && g.message !== "Waits for the earlier steps") || g.status === "failed" ? g : undefined;
+ });
+
+ it("isn't failed on one missed check: ComfyUI is asked again and the step runs on it", async () => {
+ missed();
+ const g = join();
+ const done = await launched(g.id);
+ expect(done.error ?? "").not.toMatch(/needs ComfyUI to continue/);
+ expect(done.provider).toBe("comfyui");
+ });
+
+ it("waits while ComfyUI doesn't answer, then runs on it when it does", async () => {
+ status = 503;
+ missed();
+ const g = join();
+ const waiting = await until(() => {
+ const x = gens.getGeneration(g.id)!;
+ return x.message === "Waits for ComfyUI to answer" ? x : undefined;
+ });
+ expect(waiting.status).toBe("queued");
+ // Still waiting a few sweeps later.
+ await new Promise((r) => setTimeout(r, 3500));
+ expect(gens.getGeneration(g.id)!.status).toBe("queued");
+ status = 200;
+ expect(await probeComfy(true)).toBe(true);
+ const done = await launched(g.id);
+ expect(done.provider).toBe("comfyui");
+ expect(done.error ?? "").not.toMatch(/needs ComfyUI to continue/);
+ });
+
+ it("fails as before once the wait is over and ComfyUI still doesn't answer", async () => {
+ const wait = gens.COMFY_WAIT.ms;
+ gens.COMFY_WAIT.ms = 1000;
+ try {
+ status = 503;
+ missed();
+ const g = join();
+ const done: Generation = await until(() => {
+ const x = gens.getGeneration(g.id)!;
+ return x.status === "failed" ? x : undefined;
+ });
+ expect(done.error).toMatch(/Join clips \(copy\) needs ComfyUI to continue what the earlier steps made for real/);
+ } finally {
+ gens.COMFY_WAIT.ms = wait;
+ }
+ });
+});