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 file counts only when its SHA-256 matches its pin
Adarsh24d0c268a9c5
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex 40868f1b..9196d39b 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -30,7 +30,7 @@ export async function worker(args, io) {io.stderr.write("This worker isn't set up yet. Run: fuobe worker setup\n");return 2;}- if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json"].every((f) => fs.existsSync(path.join(here, "dist", f)))) {+ if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"].every((f) => fs.existsSync(path.join(here, "dist", f)))) {io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");return 2;}diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjsindex 9c5a52d5..68a73f8c 100644--- a/bin/lib/worker/inventory.mjs+++ b/bin/lib/worker/inventory.mjs@@ -1,11 +1,23 @@// What this worker has (docs/gpu-workers.md): the model files in its model folders that the studio's catalog names,-// each checked by folder, name and exact size, and by SHA-256 where the catalog pins one; and its ComfyUI's node packs-// with their commits. Hashes are cached by path, size and modified time, so a restart doesn't read hundreds of GB again.+// each checked by folder, name, exact size and SHA-256 (every file the catalog names has its hash pinned in the+// worker's build: dist/file-pins.json); and its ComfyUI's node packs with their commits. Hashes are cached by path,+// size and modified time, so a restart doesn't read hundreds of GB again.import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";+import { fileURLToPath } from "node:url";-const KINDS = /\.(safetensors|gguf)$/i;+const here = path.dirname(fileURLToPath(import.meta.url));++/** The SHA-256 of every model file the catalog names ("folder/file" → hex), built into this worker. */+export function filePins(file = path.join(here, "dist", "file-pins.json")) {+ try {+ const p = JSON.parse(fs.readFileSync(file, "utf8")).files;+ return p && typeof p === "object" ? p : {};+ } catch {+ return {};+ }+}function sha256File(file) {return new Promise((resolve, reject) => {@@ -60,9 +72,10 @@ function gitCommit(dir) {/*** The verified files: for every file the catalog names, found in one of the model folders under its folder with the- * exact size (and the pinned SHA-256, when there is one). A file of the wrong size isn't reported at all.+ * exact size and its pinned SHA-256 (`pins`, else the index's own). A file with no pinned hash, of the wrong size or+ * with another hash isn't reported at all, so no job that needs it comes here.*/-export async function modelFiles(modelDirs, index, cacheFile) {+export async function modelFiles(modelDirs, index, cacheFile, pins = filePins()) {const cache = (() => {try {return JSON.parse(fs.readFileSync(cacheFile, "utf8"));@@ -72,7 +85,8 @@ export async function modelFiles(modelDirs, index, cacheFile) {})();const out = [];for (const f of Object.values(index.files ?? {})) {- if (!KINDS.test(f.file) && !(f.sha256 && /\.pth$/i.test(f.file))) continue;+ const want = pins[`${f.folder}/${f.file}`] ?? f.sha256;+ if (typeof want !== "string" || !/^[0-9a-f]{64}$/.test(want)) continue;for (const root of modelDirs ?? []) {const p = path.join(root, f.folder, f.file);let st;@@ -82,12 +96,9 @@ export async function modelFiles(modelDirs, index, cacheFile) {continue;}if (!st.isFile() || st.size !== f.sizeBytes) continue;- let sha = null;- if (f.sha256) {- const key = `${p}|${st.size}|${st.mtimeMs}`;- sha = cache[key] ?? (cache[key] = await sha256File(p));- if (sha !== f.sha256) continue;- }+ const key = `${p}|${st.size}|${st.mtimeMs}`;+ const sha = cache[key] ?? (cache[key] = await sha256File(p));+ if (sha !== want) continue;out.push({ folder: f.folder, name: f.file, size: st.size, sha256: sha });break;}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 8df3b199..b628cde1 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -40,8 +40,8 @@ export function localPause(control, gpu, comfyTrouble, now) {}/**- * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner, rules }- * (rules: the built input rules, read from dist/ when not given).+ * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner, rules, pins }+ * (rules and pins: the built input rules and file hashes, read from dist/ when not given).*/export async function runWorker(cfg, deps) {const now = deps.now ?? Date.now;@@ -74,7 +74,7 @@ export async function runWorker(cfg, deps) {async function scan() {packs = packFolders(cfg.comfyDir, index);- inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json")), nodePacks: packs.map(({ name, commit }) => ({ name, commit })) };+ inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins), nodePacks: packs.map(({ name, commit }) => ({ name, commit })) };invHash = inventoryHash(inv);}await scan();diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex ad8bbcb2..f7cbedd6 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -164,6 +164,11 @@ Before its ComfyUI gets a graph, the worker checks all of these. The studio cann5. Every model file that the graph names is one that the worker verified, by its exact name. A file with the samename in another folder does not count.+The worker reports a model file only when its SHA-256 matches the hash that the catalog pins for it+(`bin/lib/worker/dist/file-pins.json`, from `requirements.json` and `model-pins.json`). A file that has no pinned hash+is not reported, so no job that needs it comes to the worker. The worker keeps the hashes it computed, so a restart+does not read the files again.+After each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from itsComfyUI's history. At start, it empties its folders.diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjsindex d91de2c9..12af82aa 100644--- a/scripts/build-worker.mjs+++ b/scripts/build-worker.mjs@@ -6,13 +6,15 @@// studio can't add to it; a worker refuses a graph with any other node;// - input-rules.json: a rule for each node input that could name a file, a folder, a download or code, from the// catalog's own values (scripts/lib/worker-catalog.mjs). A worker refuses a value outside its rule, and a link-// into it.+// into it;+// - file-pins.json: the SHA-256 of every model file the catalog names. A worker reports a file only when its own+// hash matches.// `pnpm build` runs it first. No new dependency.import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import ts from "typescript";-import { allowedNodeList, inputRules, missingRules, readCatalog } from "./lib/worker-catalog.mjs";+import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./lib/worker-catalog.mjs";const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");const out = path.join(root, "bin/lib/worker/dist");@@ -38,5 +40,7 @@ const rules = inputRules(catalog);const missing = missingRules(rules, nodes);if (missing.length) throw new Error(`These allowed inputs have no rule: ${missing.join(", ")}. Give each a literal value in the catalog.`);write("input-rules.json", rules);+const pins = filePins(catalog);+write("file-pins.json", { files: pins });const ruled = Object.values(rules.inputs).reduce((n, r) => n + Object.keys(r).length, 0);-console.log(`worker: ${SOURCES.length} modules, ${nodes.length} allowed node types, ${ruled} input rules -> ${path.relative(root, out)}`);+console.log(`worker: ${SOURCES.length} modules, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes -> ${path.relative(root, out)}`);diff --git a/scripts/lib/worker-catalog.mjs b/scripts/lib/worker-catalog.mjsindex 757d433d..5e879e61 100644--- a/scripts/lib/worker-catalog.mjs+++ b/scripts/lib/worker-catalog.mjs@@ -4,13 +4,14 @@// - allowedNodes: every node type the catalog's workflows and the graph builders use.// - inputRules: a rule for each node input that could name a file, a folder, a download or code, taken from the// catalog's own values. The worker refuses a value outside its rule, and a link from another node into it.+// - filePins: the SHA-256 of every model file the catalog names, from requirements.json and model-pins.json.import fs from "node:fs";import path from "node:path";import { loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, valueProblem } from "../../bin/lib/worker/rules.mjs";const SKIP = new Set(["requirements.json", "manifest.json", "model-pins.json"]);-/** The catalog: its workflow graphs by file name, its manifest and its requirement index. */+/** The catalog: its workflow graphs by file name, its manifest, its requirement index and its model pins. */export function readCatalog(root) {const dir = path.join(root, "workflows/comfyui");const read = (f) => JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));@@ -21,7 +22,8 @@ export function readCatalog(root) {graphs[f] = read(f);} catch {}}- return { graphs, manifest: read("manifest.json"), requirements: read("requirements.json") };+ const pinsFile = path.join(dir, "model-pins.json");+ return { graphs, manifest: read("manifest.json"), requirements: read("requirements.json"), pins: fs.existsSync(pinsFile) ? read("model-pins.json") : {} };}const nodesOf = (graph) => Object.entries(graph ?? {}).filter(([, n]) => n && typeof n === "object" && typeof n.class_type === "string");@@ -185,3 +187,13 @@ export function missingRules(rules, allowed) {return REQUIRED_RULES.filter(([cls, input]) => allowed.includes(cls) && !rules.inputs[cls]?.[input]).map(([cls, input]) => `${cls}.${input}`);}+/** The SHA-256 of every model file the catalog names ("folder/file" → hex), from its index or its model pins. */+export function filePins(catalog) {+ const pins = catalog.pins ?? {};+ const out = {};+ for (const f of Object.values(catalog.requirements.files ?? {})) {+ const sha = f.sha256 ?? pins[f.url]?.sha256 ?? pins[f.pinnedUrl]?.sha256;+ if (typeof sha === "string" && /^[0-9a-f]{64}$/.test(sha)) out[`${f.folder}/${f.file}`] = sha;+ }+ return Object.fromEntries(Object.keys(out).sort().map((k) => [k, out[k]]));+}diff --git a/tests/worker-environment.test.ts b/tests/worker-environment.test.tsindex 871b7cee..ee6de1b3 100644--- a/tests/worker-environment.test.ts+++ b/tests/worker-environment.test.ts@@ -1,14 +1,17 @@+import crypto from "node:crypto";import fs from "node:fs";import net from "node:net";import path from "node:path";import { describe, expect, it } from "vitest";import { inputRules } from "../bin/lib/worker/checks.mjs";import { comfyArgs, comfyEnv, OFFLINE_ENV, OwnComfy } from "../bin/lib/worker/comfy.mjs";-import { nodePacks, packFolders } from "../bin/lib/worker/inventory.mjs";+import { modelFiles, nodePacks, packFolders } from "../bin/lib/worker/inventory.mjs";import { minVramBytesFor, needsOf, VRAM_TOLERANCE } from "@/lib/lanes";import type { RequirementIndex } from "@/lib/gpu/types";import { tempDir } from "./helpers/temp-dir";+const sha = (data: string) => crypto.createHash("sha256").update(data).digest("hex");+/** A port nothing listens on (the system picks it). */const freePort = () =>new Promise<number>((resolve) => {@@ -40,6 +43,35 @@ describe("the worker's node packs", () => {});});+describe("the worker's model files", () => {+ it("reports a file only when its SHA-256 matches the pinned one, whatever its size says", async () => {+ const models = tempDir("fuobe-worker-models-");+ fs.mkdirSync(path.join(models, "loras"));+ fs.mkdirSync(path.join(models, "vae"));+ fs.writeFileSync(path.join(models, "loras", "good.safetensors"), "hello");+ fs.writeFileSync(path.join(models, "loras", "swapped.safetensors"), "jello");+ fs.writeFileSync(path.join(models, "loras", "unpinned.safetensors"), "hello");+ fs.writeFileSync(path.join(models, "vae", "net.pth"), "weights");+ const index = {+ files: {+ a: { folder: "loras", file: "good.safetensors", sizeBytes: 5 },+ b: { folder: "loras", file: "swapped.safetensors", sizeBytes: 5 },+ c: { folder: "loras", file: "unpinned.safetensors", sizeBytes: 5 },+ d: { folder: "vae", file: "net.pth", sizeBytes: 7, sha256: sha("weights") },+ },+ };+ const pins = { "loras/good.safetensors": sha("hello"), "loras/swapped.safetensors": sha("hello") };+ const cache = path.join(models, "hash-cache.json");+ const found = await modelFiles([models], index, cache, pins);+ expect(found).toEqual([+ { folder: "loras", name: "good.safetensors", size: 5, sha256: sha("hello") },+ { folder: "vae", name: "net.pth", size: 7, sha256: sha("weights") },+ ]);+ // The hashes are kept, so the next start reads nothing again.+ expect(Object.keys(JSON.parse(fs.readFileSync(cache, "utf8")))).toHaveLength(3);+ });+});+describe("its own ComfyUI's environment", () => {const pc = {SystemRoot: "C:\\Windows",diff --git a/tests/worker-input-rules.test.ts b/tests/worker-input-rules.test.tsindex 5d534bd4..0e79361c 100644--- a/tests/worker-input-rules.test.ts+++ b/tests/worker-input-rules.test.ts@@ -2,7 +2,7 @@ import path from "node:path";import { describe, expect, it } from "vitest";import { graphCheck, vetGraph } from "../bin/lib/worker/checks.mjs";import { loaderInput, pathProblem } from "../bin/lib/worker/rules.mjs";-import { allowedNodeList, inputRules, missingRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";+import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";import { tempDir } from "./helpers/temp-dir";process.env.FUOBE_DATA_DIR = tempDir("fuobe-worker-rules-");@@ -16,6 +16,7 @@ const catalog = readCatalog(root) as unknown as {graphs: Record<string, Graph>;manifest: { workflows: { id: string; file: string }[] };requirements: { files: Record<string, { folder: string; file: string }> };+ pins: Record<string, unknown>;};const rules = inputRules(catalog);const allowed = new Set(allowedNodeList(root, catalog));@@ -153,6 +154,13 @@ describe("the worker's input rules", () => {expect(check({ "1": { class_type: "CLIPTextEncode", inputs: { text, clip: ["2", 0] } } })).toBeNull();expect(check({ "1": { class_type: "StringConcatenate", inputs: { string_a: text, string_b: text, delimiter: "" } } })).toBeNull();});++ it("pins a SHA-256 for nearly every model file the catalog names", () => {+ const pins = filePins(catalog);+ const all = Object.keys(catalog.requirements.files);+ expect(Object.keys(pins).length / all.length).toBeGreaterThan(0.9);+ for (const sha of Object.values(pins)) expect(sha).toMatch(/^[0-9a-f]{64}$/);+ });});describe("graphs as the studio builds them", () => {