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: model files in subfolders count, and a run goes in line only when a worker has its files
Adarsh713e6c720e08
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 5ac0d739..19175b40 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -251,6 +251,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA// 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 }),+ ...(fresh.expires_at && { tokenExpiresAt: fresh.expires_at }),},};}).immediate();@@ -273,17 +274,42 @@ export function claimableNow(w: WorkerRow, now = Date.now()): number {// ---------------------------------------------------------------------------// Inventory-/** The worker's verified files and node packs: what it can run now, and what each other lane lacks. */+/**+ * A model file's name as a worker reports it: the requirements index's own name for it inside its folder, which may hold+ * subfolders ("bigvgan_vocoder/config.json"), with forward slashes. Never a path that climbs out ("..") or starts at a+ * root or a drive, never a backslash, an empty part or a control character.+ */+const fileNameOk = (name: string) => name.length <= 256 && !/[\\\0-\x1f]|^\/|^[a-z]:|(^|\/)\.{1,2}(\/|$)|\/\/|\/$/i.test(name);++/** The index's files, as "folder/name" (loadIndex keeps one index until its file changes). */+const indexFileKeys = new WeakMap<ReturnType<typeof loadIndex>, Set<string>>();+function knownFiles(): Set<string> {+ const index = loadIndex();+ let keys = indexFileKeys.get(index);+ if (!keys) {+ keys = new Set(Object.values(index.files).map((f) => `${f.folder}/${f.file}`));+ indexFileKeys.set(index, keys);+ }+ return keys;+}++/**+ * The worker's verified files and node packs: what it can run now, and what each other lane lacks. Only the files the+ * requirements index names are kept (by folder and name, subfolders and all), but the hash is of the list as the worker+ * sent it, so it equals the hash the worker computes and the studio asks for the list again only when it changed.+ */export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {const o = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;- const files = (Array.isArray(o.files) ? o.files : []).slice(0, 20_000).flatMap((f) => {+ const sent = (Array.isArray(o.files) ? o.files : []).slice(0, 20_000).flatMap((f) => {const x = f as Record<string, unknown>;const folder = text(x?.folder, 64);- const name = text(x?.name, 256);+ const name = typeof x?.name === "string" && x.name ? x.name : null;const size = num(x?.size);const sha256 = typeof x?.sha256 === "string" && /^[0-9a-f]{64}$/.test(x.sha256) ? x.sha256 : null;- return folder && name && size !== null && !/[\\/]|\.\./.test(name) ? [{ folder, name, size, sha256 }] : [];+ return folder && name && size !== null ? [{ folder, name, size, sha256 }] : [];});+ const known = knownFiles();+ const files = sent.filter((f) => !/[\\/]|\.\./.test(f.folder) && fileNameOk(f.name) && known.has(`${f.folder}/${f.name}`));const nodePacks = (Array.isArray(o.nodePacks) ? o.nodePacks : []).slice(0, 500).flatMap((p) => {const x = p as Record<string, unknown>;const name = text(x?.name, 128);@@ -294,7 +320,7 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; woconst media = Array.isArray(o.media) ? MEDIA_KINDS.filter((k) => (o.media as unknown[]).includes(k)) : undefined;const inv: Inventory = { files, nodePacks, ...(media && { media }) };const r = lanesFor(loadIndex(), inv, sha);- const invHash = inventoryHash(inv);+ const invHash = inventoryHash({ ...inv, files: sent });db().prepare("UPDATE relay_workers SET inventory_json = ?, inventory_hash = ?, lanes_json = ? WHERE id = ?").run(JSON.stringify(inv), invHash, JSON.stringify({ lanes: r.lanes, workflows: r.workflows }), w.id);@@ -704,13 +730,22 @@ export function poolLane(workflowId: string): string {}/**- * Is there a worker for this lane: one the owner added and didn't revoke, allowed the lane (any lane: `lane` null),- * whether it is paused, outside its hours or offline right now (a run then waits in line for it).+ * Is there a worker for this workflow (any workflow: `workflowId` null): one the owner added and didn't revoke, allowed+ * the workflow's lane, and able to run it as its last list of files said (its verified files and node packs, the kinds+ * of input it takes) with the VRAM it needs, whether it is paused, outside its hours or offline right now (a run then+ * waits in line for it). A run that no worker could ever take is refused before Run, never left to wait for nothing.*/-export function workersAllowed(lane: string | null): boolean {+export function workersCanRun(workflowId: string | null): boolean {+ const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;+ const lane = workflowId ? poolLane(workflowId) : null;+ // (Runs made here go to the "pool" pool: poolFields.)return poolWorkers().some((w) => {+ if (w.pool !== "pool") return false;const allow = allowOf(w);- return lane === null ? Object.keys(allow).length > 0 : lane in allow;+ const cap = capableOf(w);+ if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow);+ if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId)) return false;+ return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);});}diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 3c959396..14e811bf 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -5,7 +5,7 @@ import { h3Canvas, isH3Graph } from "@/lib/h3-prompt";import { imageSize } from "@/lib/image-size";import type { GenerationRequest } from "@/lib/catalog/types";import { billingConfigured, type Policy, type QueueFacts, type RunFacts } from "./billing";-import { lineFacts, poolLane, queueOfGeneration, workersAllowed } from "./computer/pool";+import { lineFacts, poolLane, queueOfGeneration, workersCanRun } from "./computer/pool";import { db } from "./db";import { loadIndex } from "./gpu/index-file";import { hostedRunsOn } from "./hosted-switch";@@ -47,15 +47,15 @@ export const poolOnWorkers = (): boolean => getSetting("comfyWhere") === "worker/*** Hosted runs are on, something answers for them (a billing service, or FUOBE_HOSTED_FREE=1), and this install has GPUs- * for them: a worker the owner added and allowed a lane (paused or not: a paused worker means the run waits in line),- * or its own ComfyUI server on this machine.+ * for them: a worker the owner added and allowed a lane that it can run (paused or not: a paused worker means the run+ * waits in line), or its own ComfyUI server on this machine.*/export function poolReady(): boolean {if (!hostedRunsOn()) return false;if (!billingConfigured() && !hostedFree()) return false;const where = getSetting("comfyWhere");if (where === "computer") return false;- return where === "workers" ? workersAllowed(null) : installComfyLocal();+ return where === "workers" ? workersCanRun(null) : installComfyLocal();}/**@@ -70,18 +70,18 @@ export function workflowPicks(endpoint: string): string[] {}/**- * May this install's GPUs run this workflow (planned.route.endpoint)? On the workers: one is allowed its lane (a- * workflow that picks its graph at run time, `…-{n}`: the lane of every graph it may pick). On its own server: the- * isolated ComfyUI's workflows too only when that one is on this machine.+ * May this install's GPUs run this workflow (planned.route.endpoint)? On the workers: one is allowed its lane and has+ * what it needs, as its last list of files said (a workflow that picks its graph at run time, `…-{n}`: every graph it+ * may pick). On its own server: the isolated ComfyUI's workflows too only when that one is on this machine.*/export function poolTakes(endpoint: string | undefined): boolean {if (!endpoint) return false;const isolated = workerFor(endpoint) === "isolated";if (!poolOnWorkers()) return installComfyLocal(isolated ? "isolated" : "main");if (isolated) return false;- if (!endpoint.includes("{")) return workersAllowed(poolLane(endpoint));+ if (!endpoint.includes("{")) return workersCanRun(endpoint);const picks = workflowPicks(endpoint);- return picks.length > 0 && picks.every((id) => workersAllowed(poolLane(id)));+ return picks.length > 0 && picks.every((id) => workersCanRun(id));}/**diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 5fc6139f..492a135c 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -136,7 +136,7 @@ import {type Principal,type TaskRow,} from "../computer/tasks";-import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, workersAllowed } from "../computer/pool";+import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, workersCanRun } from "../computer/pool";import { ownerWaitMs } from "../queue-settings";import { worldcastBase, worldcastHealth } from "../worldcast";@@ -309,7 +309,7 @@ export function installComfyLocal(worker: ComfyWorker = "main"): boolean {export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this machine, so runs of accounts don't go to it.";/** Said to the owner when no worker is allowed the lane of a job sent to the workers. */-export const NO_WORKER_FOR_LANE = "No worker is allowed to run this model yet. Allow its lane for a worker in Settings → Open-source engine · ComfyUI → Workers.";+export const NO_WORKER_FOR_LANE = "No worker can run this model yet. Allow its lane for a worker that has its model files, in Settings → Open-source engine · ComfyUI → Workers.";/*** Every VideoHelperSuite save node of a graph for the workers saves no metadata: the prompt and the machine's own clock never@@ -2856,9 +2856,9 @@ export const comfyProvider: ProviderAdapter = {if (computer) {const metaBatch = !!meta.metaBatch;const forPool = onWorkers(computer);- // The owner's job that no worker is allowed to run would wait with no end (the owner's jobs have no wait limit- // unless the owner sets one): it is refused now, as an account's run is.- if (forPool && computer === "owner" && !workersAllowed(poolLane(manifest.id))) throw new ProviderError(NO_WORKER_FOR_LANE);+ // The owner's job that no worker is allowed and able to run would wait with no end (the owner's jobs have no wait+ // limit unless the owner sets one): it is refused now, as an account's run is.+ if (forPool && computer === "owner" && !workersCanRun(manifest.id)) throw new ProviderError(NO_WORKER_FOR_LANE);const task = createTask({principal: computer,generationId,diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex a5207e99..c687b5dd 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -56,6 +56,7 @@ const { loadManifest, withoutSaveMetadata, planRelayOutputs, onComputer, OWN_OUTconst { accountTotalBytes, accountUsage, diskFloorBytes } = await import("@/server/account-files");const { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");+const { getModel } = await import("@/lib/catalog");const { ComputerRunner } = await import("@/lib/computer-runner");const { POOL_WORDS } = await import("@/lib/relay");const { ACCOUNT_MESSAGES } = await import("@/server/account-files");@@ -317,6 +318,23 @@ describe("an account's run on the workers", () => {expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);});+ it("refuses a run whose lane a worker is allowed but whose files no worker has, before anything is queued", async () => {+ const w = standInWorker();+ const endpoint = getModel("oss-z-image-turbo")!.routes.find((x) => x.provider === "comfyui")!.endpoint;+ const workflows = loadManifest().workflows.map((x) => x.id);+ const lanesNow = JSON.parse(workerRow(w).lanes_json ?? "{}") as { lanes: string[] };+ // Allowed every lane, but its last list of files lacks this workflow's: nothing it could ever run.+ db().prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?").run(JSON.stringify({ lanes: [], workflows: workflows.filter((x) => x !== endpoint) }), w.id);+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });+ expect(r.status, JSON.stringify(r.body)).toBe(403);+ expect(r.body.code).toBe("not-offered");+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);+ // Its files are there again: the run goes in line.+ db().prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?").run(JSON.stringify({ ...lanesNow, workflows }), w.id);+ expect((await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" })).status).toBe(201);+ });+it("a file input in params.extra is one the run sent, never a name in the workers' folders", async () => {standInWorker();const uploadsRoute = await import("@/app/api/uploads/route");diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.tsindex 6ec5ad81..d14cf0c0 100644--- a/tests/workers-pool.test.ts+++ b/tests/workers-pool.test.ts@@ -499,6 +499,83 @@ describe("a worker whose model folder isn't there yet (a drive still locked afte});});+describe("a worker's list of model files", () => {+ const inventoryRoute = () => import("@/app/api/gpu/computer/inventory/route");+ const beatWith = (w: W, inventoryHash: string | null) =>+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash, running: [], stopped: [] }), clock);+ const put = async (w: W, body: unknown) => {+ 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(body) }));+ return { status: res.status, body: (await res.json()) as { lanes?: string[]; workflows?: string[] } };+ };+ const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+ /** A workflow whose files sit in subfolders of their model folder ("audio_vae/bigvgan_vocoder/config.json"), and every workflow of its lane. */+ const nested = () => {+ const index = loadIndex();+ const id = Object.keys(index.workflows).find((x) => !index.workflows[x].isolated && index.workflows[x].files.includes("audio_vae/bigvgan_vocoder/config.json"))!;+ const lane = laneOf(index, id, sha)!;+ const all = Object.keys(index.workflows).filter((x) => !index.workflows[x].isolated && laneOf(index, x, sha) === lane);+ const needs = all.map((x) => needsOf(index, x)!);+ const files = [...new Map(needs.flatMap((n) => n.files).map((f) => [`${f.folder}/${f.name}`, { ...f, sha256: f.sha256 ?? "0".repeat(64) }])).values()];+ const nodePacks = [...new Set(needs.flatMap((n) => n.packs))].map((name) => ({ name, commit: null }));+ return { id, lane, files, nodePacks, minVram: Math.max(...needs.map((n) => n.minVramBytes)) };+ };+ /** A pool worker the owner allowed `lanes`, with `vram`, that has sent no list of files yet. */+ const bare = (name: string, lanes: string[], vram: number) => {+ const w = pool.addWorker(name);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });+ db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify({ vramBytes: vram }), w.id);+ return w;+ };++ it("keeps the index's files in subfolders, so its hash is the worker's: one list is enough, and their lane counts", async () => {+ const { inventoryHash: workerInventoryHash } = await import("../bin/lib/worker/inventory.mjs");+ const n = nested();+ expect(n.files.some((f) => f.name.includes("/"))).toBe(true);+ const w = bare("nested-files", [n.lane], n.minVram + GB);+ // Allowed the lane, but no list of files yet: nothing it could run, so no run is let in for it.+ expect(pool.workersCanRun(n.id)).toBe(false);+ const inv = { files: n.files.map(({ folder, name, size, sha256 }) => ({ folder, name, size, sha256 })), nodePacks: n.nodePacks, media: ["image", "video", "audio"] };+ expect(beatWith(w, workerInventoryHash(inv)).worker.sendInventory).toBe(true);+ const r = await put(w, inv);+ expect(r.status).toBe(200);+ expect(r.body.workflows).toContain(n.id);+ expect(r.body.lanes).toContain(n.lane);+ expect(JSON.parse(row(w).lanes_json ?? "{}").lanes).toContain(n.lane);+ // The studio's hash of what it was sent is the worker's own: the next beat asks for no list again.+ expect(row(w).inventory_hash).toBe(workerInventoryHash(inv));+ expect(beatWith(w, workerInventoryHash(inv)).worker.sendInventory).toBe(false);+ expect(pool.workersCanRun(n.id)).toBe(true);+ // Too little VRAM for it: no run is let in.+ db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify({ vramBytes: n.minVram - GB }), w.id);+ expect(pool.workersCanRun(n.id)).toBe(false);+ });++ it("drops a name that climbs out, starts at a root or a drive, uses backslashes, or isn't in the index; its hash is still of what was sent", async () => {+ const { inventoryHash: workerInventoryHash } = await import("../bin/lib/worker/inventory.mjs");+ const n = nested();+ const w = bare("odd-names", [n.lane], n.minVram + GB);+ const good = n.files.map(({ folder, name, size, sha256 }) => ({ folder, name, size, sha256 }));+ const odd = [+ { folder: "audio_vae", name: "../loras/x.safetensors", size: 1, sha256: null },+ { folder: "audio_vae", name: "bigvgan_vocoder/../../x.json", size: 1, sha256: null },+ { folder: "audio_vae", name: "/etc/passwd", size: 1, sha256: null },+ { folder: "audio_vae", name: "C:/Windows/x.dll", size: 1, sha256: null },+ { folder: "audio_vae", name: "bigvgan_vocoder\\config.json", size: 1, sha256: null },+ { folder: "audio_vae", name: "bigvgan_vocoder//config.json", size: 1, sha256: null },+ { folder: "audio_vae", name: "not-in-the-index/model.safetensors", size: 1, sha256: null },+ { folder: "../audio_vae", name: "bigvgan_vocoder/config.json", size: 1, sha256: null },+ ];+ const inv = { files: [...good, ...odd], nodePacks: n.nodePacks, media: ["image", "video", "audio"] };+ const r = await put(w, inv);+ expect(r.status).toBe(200);+ expect(r.body.workflows).toContain(n.id);+ const kept = JSON.parse(row(w).inventory_json ?? "{}") as { files: { folder: string; name: string }[] };+ expect(kept.files.map((f) => `${f.folder}/${f.name}`).sort()).toEqual(good.map((f) => `${f.folder}/${f.name}`).sort());+ expect(beatWith(w, workerInventoryHash(inv)).worker.sendInventory).toBe(false);+ });+});+describe("routes", () => {it("the beat's answer carries claimableNow", async () => {clock = Date.now();