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
GPU workers: work a worker's lanes out again when the requirements index changes
Adarsh085600a1b2af
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 51df5848..65bbe6de 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -10,7 +10,7 @@ import { APPS, MODELS } from "@/lib/catalog";import { laneName, type LaneName } from "@/lib/lane-names";import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";-import { loadIndex } from "../gpu/index-file";+import { indexKey, loadIndex } from "../gpu/index-file";import { hostedRunsOn } from "../hosted-switch";import { heldView } from "../pool-holds";import { catalogVersion } from "./catalog-version";@@ -166,7 +166,8 @@ interface Allow {}const allowOf = (w: WorkerRow) => json<Record<string, Allow>>(w.allow_json, {});-const capableOf = (w: WorkerRow) => json<{ lanes: string[]; workflows: string[] }>(w.lanes_json, { lanes: [], workflows: [] });+/** The lanes and workflows its files let it run, and the requirements index they were worked out with (none: an older row). */+const capableOf = (w: WorkerRow) => json<{ lanes: string[]; workflows: string[]; index?: string }>(w.lanes_json, { lanes: [], workflows: [] });const factsOf = (w: WorkerRow) => json<ComputerFacts>(w.facts_json, {});/** The worker's verified files as its last list said (inventory_json), read once for each list it sends. */const inventories = new Map<string, { hash: string | null; inv: Inventory }>();@@ -407,6 +408,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA...(s.prefix && { prefix: s.prefix }),}));const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;+ // Its lanes from another requirements index (the catalog changed since its list came): worked out again now.+ const lanesRefreshed = refreshLanes(fresh);// Stop now (the website, or the worker paused itself with --now / a busy GPU): its jobs go back in line at no cost,// and the worker takes their prompts off its ComfyUI.const stopNow = !!fresh.stop_now || (b.local.paused && !!b.local.why && (b.local.why === "here-now" || b.local.why.startsWith("gpu-busy")));@@ -474,7 +477,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAminProtocol: MIN_PROTOCOL,...(catalogVersion() && { catalogVersion: catalogVersion()! }),// 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),+ // Its lanes were just worked out again for a new index: the list again too, for files the old index didn't name.+ sendInventory: b.local.why !== MODELS_NOT_READY && (lanesRefreshed || !fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash),...(nextToken && { token: nextToken }),...(fresh.expires_at && { tokenExpiresAt: fresh.expires_at }),// The owner's mode it follows now: who goes first, and what local work on its PC does.@@ -670,10 +674,28 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; woconst 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);+ .run(JSON.stringify(inv), invHash, JSON.stringify({ lanes: r.lanes, workflows: r.workflows, index: indexKey() }), w.id);return r;}+/**+ * A worker's lanes worked out with another requirements index than this server's (a deploy changed the catalog after+ * its list of files came, or a server with the old index took the list during a deploy's overlap): worked out again at+ * once from the list it sent, so a workflow the new index adds, or a lane it changes, counts from this beat on. True when+ * they were (the studio then asks for its list again too, for files the old index didn't name). A worker that sent no+ * list yet is left as it is.+ */+export function refreshLanes(w: WorkerRow): boolean {+ if (!w.inventory_json) return false;+ const key = indexKey();+ if (capableOf(w).index === key) return false;+ const r = lanesFor(loadIndex(), inventoryOf(w), sha);+ const lanesJson = JSON.stringify({ lanes: r.lanes, workflows: r.workflows, index: key });+ db().prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?").run(lanesJson, w.id);+ w.lanes_json = lanesJson;+ return true;+}+/** The hash a worker sends with each beat, so the studio asks for the whole list only when it changed. */export function inventoryHash(inv: Inventory): string {const files = [...inv.files].map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();diff --git a/src/server/gpu/index-file.ts b/src/server/gpu/index-file.tsindex aa4485e2..8ca33f13 100644--- a/src/server/gpu/index-file.ts+++ b/src/server/gpu/index-file.ts@@ -1,4 +1,5 @@import "server-only";+import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";import { parseIndex } from "@/lib/gpu/requirements";@@ -12,7 +13,7 @@ export const preflightOn = (): boolean => process.env.FUOBE_GPU_PREFLIGHT?.trim(export const INDEX_FILE = path.join(process.cwd(), "workflows", "comfyui", "requirements.json");-let cache: { mtime: number; index: RequirementIndex; raw: string } | null = null;+let cache: { mtime: number; index: RequirementIndex; raw: string; key: string } | null = null;/** workflows/comfyui/requirements.json (scripts/comfy/build-requirements.mjs), cached by mtime like loadManifest. */export function loadIndex(): RequirementIndex {@@ -20,11 +21,16 @@ export function loadIndex(): RequirementIndex {}/** The index and its file text (GET /api/gpu/requirements serves the text as it is). */-export function loadIndexRaw(): { index: RequirementIndex; raw: string } {+export function loadIndexRaw(): { index: RequirementIndex; raw: string; key: string } {const mtime = fs.statSync(INDEX_FILE).mtimeMs;if (!cache || cache.mtime !== mtime) {const raw = fs.readFileSync(INDEX_FILE, "utf8");- cache = { mtime, index: parseIndex(JSON.parse(raw)), raw };+ cache = { mtime, index: parseIndex(JSON.parse(raw)), raw, key: crypto.createHash("sha256").update(raw).digest("hex").slice(0, 16) };}return cache;}++/** Which requirements index this is: a short hash of its file text. A worker's lanes say which index they were worked out with. */+export function indexKey(): string {+ return loadIndexRaw().key;+}diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.tsindex ec3c2cc8..dbb9d005 100644--- a/tests/workers-pool.test.ts+++ b/tests/workers-pool.test.ts@@ -787,6 +787,36 @@ describe("a worker's list of model files", () => {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);});++ it("works its lanes out again on the next beat when the requirements index changed after its list came, and asks for the list again", async () => {+ const { inventoryHash: workerInventoryHash } = await import("../bin/lib/worker/inventory.mjs");+ const { indexKey } = await import("@/server/gpu/index-file");+ const n = nested();+ const w = bare("stale-lanes", [n.lane], n.minVram + GB);+ const inv = { files: n.files.map(({ folder, name, size, sha256 }) => ({ folder, name, size, sha256 })), nodePacks: n.nodePacks, media: ["image", "video", "audio"] };+ expect((await put(w, inv)).status).toBe(200);+ const fresh = JSON.parse(row(w).lanes_json ?? "{}") as { lanes: string[]; workflows: string[]; index?: string };+ expect(fresh.index).toBe(indexKey());+ // Its lanes as an older index gave them (the workflow is new since; the row from before lanes said their index),+ // with the same list of files: the worker sees no change of its own, so it sends no list by itself.+ for (const stale of [{ lanes: [], workflows: [] }, { lanes: [], workflows: [], index: "another-index" }]) {+ db().prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?").run(JSON.stringify(stale), w.id);+ const id = task({ lane: n.lane, workflow: n.id, minVram: n.minVram, account: "acct-stale-lanes" });+ expect(claim(w)).toBeNull();+ // The next beat works them out again from the list it sent, at once, and asks for the list again.+ expect(beatWith(w, workerInventoryHash(inv)).worker.sendInventory).toBe(true);+ expect(JSON.parse(row(w).lanes_json ?? "{}")).toEqual(fresh);+ expect(claim(w)?.id).toBe(id);+ db().prepare("UPDATE relay_tasks SET state = 'done', worker_id = NULL, device = NULL WHERE id = ?").run(id);+ // Worked out for this index: the next beat neither works them out again nor asks for the list.+ expect(beatWith(w, workerInventoryHash(inv)).worker.sendInventory).toBe(false);+ }+ });++ it("leaves the lanes of a worker that sent no list yet as they are", () => {+ const w = worker("no-list-yet", { lanes: [LANE_A], workflows: ["wf-a"] });+ expect(JSON.parse(row(w).lanes_json ?? "{}")).toEqual({ lanes: [LANE_A], workflows: ["wf-a"] });+ });});describe("routes", () => {