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 model folder that isn't there yet shows as its own state, and the worker's lanes stay
Adarsh6ea56ea33f00
diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjsindex 666ab83d..bae3d31d 100644--- a/bin/lib/worker/inventory.mjs+++ b/bin/lib/worker/inventory.mjs@@ -162,8 +162,26 @@ export function comfyModelDirs(comfyDir, env = process.env, home = os.homedir())};}+/**+ * The model folders that aren't there now: each one must be a folder the worker can read. A drive that is still locked+ * or not yet connected after a restart makes its folder missing, and the worker then waits for it (run.mjs) instead of+ * telling the studio it lacks those files.+ */+export function missingModelDirs(modelDirs) {+ const readable = (dir) => {+ try {+ if (!fs.statSync(dir).isDirectory()) return false;+ fs.readdirSync(dir);+ return true;+ } catch {+ return false;+ }+ };+ return (modelDirs ?? []).filter((dir) => !readable(dir));+}+/** The same file, by its full path (whatever its case on Windows). */-const samePath = (a, b) => (process.platform === "win32" ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));+const samePath =(a, b) => (process.platform === "win32" ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));/*** The verified files: for every file the catalog names with a pinned SHA-256 (`pins`, else the index's own), the copydiff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 8331ae23..0c86d02a 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -22,7 +22,7 @@ import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";import { ffmpegOf, PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";import { Hold } from "./hold.mjs";-import { inventoryHash, modelFiles, packFolders } from "./inventory.mjs";+import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";import { takeLock, workerLives } from "./lock.mjs";import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";@@ -50,6 +50,12 @@ 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;+/**+ * It checks that every model folder is there this often. While one isn't (a drive still locked, or not connected yet+ * after a restart), it takes no new job and keeps the studio's list of its files as it was.+ */+export const MODELS_CHECK_MS = 60_000;+/** Kept results that the studio hasn't taken for this long are deleted (the studio drops its jobs after a day). */export const HOLD_MAX_AGE_MS = 24 * HOUR;@@ -106,13 +112,15 @@ export function siteProblem(site, o = {}) {}/**- * The worker's local pause, from its switch (`worker pause`), the GPU, and its ComfyUI: { paused, why, until }.- * A pause by hand ("here", "here-until:<ms>", "here-now") always wins over the GPU's.+ * The worker's local pause, from its switch (`worker pause`), the GPU, its model folders (`modelsMissing`: the ones that+ * aren't there) and its ComfyUI: { paused, why, until }. A pause by hand ("here", "here-until:<ms>", "here-now") always+ * wins over the GPU's.*/-export function localPause(control, gpu, comfyTrouble, now) {+export function localPause(control, gpu, comfyTrouble, now, modelsMissing = []) {if (control.paused && control.until && now >= control.until) return null; // its --for ran out: the caller clears itif (control.paused) return { paused: true, why: control.now ? "here-now" : control.until ? `here-until:${control.until}` : "here", until: control.until ?? null };if (gpu.paused) return { paused: true, why: `gpu-busy:${gpu.who ?? "another program"}`, until: null };+ if (modelsMissing.length) return { paused: true, why: "models-not-ready", until: null };if (comfyTrouble) return { paused: true, why: comfyTrouble, until: null };return { paused: false, why: null, until: null };}@@ -285,6 +293,13 @@ async function work(saved, deps, owner) {scannedAt = now();}));await scan();+ // A model folder that isn't there yet: no new job, and no list of files that lacks its files, until it is.+ let modelsMissing = missingModelDirs(cfg.modelDirs);+ let modelsCheckedAt = now();+ let modelsBack = null;+ const sayMissing = (missing) =>+ log(`${missing.length === 1 ? "A model folder isn't" : `${missing.length} model folders aren't`} there yet (${missing.join(", ")}): it takes no new job until ${missing.length === 1 ? "it is" : "they are"}, and looks again every minute.`);+ if (modelsMissing.length) sayMissing(modelsMissing);/** An input for its ComfyUI: read from the studio once, kept by its SHA-256, and a clip or sound made again. */async function takeInput(t, input, read) {@@ -416,21 +431,23 @@ async function work(saved, deps, owner) {const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;const state = () =>- pause.paused- ? `Paused here (${pause.why})`- : !answer- ? "Connecting"- : answer.worker?.paused- ? "Paused on the website"- : !answer.worker?.insideHours- ? "Outside its hours"- : answer.worker?.drain- ? "Finishing, then pausing"- : turn.waitForYield- ? "Waiting for local ComfyUI work to make room (its jobs keep their place)"- : comfy.ready- ? "Ready"- : "Starting ComfyUI";+ pause.why === "models-not-ready"+ ? "Waiting for its model folders"+ : pause.paused+ ? `Paused here (${pause.why})`+ : !answer+ ? "Connecting"+ : answer.worker?.paused+ ? "Paused on the website"+ : !answer.worker?.insideHours+ ? "Outside its hours"+ : answer.worker?.drain+ ? "Finishing, then pausing"+ : turn.waitForYield+ ? "Waiting for local ComfyUI work to make room (its jobs keep their place)"+ : comfy.ready+ ? "Ready"+ : "Starting ComfyUI";// A job that runs on its ComfyUI (not only sending kept results, which needs no GPU).let jobUsesGpu = false;const take = (o) => {@@ -523,7 +540,22 @@ async function work(saved, deps, owner) {log("Its ComfyUI stopped answering: starting it again.");await comfy.stop();}- let next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };+ if (!modelsBack && t - modelsCheckedAt >= (deps.modelsCheckMs ?? MODELS_CHECK_MS)) {+ modelsCheckedAt = t;+ const missing = missingModelDirs(cfg.modelDirs);+ if (missing.length && !modelsMissing.length) {+ sayMissing(missing);+ modelsMissing = missing;+ } else if (!missing.length && modelsMissing.length) {+ // Its files are read again first, so the studio gets the whole list before it takes a job.+ log("Its model folders are all there: looking at them again.");+ modelsBack = rescan().finally(() => {+ modelsMissing = missingModelDirs(cfg.modelDirs);+ modelsBack = null;+ });+ } else modelsMissing = missing;+ }+ let next = localPause(control, gpu, comfyTrouble, t, modelsMissing) ?? { paused: false, why: null, until: null };// Waiting for its turn is not a pause: its jobs keep their place in the line. The helper's estimate of the start// goes with it.if (!next.paused && turn.waitForYield) next = { paused: false, why: turn.late ? "waiting-for-yield:no-answer" : "waiting-for-yield", until: turn.startsAt };@@ -540,7 +572,7 @@ async function work(saved, deps, owner) {log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");break;}- if (a?.worker?.sendInventory) {+ if (a?.worker?.sendInventory && !modelsMissing.length) {const r = await call("/api/gpu/computer/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });if (r.ok) {const body = await r.json();@@ -552,7 +584,7 @@ async function work(saved, deps, owner) {}}// Its model folders, again every 10 minutes (in the background: beats go on while it hashes a new file).- if (t - scannedAt >= (deps.rescanMs ?? RESCAN_MS) && !scanning) void rescan();+ if (t - scannedAt >= (deps.rescanMs ?? RESCAN_MS) && !scanning && !modelsMissing.length) void rescan();// Its own ComfyUI runs only while it may work; a pause (and a stop-now) frees the GPU.const stopNow = (pause.paused && (pause.why === "here-now" || pause.why?.startsWith("gpu-busy"))) || answer?.worker?.pauseNow;// Studio jobs first: the turn, from what the beat said and what holds the GPU; site.json on every beat, on a change,diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 7117c39d..fcccc6b7 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -463,6 +463,11 @@ The worker keeps its jobs going by itself:screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.- **Its model folders are read again** every 10 minutes, and whenever a job needs a model file that the worker has notfound yet. A drive that comes back after a restart is noticed, and the studio gets the new list.+- **A model folder that isn't there yet** (a drive that is still locked or not connected after a restart) pauses the+ worker by itself (`local.why: "models-not-ready"`). Settings → Workers shows "Waiting for its model folders", and+ the worker's lanes stay as they were: the studio asks for no list of files meanwhile, and refuses one with 409. The+ worker checks its folders every minute. Once they are all there, it reads them again, sends the new list, and takes+ jobs again. A job already running goes on.- **When the studio stops the worker.** If the studio no longer knows the worker's token, `fuobe worker run` ends withexit code 3; any other stop that you did not ask for ends with exit code 1. The sign-in task that`fuobe worker install` adds then starts the worker again after a minute. Ctrl+C ends with 0. On Ctrl+C, and on adiff --git a/src/app/api/gpu/computer/inventory/route.ts b/src/app/api/gpu/computer/inventory/route.tsindex e3de5ad1..dcbb2317 100644--- a/src/app/api/gpu/computer/inventory/route.ts+++ b/src/app/api/gpu/computer/inventory/route.ts@@ -1,5 +1,5 @@import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";-import { saveInventory } from "@/server/computer/pool";+import { MODELS_NOT_READY, saveInventory } from "@/server/computer/pool";/** What an inventory may weigh: 20,000 files with their names and hashes. */const MAX_BYTES = 8 * 2 ** 20;@@ -13,6 +13,8 @@ export async function PUT(request: Request) {if (principal instanceof Response) return principal;const worker = requestWorker(request);if (worker?.kind !== "pool") return Response.json({ error: "Only a worker sends its files" }, { status: 403 });+ // A model folder of its isn't there yet: the list it has now lacks those files, so the last one stands.+ if (worker.paused_local && worker.local_why === MODELS_NOT_READY) return Response.json({ error: "Its model folders aren't all there yet. Its last list of files stays." }, { status: 409, headers: { "Cache-Control": "no-store" } });const limited = rateOf(callerKey(request, principal), "inventory", 6);if (limited) return limited;const text = await request.text().catch(() => "");diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 39e1cf6d..680bbbbd 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -217,7 +217,7 @@ export interface WorkerBeat {why: string | null;/*** Its own pause switch: by hand ("here", "here-until:<ms>", "here-now"), by itself ("gpu-busy:<process>",- * "comfy-crashes", "port-busy"). Not paused, `why` may say that it+ * "comfy-crashes", "port-busy", "models-not-ready": a model folder isn't there yet). Not paused, `why` may say that it* waits for local ComfyUI work to make room ("waiting-for-yield", "waiting-for-yield:no-answer").*/local: { paused: boolean; why: string | null; until: number | null };diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 9fce48cb..85b38948 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -22,6 +22,8 @@ import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRo* every input against its rules, and keeps its ComfyUI behind the guard. An older one is told to update.*/export const MIN_PROTOCOL = 2;+/** A worker's own pause while a model folder of its isn't there yet: it keeps its last list of files. */+export const MODELS_NOT_READY = "models-not-ready";/** A task avoids workers that lost or failed it, unless no other worker that can run it beat this recently. */export const RETRY_WINDOW_MS = 10 * 60_000;/** Attempts in all before a task fails. */@@ -79,7 +81,7 @@ const factsOf = (w: WorkerRow) => json<ComputerFacts>(w.facts_json, {});const hoursOf = (w: WorkerRow): Hours | null => parseHours(json<unknown>(w.hours_json, null));const benchOf = (w: WorkerRow) => json<Record<string, { medianMs?: number; p90Ms?: number; loadMs?: number; peakVramBytes?: number }>>(w.bench_json, {});-export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "waiting-for-yield" | "offline";+export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "models-not-ready" | "waiting-for-yield" | "offline";/** The state in one word, and in words for the owner ("Paused here until 16:30", "Your GPU is busy (blender.exe)"). */export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerState; words: string } {@@ -92,6 +94,8 @@ export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerStatif (why.startsWith("gpu-busy")) return { state: "gpu-busy", words: `Your GPU is busy${why.includes(":") ? ` (${why.split(":").slice(1).join(":")})` : ""}` };if (why === "comfy-crashes") return { state: "comfy-down", words: "ComfyUI keeps stopping" };if (why === "port-busy") return { state: "comfy-down", words: "Its ComfyUI port is taken by another program" };+ // A model folder isn't there yet (a drive still locked after a restart): it waits for it, with its lanes as they were.+ if (why === MODELS_NOT_READY) return { state: "models-not-ready", words: "Waiting for its model folders" };return { state: "paused", words: w.local_until ? `Paused here until ${clock(w.local_until, tz)}` : "Paused here" };}if (w.paused_server) return { state: "paused", words: "Paused on the website" };@@ -224,7 +228,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAnextChangeAt: h.nextChangeAt,lanes: Object.keys(allowOf(fresh)),minProtocol: MIN_PROTOCOL,- sendInventory: !fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash,+ // While a model folder isn't there, the studio keeps the list it has (its lanes don't go missing meanwhile).+ sendInventory: b.local.why !== MODELS_NOT_READY && (!fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash),...(nextToken && { token: nextToken }),},};diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.tsindex ee30ebcb..fc818095 100644--- a/tests/worker-program.test.ts+++ b/tests/worker-program.test.ts@@ -8,7 +8,7 @@ import { comfyArgs, OwnComfy, PortBusy, portFree } from "../bin/lib/worker/comfyimport { parseFor, syncedFolder } from "../bin/lib/worker/config.mjs";import { worker } from "../bin/lib/worker/index.mjs";import { localPause } from "../bin/lib/worker/run.mjs";-import { inventoryHash as workerHash } from "../bin/lib/worker/inventory.mjs";+import { inventoryHash as workerHash, missingModelDirs } from "../bin/lib/worker/inventory.mjs";import { tempDir } from "./helpers/temp-dir";const MIN = 60_000;@@ -66,6 +66,19 @@ describe("the GPU check (check 11)", () => {expect(localPause({ paused: false }, { paused: true, who: "blender.exe" }, null, 0)?.why).toBe("gpu-busy:blender.exe");expect(localPause({ paused: true, now: true }, free, null, 0)?.why).toBe("here-now");expect(localPause({ paused: false }, free, "port-busy", 0)).toEqual({ paused: true, why: "port-busy", until: null });+ // A model folder that isn't there yet: after a pause by hand and a busy GPU, before its ComfyUI's trouble.+ expect(localPause({ paused: false }, free, "port-busy", 0, ["X:/models"])).toEqual({ paused: true, why: "models-not-ready", until: null });+ expect(localPause({ paused: false }, { paused: true, who: "game.exe" }, null, 0, ["X:/models"])?.why).toBe("gpu-busy:game.exe");+ expect(localPause({ paused: true }, free, null, 0, ["X:/models"])?.why).toBe("here");+ expect(localPause({ paused: false }, free, null, 0, [])).toEqual({ paused: false, why: null, until: null });+ });++ it("a model folder that can't be read counts as missing; a folder that is there doesn't", () => {+ const base = tempDir("fuobe-model-dirs-");+ const file = path.join(base, "a-file");+ fs.writeFileSync(file, "x");+ expect(missingModelDirs([base, path.join(base, "not-yet"), file])).toEqual([path.join(base, "not-yet"), file]);+ expect(missingModelDirs(undefined)).toEqual([]);});it("--for 2h ends by itself after 2 hours (check 10)", () => {diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.tsindex aa490f6c..bf0695b2 100644--- a/tests/worker-recovery.test.ts+++ b/tests/worker-recovery.test.ts@@ -12,6 +12,8 @@* - 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.+ * - A model folder that isn't there yet (a drive still locked after a restart): the worker waits for it, says so, and+ * sends no list of files meanwhile; once the folder is there, the waiting job is taken within one look.*/import { spawnSync } from "node:child_process";import crypto from "node:crypto";@@ -154,7 +156,7 @@ 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[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number } = {},+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number } = {},) {const ctrl = new AbortController();const cfg = {@@ -193,6 +195,7 @@ function start(p.logAt.push(Date.now());},...(o.rescanMs && { rescanMs: o.rescanMs }),+ ...(o.modelsCheckMs && { modelsCheckMs: o.modelsCheckMs }),});const r = { ctrl, done };running.push(r);@@ -598,4 +601,28 @@ describe("its model folders", () => {const seen = await until(() => s.inventories.find((i) => (i.files as unknown[]).length > 0), 60_000);expect(seen.files).toEqual([{ folder: "loras", name: "late.safetensors", size: 5, sha256: sha }]);});++ it("a model folder that isn't there yet: it waits for it with its lanes kept, then takes the waiting job within one look", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const drive = path.join(tempDir("fuobe-worker-drive-"), "models");+ const { id } = addTask();+ start(w, s, p, { modelDirs: [drive], modelsCheckMs: 300 });+ const workerRow = () => db().prepare("SELECT paused_local, local_why, state FROM relay_workers WHERE id = ?").get(w.id) as { paused_local: number; local_why: string | null; state: string };+ await until(() => workerRow().local_why === "models-not-ready");+ expect(workerRow()).toMatchObject({ paused_local: 1, state: "models-not-ready" });+ expect(p.logs.some((l) => /A model folder isn't there yet/.test(l))).toBe(true);+ // A few beats later: still waiting, its job still in line, and no list of files that lacks the folder's.+ await sleep(1_500);+ expect(state(id).state).toBe("waiting");+ expect(s.inventories).toEqual([]);+ expect(prompts(p)).toBe(0);+ // The drive is unlocked: within one look its files are read again, and the job runs.+ fs.mkdirSync(drive, { recursive: true });+ const done = await ended(id);+ expect(done.state).toBe("done");+ expect(s.inventories.length).toBeGreaterThan(0);+ expect(p.logs.some((l) => /model folders are all there/.test(l))).toBe(true);+ });});diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.tsindex d0f24d7d..e54afd71 100644--- a/tests/workers-pool.test.ts+++ b/tests/workers-pool.test.ts@@ -407,6 +407,36 @@ describe("a worker waiting for local ComfyUI work to make room", () => {});});+describe("a worker whose model folder isn't there yet (a drive still locked after a restart)", () => {+ const inventoryRoute = () => import("@/app/api/gpu/computer/inventory/route");+ const beatWith = (w: W, local: { paused: boolean; why: string | null }, inventoryHash: string | null) =>+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { ...local, until: null }, gpu: {}, inventoryHash, running: [], stopped: [] }), clock);++ it("shows its own state, takes nothing, and keeps its lanes: no list of files is asked for or taken meanwhile", async () => {+ const w = worker("models-later", { lanes: [LANE_A] });+ db().prepare("UPDATE relay_workers SET inventory_hash = 'before' WHERE id = ?").run(w.id);+ const id = task({ account: "acct-1" });+ const a = beatWith(w, { paused: true, why: "models-not-ready" }, "a-shorter-list");+ expect(pool.workerState(row(w), clock)).toEqual({ state: "models-not-ready", words: "Waiting for its model folders" });+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)).toMatchObject({ state: "models-not-ready", words: "Waiting for its model folders", lanes: [LANE_A] });+ expect(a.runner).toBe(false);+ expect(a.worker.sendInventory).toBe(false);+ expect(a.worker.pauseNow).toBe(false);+ expect(claim(w)).toBeNull();+ expect(state(id).state).toBe("waiting");+ // A list sent anyway is refused, and the lanes stay as they were.+ const { PUT } = await inventoryRoute();+ const res = await PUT(new Request("http://localhost:3000/api/gpu/computer/inventory", { method: "PUT", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify({ files: [], nodePacks: [] }) }));+ expect(res.status).toBe(409);+ expect(JSON.parse(row(w).lanes_json ?? "{}").lanes).toEqual([LANE_A]);+ // The folder is back: the studio asks for the list again, and the run is taken.+ const back = beatWith(w, { paused: false, why: null }, "the-whole-list");+ expect(back.worker.sendInventory).toBe(true);+ expect(pool.workerState(row(w), clock).state).toBe("idle");+ expect(claim(w)?.id).toBe(id);+ });+});+describe("routes", () => {it("the beat's answer carries claimableNow", async () => {clock = Date.now();