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.

Hosted runs: offer the workers only when one verified every run-time file

Adarshddbb09a4e455
diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjs
index 1cef7c1e..9d4975b7 100644
--- a/bin/lib/worker/inventory.mjs
+++ b/bin/lib/worker/inventory.mjs
@@ -20,6 +20,22 @@ export function filePins(file = path.join(here, "dist", "file-pins.json")) {
}
}
+/**
+ * The files a run may add beyond its workflow's own, built into this worker (dist/runtime-files.json: every LoRA library
+ * entry with a pinned size and SHA-256, src/lib/runtime-files.ts): [{ folder, file, sizeBytes, sha256 }]. None when the
+ * build has no such list (a build from before it): the worker then reports the catalog's own files only.
+ */
+export function runtimeFileList(file = path.join(here, "dist", "runtime-files.json")) {
+ try {
+ const list = JSON.parse(fs.readFileSync(file, "utf8")).files;
+ return Array.isArray(list)
+ ? list.filter((f) => f && typeof f.folder === "string" && typeof f.file === "string" && Number.isInteger(f.sizeBytes) && typeof f.sha256 === "string" && /^[0-9a-f]{64}$/.test(f.sha256))
+ : [];
+ } catch {
+ return [];
+ }
+}
+
function sha256File(file) {
return new Promise((resolve, reject) => {
const h = crypto.createHash("sha256");
@@ -201,6 +217,9 @@ const samePath = (a, b) => (process.platform === "win32" ? path.resolve(a).toLow
* older twin (twinFolders: text_encoders/x and then clip/x). Every copy where ComfyUI itself also looks (`o.comfyDir`: its own models
* folder and its extra_model_paths.yaml) must be the same file too, or it isn't reported. A file with no pin isn't
* reported at all, so no job that needs it comes here.
+ *
+ * `o.runtime`: the run-time files (runtimeFileList), checked the same way after the catalog's own (a file the catalog
+ * names already counts once), so a look's or a motion's LoRA on this PC is verified and a job that loads it may come.
*/
export async function modelFiles(modelDirs, index, cacheFile, pins = filePins(), o = {}) {
const cache = (() => {
@@ -229,7 +248,10 @@ export async function modelFiles(modelDirs, index, cacheFile, pins = filePins(),
return { ok: sha === want, size: st.size, sha };
};
const out = [];
- for (const f of Object.values(index.files ?? {})) {
+ const catalog = Object.values(index.files ?? {});
+ const named = new Set(catalog.map((f) => `${f.folder}/${f.file}`));
+ const runtime = (o.runtime ?? []).filter((f) => !named.has(`${f.folder}/${f.file}`));
+ for (const f of [...catalog, ...runtime]) {
const want = pins[`${f.folder}/${f.file}`] ?? f.sha256;
if (typeof want !== "string" || !/^[0-9a-f]{64}$/.test(want)) continue;
let first = null;
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 8df5969a..96288822 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -27,7 +27,7 @@ import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";
import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";
import { GpuWatch, othersOf, readGpu, readGpuGen } from "./gpu.mjs";
import { Hold } from "./hold.mjs";
-import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";
+import { inventoryHash, missingModelDirs, modelFiles, packFolders, runtimeFileList } from "./inventory.mjs";
import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";
import { takeLock, workerLives } from "./lock.mjs";
import { finishers } from "./finish.mjs";
@@ -189,10 +189,11 @@ export function siteOf(answer) {
/**
* Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),
* "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,
- * signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own
- * options), readCounters, readListeners, gpuEveryMs, readGpuGen, idleClaimMs (IDLE_CLAIM_MS), canCleanPictures, and for
- * job tickets: composer (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, and codeWatch (update.mjs's
- * CodeWatch: new code on disk ends it with "update" once its jobs are done) }.
+ * signal, requirements, ComputerRunner, rules, pins, runtime (the run-time files it verifies: inventory.mjs
+ * runtimeFileList), allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own options), readCounters,
+ * readListeners, gpuEveryMs, readGpuGen, idleClaimMs (IDLE_CLAIM_MS), canCleanPictures, and for job tickets: composer
+ * (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, and codeWatch (update.mjs's CodeWatch: new
+ * code on disk ends it with "update" once its jobs are done) }.
*/
export async function runWorker(saved, deps) {
// One worker at a time on a worker folder: a second one would stop the first one's ComfyUI, empty its folders and
@@ -377,9 +378,11 @@ async function work(saved, deps, owner) {
log(`Saved its next token in worker.json${Number.isFinite(next.expiresAt) ? ` (it lasts until ${new Date(next.expiresAt).toISOString().slice(0, 10)})` : ""}.`);
};
+ // The run-time files it verifies beside the catalog's own (a look's or a motion's LoRAs), as its build lists them.
+ const runtime = deps.runtime ?? runtimeFileList();
async function scan() {
packs = packFolders(cfg.comfyDir, index);
- inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins, { comfyDir: cfg.comfyDir, fileCheck: cfg.fileCheck }), nodePacks: packs.map(({ name, commit }) => ({ name, commit })), media: inv.media };
+ inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins, { comfyDir: cfg.comfyDir, fileCheck: cfg.fileCheck, runtime }), nodePacks: packs.map(({ name, commit }) => ({ name, commit })), media: inv.media };
invHash = inventoryHash(inv);
}
// One look at a time; the next beat carries a changed hash, and the studio then asks for the list.
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index ca0bb3d7..b7b248f0 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -399,6 +399,7 @@ A worker gets a job only when all of these are true, all in one SQLite transacti
- the job is in its pool, in a lane that the owner allows for it, after the lane's delay and `claim_after_ms`;
- it has the workflow's files and packs (from its inventory) and enough VRAM. A workflow's need is its whole GB less
3%, because a card reports a little less than its size (a 32 GB card shows about 31.8 GiB);
+- it verified every run-time file the job loads (see "Run-time files" below);
- the retry rule allows it: a worker that lost or failed the job gets it again only when no other worker that can run
the job was heard from in the last 10 minutes;
- near the end of its hours, the job's estimate fits before the window closes;
@@ -561,6 +562,27 @@ does not read the files again. The catalog's files that still have no pin are li
(`scripts/lib/worker-catalog.mjs`), the one list of them. A test fails when a catalog file has no pin and is not on
that list, and when a file on the list gets a pin, so the list only gets shorter.
+#### Run-time files
+
+Some runs load model files that are not among their workflow's own files: a Soul look's LoRAs, Soul Cinema's, a DoP
+motion's or effect's, a model recipe's, and a LoRA that a graph picks by an option. These are run-time files
+(`src/lib/runtime-files.ts`). A worker verifies them the same way, and reports them in its inventory with the catalog's
+files:
+
+- Its build writes `bin/lib/worker/dist/runtime-files.json`: every LoRA library entry
+ (`src/lib/catalog/lora-library.generated.ts`) that has a pinned size and SHA-256, in the `loras` folder. A LoRA
+ with no pin (a person's own trained LoRA, or a map LoRA with no pin) is never verified.
+- The studio keeps these files from an inventory too, and they decide which runs go to the workers. The price check and
+ the run plan every row of the run with the LoRA files it loads (`runLoraFiles`). A run goes to the workers only when
+ a worker that may run its workflow verified each run-time file (`poolHasFiles`). Otherwise the price check says
+ "This style runs on your own GPU", and Run opens the visitor's own GPU, as for a workflow that no worker runs. The
+ LoRAs are never left out to make the run fit. Preset cards say the same before the press.
+- A task stores its run-time files (`needs.runtime`, read from its graph's LoRA loaders), and only a worker that
+ verified each one claims it. A job that no worker could take is refused before it waits in line. The owner's error
+ names the files.
+
+A worker program from before run-time files reports none, so runs that add them do not go to it.
+
The worker checks the copy that its ComfyUI loads:
- Its ComfyUI looks in the worker's model folders first, in the order that `worker.json` gives (`is_default` in the
@@ -831,8 +853,9 @@ its target), at most once an hour each.
→ `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,
`audio`). With no `media` (a worker from before it was added, which doesn't make clips and sound again), the studio
counts pictures only. A file's `name` is the requirements index's name for it inside its folder, subfolders and all
- (`bigvgan_vocoder/config.json`). The studio keeps only the files the index names, and hashes the list as it was
- sent, so its hash equals the worker's `inventoryHash`.
+ (`bigvgan_vocoder/config.json`). The studio keeps only the files the index names and the run-time files (the LoRA
+ library's pinned files, as `loras/<file>`), and hashes the list as it was sent, so its hash equals the worker's
+ `inventoryHash`.
- `POST /api/gpu/computer/claim`: the browser's claimed task plus
`{ lane, estMs, runLimitMs, stallMs, notAfter, attempt, models, class, workflowId }`. An account's job carries
`ticket` in place of `graph`, with its run and stall limits in it too. `class` is `owner` for the owner's own job,
diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjs
index 423a336e..a1ddcf5e 100644
--- a/scripts/lib/worker-build.mjs
+++ b/scripts/lib/worker-build.mjs
@@ -9,6 +9,8 @@
// 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;
+// - runtime-files.json: the files a run may add beyond its workflow's own (src/lib/runtime-files.ts: every LoRA
+// library entry with a pinned size and SHA-256). A worker verifies and reports them as it does the catalog's files;
// - compose/: the graph composer (src/lib/ticket-compose.ts and every file it imports: bin/lib/worker/composer-files.mjs),
// transpiled the same way, so the worker composes a job ticket's graph with the studio's own code;
// - catalog-version.json: the catalog version those files and the catalog give. A worker takes a ticket only for it;
@@ -17,6 +19,7 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import vm from "node:vm";
import ts from "typescript";
import { builtName, catalogVersion, composerFiles, resolveSpec } from "../../bin/lib/worker/composer-files.mjs";
import { buildStamp, STAMP_FILE } from "../../bin/lib/worker/stamp.mjs";
@@ -42,6 +45,32 @@ export function workerParts(catalog, root = ROOT) {
const TRANSPILE = { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true };
+/** The LoRA library a run's run-time files come from (data only: it imports nothing but types). */
+export const LORA_LIBRARY_FILE = "src/lib/catalog/lora-library.generated.ts";
+
+/**
+ * The run-time files a worker verifies (src/lib/runtime-files.ts runtimeFiles, which the tests hold this to): each LoRA
+ * library entry with a pinned SHA-256 and size, once by name, sorted. The library is read by transpiling its file and
+ * running it alone (it imports types only), so nothing else of the studio runs here.
+ */
+export function runtimeFilePins(root = ROOT) {
+ const src = fs.readFileSync(path.join(root, LORA_LIBRARY_FILE), "utf8");
+ const { outputText } = ts.transpileModule(src, { compilerOptions: { ...TRANSPILE, module: ts.ModuleKind.CommonJS }, fileName: path.basename(LORA_LIBRARY_FILE) });
+ const mod = { exports: {} };
+ const require = (name) => {
+ throw new Error(`${LORA_LIBRARY_FILE} imports ${name}: it may hold data only`);
+ };
+ vm.runInNewContext(outputText, { module: mod, exports: mod.exports, require }, { filename: LORA_LIBRARY_FILE });
+ const library = mod.exports.LORA_LIBRARY;
+ if (!Array.isArray(library)) throw new Error(`${LORA_LIBRARY_FILE} has no LORA_LIBRARY`);
+ const out = new Map();
+ for (const e of library) {
+ if (!e?.file || out.has(e.file) || typeof e.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(e.sha256) || !Number.isInteger(e.sizeBytes) || e.sizeBytes <= 0) continue;
+ out.set(e.file, { folder: "loras", file: e.file, sizeBytes: e.sizeBytes, sha256: e.sha256 });
+ }
+ return [...out.values()].sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
+}
+
/**
* The graph composer as plain .mjs files under compose/ (src/lib/x.ts → compose/lib/x.mjs; a .json it imports →
* compose/….json.mjs, with the data as its default export), each import pointed at the built file. Node's own modules
@@ -98,10 +127,12 @@ export function workerFiles({ root = ROOT, catalogDir } = {}) {
files["allowed-nodes.json"] = json({ nodes });
files["input-rules.json"] = json(rules);
files["file-pins.json"] = json({ files: pins });
+ const runtime = runtimeFilePins(root);
+ files["runtime-files.json"] = json({ files: runtime });
const composer = composerParts(root);
Object.assign(files, composer);
files["catalog-version.json"] = json({ version: catalogVersion(root, catalogDir) });
files[STAMP_FILE] = json({ stamp: buildStamp(root, catalogDir) });
const ruled = Object.values(rules.inputs).reduce((n, r) => n + Object.keys(r).length, 0);
- return { files, summary: `worker: ${SOURCES.length} modules, ${Object.keys(composer).length} composer files, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes` };
+ return { files, summary: `worker: ${SOURCES.length} modules, ${Object.keys(composer).length} composer files, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes, ${runtime.length} run-time files` };
}
diff --git a/src/lib/lanes.ts b/src/lib/lanes.ts
index 64a5dee6..cf8cfb49 100644
--- a/src/lib/lanes.ts
+++ b/src/lib/lanes.ts
@@ -29,6 +29,11 @@ export interface Needs {
size?: { megapixels: number; seconds: number; outputs: number };
/** A job ticket's catalog version (src/lib/job-ticket.ts): only a worker built for that catalog takes the task. */
catalogVersion?: string;
+ /**
+ * The files the run adds beyond its workflow's own (a look's, a motion's or a recipe's LoRAs: src/lib/runtime-files.ts):
+ * only a worker that verified each one takes the task.
+ */
+ runtime?: FileNeed[];
}
/**
@@ -124,6 +129,9 @@ export function hasFile(inv: Inventory, need: FileNeed): boolean {
return inv.files.some((f) => fileKey(f) === fileKey(need) && f.size === need.size && (!need.sha256 || f.sha256 === need.sha256));
}
+/** Has the worker every one of these files (none asked: yes)? */
+export const hasFiles = (inv: Inventory, needs: readonly FileNeed[] | undefined): boolean => !needs?.length || needs.every((n) => hasFile(inv, n));
+
/**
* What a worker can run with what it has: the workflows whose files and packs are all there, the lanes whose every
* workflow runs, and, for the other lanes, what it lacks. A task goes only to a worker that can run its workflow.
diff --git a/src/lib/runtime-files.ts b/src/lib/runtime-files.ts
new file mode 100644
index 00000000..511bcdeb
--- /dev/null
+++ b/src/lib/runtime-files.ts
@@ -0,0 +1,84 @@
+/**
+ * Run-time files (docs/gpu-workers.md "Run-time files"): the model files a run adds beyond its workflow's own, such as a
+ * Soul look's, Soul Cinema's, a DoP motion's or a model recipe's LoRAs, and a LoRA a graph picks by option. A worker
+ * verifies them as it verifies a workflow's files (folder, name, exact size and SHA-256) and reports them with its
+ * inventory; a run goes to the workers only when one that may run its workflow verified every run-time file it loads.
+ *
+ * Only a file with a pinned size and SHA-256 can be verified: every LoRA library entry that has both
+ * (lora-library.generated.ts), and the LoRAs the requirements index names. Any other file (a person's own trained LoRA, a
+ * map LoRA with no pin) runs on a GPU of the person's own.
+ *
+ * Pure: the server, the worker build (scripts/lib/worker-build.mjs reads the same library) and the tests share it.
+ */
+import { LORA_LIBRARY } from "./catalog/lora-library.generated";
+import type { RequirementIndex } from "./gpu/types";
+import type { FileNeed } from "./lanes";
+
+/** The model folder ComfyUI reads a LoRA from (by its name there). */
+export const LORA_FOLDER = "loras";
+
+/** A run-time file a worker can verify: its folder, name, exact size and SHA-256. */
+export interface RuntimeFile {
+ folder: string;
+ file: string;
+ sizeBytes: number;
+ sha256: string;
+}
+
+const SHA = /^[0-9a-f]{64}$/;
+
+/**
+ * The run-time files a worker verifies: each LoRA library entry with a pinned SHA-256 and size, once by name, sorted. The
+ * worker's build writes the same list (dist/runtime-files.json).
+ */
+export function runtimeFiles(library: readonly { file: string; sha256?: string; sizeBytes?: number }[] = LORA_LIBRARY): RuntimeFile[] {
+ const out = new Map<string, RuntimeFile>();
+ for (const e of library) {
+ if (!e.file || out.has(e.file) || typeof e.sha256 !== "string" || !SHA.test(e.sha256) || !Number.isInteger(e.sizeBytes) || (e.sizeBytes ?? 0) <= 0) continue;
+ out.set(e.file, { folder: LORA_FOLDER, file: e.file, sizeBytes: e.sizeBytes!, sha256: e.sha256 });
+ }
+ return [...out.values()].sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
+}
+
+/** "folder/name" of every run-time file, as an inventory keeps them. */
+export const runtimeFileKeys = (files: readonly RuntimeFile[] = runtimeFiles()): Set<string> => new Set(files.map((f) => `${f.folder}/${f.file}`));
+
+/**
+ * A run's run-time files as a worker must have them (`files`), from the LoRA names it loads: a LoRA of the workflow's own
+ * files is left out (its lane says), one the requirements index names is that file, then a library file. `unknown`: the
+ * names no worker can verify (no pin), so no worker runs that run.
+ */
+export function runtimeNeeds(names: readonly string[], index: Pick<RequirementIndex, "files" | "workflows">, workflowId?: string, files: readonly RuntimeFile[] = runtimeFiles()): { files: FileNeed[]; unknown: string[] } {
+ const own = new Set(workflowId ? (index.workflows[workflowId]?.files ?? []) : []);
+ const byName = new Map(files.map((f) => [f.file, f]));
+ const out = new Map<string, FileNeed>();
+ const unknown: string[] = [];
+ for (const raw of names) {
+ const name = typeof raw === "string" ? raw.replace(/\\/g, "/") : "";
+ if (!name || out.has(name) || unknown.includes(name)) continue;
+ const key: `${string}/${string}` = `${LORA_FOLDER}/${name}`;
+ if (own.has(key)) continue;
+ const listed = index.files[key];
+ if (listed) {
+ out.set(name, { folder: listed.folder, name: listed.file, size: listed.sizeBytes, sha256: listed.sha256 ?? null });
+ continue;
+ }
+ const lib = byName.get(name);
+ if (lib) out.set(name, { folder: lib.folder, name: lib.file, size: lib.sizeBytes, sha256: lib.sha256 });
+ else unknown.push(name);
+ }
+ return { files: [...out.values()], unknown };
+}
+
+/** The node inputs that name a LoRA file (LoraLoader's and LoraLoaderModelOnly's lora_name, WanVideoLoraSelect's lora). */
+const LORA_INPUT = /^lora(_name)?$/;
+
+/** The LoRA files a ComfyUI graph loads (each LoRA loader's file, as the worker checks it), once each. */
+export function graphLoraNames(graph: Record<string, { class_type?: unknown; inputs?: Record<string, unknown> } | null | undefined>): string[] {
+ const out = new Set<string>();
+ for (const node of Object.values(graph ?? {})) {
+ if (!node || typeof node.class_type !== "string" || !node.inputs) continue;
+ for (const [input, v] of Object.entries(node.inputs)) if (LORA_INPUT.test(input) && typeof v === "string" && v && v !== "None") out.add(v.replace(/\\/g, "/"));
+ }
+ return [...out];
+}
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 0b595328..038bdc35 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -16,7 +16,7 @@ import { redactKey } from "./provider-keys";
import { networkCode, recordRunEvent } from "./run-events";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";
-import { poolReady, poolTakes } from "./hosted";
+import { poolHasFiles, poolReady, poolTakes } from "./hosted";
import { placeName } from "./place-name";
import { poolOwnModels, poolOwnPresets, type PresetPress } from "./pool-own-setup";
import { ranOwnFirst, runOnOf, type RunOn } from "./run-on";
@@ -395,13 +395,17 @@ const presetModels = (): PresetModel[] =>
return { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) }, ...(step && end && { steps: [{ id: end.id, kind: operationOutput(step.op, end.kind) }] }) };
}));
-/** Every preset's press on its open route, step by step (its end frame's edit first, then its clip to that frame): made once. */
+/**
+ * Every preset's press on its open route, step by step (its end frame's edit first, then its clip to that frame, with the
+ * LoRA files it adds): made once.
+ */
const presetPresses = (): PresetPress[] =>
(globalThis.__fuobePresetPresses ??= PRESETS.flatMap((p) => {
const route = openRoute(p);
if (!route) return [];
const end = route.end;
- return [{ id: p.id, steps: [...(end ? [{ modelId: end.modelId, op: end.op }] : []), { modelId: route.modelId, op: end ? "flf2v" : route.op }] }];
+ const loras = (route.loras ?? []).map((l) => l.file).filter(Boolean);
+ return [{ id: p.id, steps: [...(end ? [{ modelId: end.modelId, op: end.op }] : []), { modelId: route.modelId, op: end ? "flf2v" : route.op, ...(loras.length && { loras }) }] }];
}));
/** Keys whose balance ran out on a run, as the status says them. */
@@ -465,7 +469,7 @@ export async function visitorStatus(account: Account | null) {
// What this studio's GPUs keep off, the open models they can't run right now among it: shown in the pickers with
// what the visitor needs to run them on its own setup. For every viewer, a GPU of its own or not: its runs go
// there first too, and the label says what runs on its own GPU instead.
- const rules = p?.hosted ? poolRulesOf(p, presetModels(), poolOwnModels(), poolOwnPresets(presetPresses(), poolTakes)) : undefined;
+ const rules = p?.hosted ? poolRulesOf(p, presetModels(), poolOwnModels(), poolOwnPresets(presetPresses(), poolTakes, poolHasFiles)) : undefined;
if (rules) viewer.pool = rules;
if (account && p?.links?.length) viewer.links = p.links;
if (account && p?.notice) viewer.notice = p.notice;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index e9a5380d..cd8ed17d 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -2,8 +2,9 @@ import "server-only";
import crypto from "node:crypto";
import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";
import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";
-import { allLanes, laneLabel, lanesFor, MEDIA_KINDS, needsOf, partLanes, type Inventory, type Needs } from "@/lib/lanes";
+import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, partLanes, type FileNeed, type Inventory, type Needs } from "@/lib/lanes";
import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";
+import { runtimeFileKeys } from "@/lib/runtime-files";
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
@@ -140,6 +141,17 @@ 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: [] });
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 }>();
+export function inventoryOf(w: Pick<WorkerRow, "id" | "inventory_json" | "inventory_hash">): Inventory {
+ const kept = inventories.get(w.id);
+ if (kept && kept.hash === (w.inventory_hash ?? null) && w.inventory_hash) return kept.inv;
+ const raw = json<Partial<Inventory>>(w.inventory_json, {});
+ const inv: Inventory = { files: Array.isArray(raw.files) ? raw.files : [], nodePacks: Array.isArray(raw.nodePacks) ? raw.nodePacks : [], ...(Array.isArray(raw.media) && { media: raw.media }) };
+ inventories.set(w.id, { hash: w.inventory_hash ?? null, inv });
+ if (inventories.size > 500) inventories.delete(inventories.keys().next().value!);
+ return inv;
+}
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, {});
/** What its PC may ever run, as its last beat said (null: no ceiling of its own). */
@@ -373,13 +385,16 @@ function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): num
*/
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). */
+/**
+ * The files a worker may report, as "folder/name": the index's (loadIndex keeps one index until its file changes), and the
+ * run-time files a run may add beyond its workflow's own (src/lib/runtime-files.ts: the LoRA library's pinned files).
+ */
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}`));
+ keys = new Set([...Object.values(index.files).map((f) => `${f.folder}/${f.file}`), ...runtimeFileKeys()]);
indexFileKeys.set(index, keys);
}
return keys;
@@ -387,8 +402,9 @@ function knownFiles(): Set<string> {
/**
* 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.
+ * requirements index names and the run-time files (knownFiles) 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. The run-time files it verified decide which runs that add them it may take (fits).
*/
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>;
@@ -505,7 +521,7 @@ function estOn(t: TaskRow, w: WorkerRow): number | null {
/**
* May this worker run this task: its pool, its lane allowed and capable, its PC's ceiling (the lanes or workflows it
* may ever run, the largest picture, the longest clip, the most results), its build's catalog for a job ticket, its
- * files, its VRAM, and the delays.
+ * files (the run-time files the run adds too), its VRAM, and the delays.
*/
function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
if (!(t.pools ?? "").split(",").includes(w.pool)) return false;
@@ -522,6 +538,8 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
if (needs?.catalogVersion && (w.protocol ?? 0) < TICKET_PROTOCOL) return false;
if (refusedBy(t).includes(refusalKey(w))) return false;
if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return false;
+ // The files the run adds beyond its workflow's own (a look's LoRAs): only a worker that verified each one.
+ if (needs?.runtime?.length && !hasFiles(inventoryOf(w), needs.runtime)) return false;
const vram = factsOf(w).vramBytes ?? 0;
if ((needs?.minVramBytes ?? 0) > vram) return false;
if (now - t.created_at < w.claim_after_ms + (allow[lane]?.delayMs ?? 0)) return false;
@@ -963,7 +981,7 @@ export function poolLane(workflowId: string): string {
* an account's run needs; without it, a worker built from another catalog counts too (the owner's own jobs, and
* whether this install's GPUs could ever run it).
*/
-export function workersCanRun(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean } = {}): boolean {
+export function workersCanRun(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean; files?: readonly FileNeed[] } = {}): boolean {
return ableWorkers(workflowId, o).length > 0;
}
@@ -985,8 +1003,11 @@ export function workersMost(workflowId: string): { maxMegapixels?: number; maxSe
return out;
}
-/** The workers that may and can run this workflow (any workflow: null), whatever their state now (workersCanRun). */
-function ableWorkers(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean } = {}): WorkerRow[] {
+/**
+ * The workers that may and can run this workflow (any workflow: null), whatever their state now (workersCanRun). `files`:
+ * the run-time files a run adds (src/lib/runtime-files.ts), each one the worker verified.
+ */
+function ableWorkers(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean; files?: readonly FileNeed[] } = {}): WorkerRow[] {
const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;
const lane = workflowId ? poolLane(workflowId) : null;
// (Runs made here go to the "pool" pool: poolFields.)
@@ -998,6 +1019,7 @@ function ableWorkers(workflowId: string | null, o: { size?: Needs["size"]; ticke
const ceiling = ceilingOf(w);
if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow && insideCeiling(ceiling, { workflowId: id, lane: poolLane(id) }));
if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId) || ceilingProblem(ceiling, { workflowId, lane, size: o.size })) return false;
+ if (o.files?.length && !hasFiles(inventoryOf(w), o.files)) return false;
return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);
});
}
@@ -1081,13 +1103,14 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
*/
export function poolFields(
workflowId: string,
- o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string } = {},
+ o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string; runtime?: FileNeed[] } = {},
now = Date.now(),
) {
const index = loadIndex();
const found = needsOf(index, workflowId);
// How big the job is (a PC's ceiling reads it), and a job ticket's catalog version (only a worker built for it takes it).
- const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }) };
+ // And the files the run adds beyond its workflow's own (a look's LoRAs): only a worker that verified them takes it.
+ const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }), ...(o.runtime?.length && { runtime: o.runtime }) };
const needs = found && { ...found, ...extra };
const lane = poolLane(workflowId);
return {
diff --git a/src/server/computer/ticket-refresh.ts b/src/server/computer/ticket-refresh.ts
index abe76001..6cc115b0 100644
--- a/src/server/computer/ticket-refresh.ts
+++ b/src/server/computer/ticket-refresh.ts
@@ -1,8 +1,10 @@
import "server-only";
import crypto from "node:crypto";
import type { JobTicket, TicketInput } from "@/lib/job-ticket";
+import { graphLoraNames, runtimeNeeds } from "@/lib/runtime-files";
import { composeTicket, inputKind } from "@/lib/ticket-compose";
import { db } from "../db";
+import { loadIndex } from "../gpu/index-file";
import { getWorkflow, loadManifest } from "../providers/comfyui";
import { catalogVersion } from "./catalog-version";
import { GAVE_BACK_WORDS, poolFields } from "./pool";
@@ -105,9 +107,10 @@ export async function refreshTickets(o: { version?: string; startedAt?: number;
});
for (const gone of wasMade.slice(r.made.length)) swapTaskInput(t, gone.name, null);
const fresh: JobTicket = { ...ticket, inputs: [...ticket.inputs.filter((i) => !i.slot.startsWith("made.")), ...made], size: r.size };
- // Its lane and what it needs, from this catalog (the workflow may have moved to other files); its rank, class and
- // wait as they were.
- const fields = poolFields(r.workflowId, { size: r.size, catalogVersion: version });
+ // Its lane and what it needs, from this catalog (the workflow may have moved to other files), with the files its
+ // graph adds at run time (a look's LoRAs); its rank, class and wait as they were.
+ const runtime = runtimeNeeds(graphLoraNames(r.graph), loadIndex(), r.workflowId).files;
+ const fields = poolFields(r.workflowId, { size: r.size, catalogVersion: version, runtime });
// A new ticket: a worker that refused the old one may take it.
const { refusedBy: _refused, ...extra } = json<Record<string, unknown>>(t.extra_json, {});
void _refused;
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e002681c..c44acb43 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -1383,6 +1383,16 @@ const graphLoras = (endpoint: string, extra: Record<string, unknown> | undefined
...pikaFlexGraphLoras(endpoint, extra),
];
+/**
+ * The LoRA files a planned ComfyUI run loads (by name, once each): the ones its plan adds (a look's, a motion's, a
+ * recipe's, the person's own) and the ones its graph picks by option. Whatever of them is a workflow's own file its lane
+ * covers; the rest are its run-time files (src/lib/runtime-files.ts). None off ComfyUI.
+ */
+export function runLoraFiles(p: { route: { provider: string; endpoint: string }; loras: { applied: LoraRef[] } }, extra: Record<string, unknown> | undefined): string[] {
+ if (p.route.provider !== "comfyui") return [];
+ return [...new Set([...p.loras.applied, ...graphLoras(p.route.endpoint, extra)].map((l) => l.file).filter(Boolean))];
+}
+
/** Operations whose clip length is the duration picked (made, or added by extend), not an input video's. */
const MADE_LENGTH_OPS = new Set<Operation>(["t2v", "i2v", "flf2v", "ref2v", "extend", "keyframes"]);
@@ -1697,7 +1707,10 @@ function isParked(id: string, now = Date.now()): boolean {
return false;
}
-/** One row a run would make: its model, operation, provider, kind and app, and the earlier steps it waits for. */
+/**
+ * One row a run would make: its model, operation, provider, kind and app, and the earlier steps it waits for. `loras`:
+ * the LoRA files a planned ComfyUI row loads (runLoraFiles), when plannedSteps could plan it.
+ */
export interface PlannedStep {
id: string;
modelId: string;
@@ -1706,13 +1719,15 @@ export interface PlannedStep {
kind: string;
presetId: string | null;
waits: boolean;
+ loras?: string[];
}
const ROLLED_BACK = Symbol("rolled back");
/**
* Every row `fn` (createGenerations) would make, made and thrown away inside one transaction: nothing is kept and
- * nothing is sent. A chain's later steps are planned exactly as the real run plans them.
+ * nothing is sent. A chain's later steps are planned exactly as the real run plans them, each ComfyUI row with the LoRA
+ * files it loads (a look's, a motion's, a relit start frame's), so a gate checks them all.
*/
export function plannedSteps(fn: () => unknown): PlannedStep[] {
const d = db();
@@ -1721,7 +1736,7 @@ export function plannedSteps(fn: () => unknown): PlannedStep[] {
d.transaction(() => {
const run = captureRun(fn);
run.settle();
- steps = stepsOf(run.ids);
+ steps = stepsOf(run.ids).map(withRowLoras);
throw ROLLED_BACK;
})();
} catch (e) {
@@ -1730,6 +1745,21 @@ export function plannedSteps(fn: () => unknown): PlannedStep[] {
return steps;
}
+/** A ComfyUI row with the LoRA files it loads, planned from its request as createGenerations planned it (else as it was). */
+function withRowLoras(s: PlannedStep): PlannedStep {
+ if (s.provider !== "comfyui") return s;
+ const r = db().prepare("SELECT request_json, depends_on FROM generations WHERE id = ?").get(s.id) as { request_json: string; depends_on: string | null } | undefined;
+ if (!r) return s;
+ try {
+ const req = JSON.parse(r.request_json) as GenerationRequest;
+ const deps = !r.depends_on ? 0 : r.depends_on.startsWith("[") ? (JSON.parse(r.depends_on) as unknown[]).length : 1;
+ const loras = runLoraFiles(previewChained(req, deps), req.params?.extra);
+ return loras.length ? { ...s, loras } : s;
+ } catch {
+ return s;
+ }
+}
+
/** The rows of a run (by id) as steps. */
export function stepsOf(ids: string[]): PlannedStep[] {
const q = db().prepare("SELECT id, model_id, op, provider, kind, preset_id, depends_on FROM generations WHERE id = ?");
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 18da0b6e..559de00e 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -39,12 +39,12 @@ import {
import { getModel } from "@/lib/catalog";
import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER } from "@/lib/guest-access";
import { db } from "./db";
-import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, stepsOf, type PlannedStep } from "./generations";
+import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, runLoraFiles, stepsOf, type PlannedStep } from "./generations";
import { loadIndex } from "./gpu/index-file";
import { attemptLimitMs, MAX_ATTEMPTS, poolLane } from "./computer/pool";
import { poolFinishes3d } from "./computer/finish";
import { holdTiming } from "./queue-settings";
-import { hostedDetails, hostedGuestWords, hostedWords, inputCounts, isOutputsWords, outputsWords, poolAllows, poolAllowsRun, poolAway, poolFitsSize, poolMostWords, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTicketsReady, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks, type JobSize } from "./hosted";
+import { hostedDetails, hostedGuestWords, hostedWords, inputCounts, isOutputsWords, outputsWords, poolAllows, poolAllowsRun, poolAway, poolFitsSize, poolHasFiles, poolMostWords, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTicketsReady, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks, type JobSize } from "./hosted";
import { withRunStamp } from "./run-stamp";
import { hostedRunsOn } from "./hosted-switch";
import { checkRun, moderationConfigured } from "./moderation";
@@ -349,14 +349,15 @@ export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]
/**
* Why this install's GPUs won't take a run: a 3D model no worker finishes (computer/finish.ts poolFinishes3d), a model
- * or kind not offered there, a model their card can't run, LoRAs, a kind of file, more outputs at once than a run there
- * makes (`outputs`: a tool's run, which can't be cut down the way the studios' own runs are), one that runs on the
- * visitor's own setup only (`ownSetup`: a static item of own-setup.ts, or a workflow none of this install's GPUs can
- * run right now: none holds its files, serves its lane, or has the memory). Each is a label the visitor reads before
- * Run, with the setup that runs it. A run these GPUs take but can't start right now (every one that could is away, or
- * being updated) is no reason: it waits in line (runWaits).
+ * or kind not offered there, a model their card can't run, LoRAs, a style's files no GPU there holds (`files`: the
+ * LoRAs a look, a motion or a recipe adds at run time, src/lib/runtime-files.ts), a kind of file, more outputs at once
+ * than a run there makes (`outputs`: a tool's run, which can't be cut down the way the studios' own runs are), one
+ * that runs on the visitor's own setup only (`ownSetup`: a static item of own-setup.ts, or a workflow none of this
+ * install's GPUs can run right now: none holds its files, serves its lane, or has the memory). Each is a label the
+ * visitor reads before Run, with the setup that runs it. A run these GPUs take but can't start right now (every one
+ * that could is away, or being updated) is no reason: it waits in line (runWaits).
*/
-export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "size" | "outputs" | "ownSetup";
+export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "files" | "inputs" | "size" | "outputs" | "ownSetup";
/**
* A gate's refusal: its reason, and the visitor's own setup that would run it (`setup`: always with "ownSetup" and
@@ -396,8 +397,9 @@ export function gateDetail(gate: GateRefusal, place: Place): string | undefined
* The one check of whether this install's GPUs take a run, shared by the run itself (decidePlace) and the price check
* before Run (poolQuote), so the two always agree: its output kind (3D only where a worker finishes it), the policy's
* model, app and kind lists (for the run's own model and every other model it makes a step with, such as a 2K take's
- * finish), a worker allowed its lane, a card that can run it, LoRAs, the kinds of file it sends, and every later step
- * of a chain (planned only once the cheaper checks pass). `p` null: the billing service didn't answer, so only what needs
+ * finish), a worker allowed its lane, a card that can run it, LoRAs, the files it adds at run time (a look's, a motion's
+ * or a recipe's LoRAs: a worker allowed its lane must have verified each one), the kinds of file it sends, and every
+ * later step of a chain (planned only once the cheaper checks pass), its run-time files too. `p` null: the billing service didn't answer, so only what needs
* no policy is checked. Passed, it gives the planned steps for the run's one price.
*
* First of all, every step's own setup (own-setup.ts): a model, mode or option that runs on a visitor's own GPU or key
@@ -423,6 +425,9 @@ export function poolGate(
if (!poolTakes(planned.route.endpoint)) return { ok: false, reason: "ownSetup", setup: gpu };
if (poolCardRefuses(planned.model.id)) return { ok: false, reason: "rtxCard", setup: gpu };
if (req.loras?.length && !req.lorasOff) return { ok: false, reason: "loras", setup: gpu };
+ // The files it adds at run time (a look's, a motion's or a recipe's LoRAs): a run whose worker would refuse it for a
+ // file it hasn't verified runs on the visitor's own GPU instead, said before Run (never dropped without a word).
+ if (!poolHasFiles(planned.route.endpoint, runLoraFiles(planned, req.params?.extra))) return { ok: false, reason: "files", setup: gpu };
if (p) {
const inputs = inputCounts(req);
const takes = poolUploads(p);
@@ -444,6 +449,8 @@ export function poolGate(
// visitor's own GPU, labelled with what that step needs, as the run's own step is. Never a first step run here
// and a later one that can't go on.
if (s.provider === "comfyui" && !poolTakes(stepEndpoint(s))) return { ok: false, reason: "ownSetup", setup: needsGpu(stepEndpoint(s)) };
+ // A step that adds files at run time (a relit start frame's LoRA, a Mixed Media still's look) that no worker verified.
+ if (s.provider === "comfyui" && s.loras?.length && !poolHasFiles(stepEndpoint(s), s.loras)) return { ok: false, reason: "files", setup: needsGpu(stepEndpoint(s)) };
}
const problem = steps && p ? stepsProblem(p, steps) : null;
if (problem) return { ok: false, reason: problem === hostedWords(placeFor(p)).rtxCard ? "rtxCard" : "notOffered", setup: gpu };
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
index 4eee338c..49ba8bbb 100644
--- a/src/server/hosted.ts
+++ b/src/server/hosted.ts
@@ -5,6 +5,7 @@ import { h3Canvas, isH3Graph } from "@/lib/h3-prompt";
import { imageSize } from "@/lib/image-size";
import type { GenerationRequest } from "@/lib/catalog/types";
import type { Place } from "@/lib/place-name";
+import { runtimeNeeds } from "@/lib/runtime-files";
import { billingConfigured, type Policy, type QueueFacts, type RunFacts } from "./billing";
import { lineFacts, poolLane, queueOfGeneration, workersAway, workersCanRun, workersMost, type LinePlace } from "./computer/pool";
import { db } from "./db";
@@ -86,6 +87,25 @@ export function poolTakes(endpoint: string | undefined): boolean {
return picks.length > 0 && picks.every((id) => workersCanRun(id));
}
+/**
+ * Has a worker that may run this workflow verified every run-time file a run of it loads (`names`: the LoRA files it adds
+ * beyond its workflow's own, src/lib/runtime-files.ts)? A file with no pin (a person's own LoRA) no worker can verify. A
+ * workflow that picks its graph at run time: every graph it may pick. No such files, or not on the workers (this install's
+ * own ComfyUI downloads into its own LoRA folder, or says what it lacks): yes.
+ */
+export function poolHasFiles(endpoint: string | undefined, names: readonly string[]): boolean {
+ if (!endpoint || !names.length || !poolOnWorkers()) return true;
+ const index = loadIndex();
+ const picks = endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint];
+ return (
+ picks.length > 0 &&
+ picks.every((id) => {
+ const r = runtimeNeeds(names, index, id);
+ return !r.unknown.length && (!r.files.length || workersCanRun(id, { files: r.files }));
+ })
+ );
+}
+
/** The size of one job, as a PC's ceiling reads it: its pictures' or frames' megapixels, a clip's seconds, its results. */
export interface JobSize {
megapixels: number;
@@ -184,6 +204,7 @@ export function hostedWords(place: Place) {
return {
notOffered: "Runs on your own GPU",
loras: "LoRAs run on your own GPU",
+ files: "This style runs on your own GPU",
inputs: "This file runs on your own GPU",
rtxCard: "Runs on your own RTX GPU",
size: "This size runs on your own GPU",
@@ -199,6 +220,7 @@ export function hostedDetails(place: Place, most?: string | null) {
return {
notOffered: "Connect your GPU to run this one, or pick another model.",
loras: "Connect your GPU to use them, or run without them.",
+ files: "Connect your GPU to use this style, or pick another one.",
inputs: "Connect your GPU to use it, or use a picture.",
rtxCard: "This one needs an NVIDIA RTX card.",
size: `${most ? `Up to ${most} on ${place.text}. ` : ""}Pick a smaller size, or run it on your own GPU.`,
@@ -207,8 +229,8 @@ export function hostedDetails(place: Place, most?: string | null) {
/** The labels for a guest: the same as an account's (Run opens the sign-up for that label). */
export function hostedGuestWords() {
- const { notOffered, rtxCard, loras, inputs, size } = hostedWords({ label: "", text: "" });
- return { notOffered, rtxCard, loras, inputs, size };
+ const { notOffered, rtxCard, loras, files, inputs, size } = hostedWords({ label: "", text: "" });
+ return { notOffered, rtxCard, loras, files, inputs, size };
}
/**
diff --git a/src/server/pool-own-setup.ts b/src/server/pool-own-setup.ts
index da41ef53..f34b16c3 100644
--- a/src/server/pool-own-setup.ts
+++ b/src/server/pool-own-setup.ts
@@ -155,20 +155,24 @@ export function poolCardRefuses(modelId: string): boolean {
/** The open models this install's GPUs can't run right now (poolOwnSetups), for GET /api/status's pool rules. */
export const poolOwnModels = (): Record<string, OwnSetup> => poolOwnSetups(poolTakes, poolCardRefuses);
-/** A preset's press as the cards see it: each step's open model and operation (its end frame's edit first, then its clip). */
+/**
+ * A preset's press as the cards see it: each step's open model and operation (its end frame's edit first, then its clip),
+ * with the LoRA files the step adds at run time (a motion's or an effect's).
+ */
export interface PresetPress {
id: string;
- steps: { modelId: string; op: string }[];
+ steps: { modelId: string; op: string; loras?: string[] }[];
}
/**
* The presets whose press this install's GPUs can't run in whole right now, with what a visitor needs to run them on its
* own setup: a step none of whose workflows for its operation `takes` (a start-and-end-frame clip while only the plain
- * clip's workflow is held, or an end frame's edit no worker holds). Their cards say so before the press, as the price
+ * clip's workflow is held, or an end frame's edit no worker holds), or whose run-time files (its LoRAs) no worker that
+ * takes it verified (`hasFiles`: hosted.ts poolHasFiles). Their cards say so before the press, as the price
* check does (hosted-run.ts poolGate): never "Try free" for a run whose later step can't go on there. A step with no
* workflow for its operation is left to the price check.
*/
-export function poolOwnPresets(presets: readonly PresetPress[], takes: (endpoint: string) => boolean): Record<string, OwnSetup> {
+export function poolOwnPresets(presets: readonly PresetPress[], takes: (endpoint: string) => boolean, hasFiles: (endpoint: string, loras: readonly string[]) => boolean = () => true): Record<string, OwnSetup> {
const out: Record<string, OwnSetup> = {};
const known = new Map<string, boolean>();
const taken = (e: string) => {
@@ -181,7 +185,7 @@ export function poolOwnPresets(presets: readonly PresetPress[], takes: (endpoint
for (const s of p.steps) {
const m = byId.get(s.modelId);
const endpoints = m ? [...new Set(m.routes.filter((r) => r.provider === "comfyui" && r.op === s.op).map((r) => r.endpoint))] : [];
- if (!endpoints.length || endpoints.some(taken)) continue;
+ if (!endpoints.length || endpoints.some((e) => taken(e) && (!s.loras?.length || hasFiles(e, s.loras)))) continue;
out[p.id] = needsGpu(endpoints[0]);
break;
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 504ecbe2..cbd170f8 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -14,6 +14,8 @@ import { mergeScanReports, qualityOf } from "@/lib/watermark";
import { H3_LATENT_DRAFT_WORKFLOW, REGEN_COPY, REGEN_LATENT_WORKFLOW, REGEN_WORKFLOW } from "@/lib/catalog/regenerate";
import { fixFromPromptError } from "@/lib/gpu/fix-codes";
import { loadIndex } from "../gpu/index-file";
+import type { FileNeed } from "@/lib/lanes";
+import { graphLoraNames, runtimeNeeds } from "@/lib/runtime-files";
import { installedDbs, type DbsModel } from "@/lib/av/split";
import { installedReuse, type ReuseModel } from "@/lib/av/clean-voice";
import { RTX_FRAMEGEN_WORKFLOW, RTX_HDR_WORKFLOW, RTX_MISSING } from "@/lib/catalog/rtx-video";
@@ -291,7 +293,7 @@ export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this mach
* limit (the run was taken in line once; the wait limit applies only before its first start). The run's wait limit is
* the one stamped on it (0: as long as it takes), else the install's own (FUOBE_POOL_WAIT_MIN).
*/
-function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string }) {
+function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string; runtime?: FileNeed[] }) {
const stamp = runStamp();
const run = generationId ? runPlaceOf(generationId) : null;
// A run that waited to enter the line (pool-holds.ts) enters where its release says (stamp.rankAt): for the system's
@@ -307,6 +309,7 @@ function accountPoolFields(workflowId: string, account: string, generationId: st
waitMs: run?.started || run?.later ? undefined : (stamp?.waitMs ?? poolWaitMs()),
size: o.size,
catalogVersion: o.catalogVersion,
+ runtime: o.runtime,
});
}
@@ -316,6 +319,16 @@ export const NO_WORKER_FOR_SIZE = "No worker may run a job this large: each PC's
/** Said to an account when its run is larger than this install's GPUs ever make (refused before it is queued). */
export const POOL_TOO_BIG = "This size isn't offered here yet. Pick a smaller size, a shorter clip or fewer results.";
+/**
+ * Said to the owner when no worker that may run the job's workflow verified a file the job adds at run time (a look's or
+ * a motion's LoRA), naming the files.
+ */
+export const noWorkerForFiles = (files: readonly string[]): string =>
+ `No worker has ${files.length > 1 ? "these files" : "this file"} yet: ${files.join(", ")}. Put ${files.length > 1 ? "them" : "it"} in a worker's loras folder (a library LoRA is verified by its pinned size and SHA-256), then run it again.`;
+
+/** Said to an account when its run adds a file no GPU here verified (refused before it is queued; the price check said so first). */
+export const POOL_NO_FILES = "This style runs on your own GPU. Connect your GPU to use it, or pick another one.";
+
/** 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 can run this model yet. Allow its lane for a worker that has its model files, in Settings → Open-source engine · ComfyUI → Workers.";
@@ -1960,6 +1973,14 @@ export const comfyProvider: ProviderAdapter = {
// A job larger than every PC that could run it may ever make (its ceiling) would never be taken: refused now, the
// owner's and an account's alike, before it waits in line.
if (forPool && workersCanRun(manifest.id) && !workersCanRun(manifest.id, { size: prepared.size })) throw new ProviderError(computer === "owner" ? NO_WORKER_FOR_SIZE : POOL_TOO_BIG);
+ // The files the graph loads beyond its workflow's own (a look's, a motion's or a recipe's LoRAs): only a worker that
+ // verified each one takes the task, and a job no worker could take is refused now, never left to wait for nothing
+ // (or refused by a worker for a file it hasn't verified).
+ const runtime = forPool ? runtimeNeeds(graphLoraNames(wf), loadIndex(), manifest.id) : null;
+ if (runtime && workersCanRun(manifest.id) && (runtime.unknown.length || !workersCanRun(manifest.id, { files: runtime.files }))) {
+ const lacking = [...runtime.unknown, ...runtime.files.filter((f) => !workersCanRun(manifest.id, { files: [f] })).map((f) => f.name)];
+ throw new ProviderError(computer === "owner" ? noWorkerForFiles(lacking.length ? lacking : runtime.files.map((f) => f.name)) : POOL_NO_FILES);
+ }
const outputs = Math.max(1, manifest.outputs.length) * Math.max(1, Math.round(Number(input.numOutputs) || 1));
// An account's run on the workers: a job ticket, and the worker composes the graph (the owner's own jobs keep theirs).
const ticket = forPool && computer !== "owner" ? accountTicket(prepared, computer, { outputs, kind: model?.kind }) : undefined;
@@ -1984,11 +2005,11 @@ export const comfyProvider: ProviderAdapter = {
computer === "owner"
? // The owner's jobs on the workers: the lane and files they need, after every person's run (the owner's
// class), with the owner's own wait limit (none unless the owner sets one: queue-settings.ts).
- poolFields(manifest.id, { class: "owner", waitMs: ownerWaitMs(), size: prepared.size })
+ poolFields(manifest.id, { class: "owner", waitMs: ownerWaitMs(), size: prepared.size, runtime: runtime?.files })
: // An account's: the lane and files they need, in its class (paid before free), in the order they came
// (with the billing service's head start inside the class), with the wait set for the run.
// A ticket's task goes only to a worker built for its catalog, and inside that PC's ceiling.
- accountPoolFields(manifest.id, computer.slice(5), generationId, { size: prepared.size, catalogVersion: ticket?.catalogVersion }),
+ accountPoolFields(manifest.id, computer.slice(5), generationId, { size: prepared.size, catalogVersion: ticket?.catalogVersion, runtime: runtime?.files }),
}),
});
// (`workers`: the run keeps its task's clocks, pool.ts, even when a poll of it fails.)
diff --git a/tests/hosted-words.test.ts b/tests/hosted-words.test.ts
index d206636d..316736aa 100644
--- a/tests/hosted-words.test.ts
+++ b/tests/hosted-words.test.ts
@@ -112,7 +112,7 @@ afterEach(() => notePlaceName(null));
/** Every sentence a visitor reads from the server's word tables, for a place. */
function serverWords(place: ReturnType<typeof placeOf>): string[] {
- const reasons = ["notOffered", "rtxCard", "loras", "inputs", "size", "model3d"] as const;
+ const reasons = ["notOffered", "rtxCard", "loras", "files", "inputs", "size", "model3d"] as const;
const setups = [needsGpu(), { need: "gpu" as const, vramGb: 48 }, { need: "gpu" as const, vramGb: 24, orKey: "fal" as const }, { need: "key" as const, provider: "fal" }];
return [
...Object.values(hostedWords(place)),
diff --git a/tests/pool-runtime-files.test.ts b/tests/pool-runtime-files.test.ts
new file mode 100644
index 00000000..cf986a0b
--- /dev/null
+++ b/tests/pool-runtime-files.test.ts
@@ -0,0 +1,227 @@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Run-time files on this install's GPUs (docs/gpu-workers.md "Run-time files"): a Soul look's, Soul Cinema's or a DoP
+ * motion's LoRAs are files beyond the workflow's own. A worker refuses a graph that names a file it hasn't verified, so
+ * these GPUs are offered for such a run only when a worker that may run its workflow verified every one of them. Until
+ * then the price check and the run say the visitor's own GPU runs it (never a refusal at the worker, never the LoRAs
+ * dropped), the preset cards say so too, and a task goes only to a worker that has the files.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-runtime-files-");
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing answers here: no test may reach a real ComfyUI on this machine.
+const DEAD = "http://127.0.0.1:7";
+process.env.COMFYUI_URL = DEAD;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async () => new Response("not reachable in this test", { status: 599 })) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const hosted = await import("@/server/hosted");
+const { decidePlace, poolQuote } = await import("@/server/hosted-run");
+const { loadManifest, noWorkerForFiles } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes, needsOf } = await import("@/lib/lanes");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { runtimeNeeds } = await import("@/lib/runtime-files");
+const { soulRecipe } = await import("@/lib/catalog/soul");
+const { getModel, getPreset, PRESETS } = await import("@/lib/catalog");
+const { presetRoutes } = await import("@/lib/catalog/preset-recipe-routes");
+const { poolOwnPresets } = await import("@/server/pool-own-setup");
+const { previewGeneration } = await import("@/server/generations");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+/** A Soul run in the default photo look: Shakker-Labs AWPortrait-Z and the Lenovo phone-realism LoRA, both pinned. */
+const LOOK = "v1-general";
+const soulRun = { feature: "image", modelId: "fuobe-soul", engine: "open", presetId: LOOK, prompt: "a portrait by a window", params: { aspectRatio: "3:4" } } as const;
+const lookFiles = soulRecipe("soul", "x", { look: LOOK }).loras.map((l) => l.file);
+
+let account: NonNullable<ReturnType<typeof auth.accountById>>;
+let cookie = "";
+
+beforeAll(() => {
+ auth.setPassword("install password");
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ account = auth.accountById(id)!;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+});
+afterAll(() => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE"]) delete process.env[k];
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+/**
+ * A worker the owner added and resumed, allowed every lane, able to run every workflow, that verified the workflows'
+ * files and the given run-time files (by name), as its inventory said.
+ */
+function standInWorker(name: string, runtime: readonly string[] = []) {
+ const w = pool.addWorker(name);
+ const index = loadIndex();
+ const lanes = allLanes(index, sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), Date.now(), w.id);
+ // Its list of files, as PUT /api/gpu/computer/inventory takes it: every workflow's own files, and the run-time ones.
+ const own = Object.values(index.files).map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ const extra = runtimeNeeds(runtime, index).files;
+ const packs = Object.keys(index.packs ?? {}).map((name) => ({ name, commit: null }));
+ pool.saveInventory(row(w.id), { files: [...own, ...extra], nodePacks: packs, media: ["image", "video", "audio"] });
+ // Every workflow, whatever this test's catalog copy says of their packs.
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), w.id);
+ return w;
+}
+const row = (id: string) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as import("@/server/computer/workers").WorkerRow;
+
+const press = async (body: Record<string, unknown>) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),
+ );
+ return { status: r.status, body: (await r.json()) as Record<string, unknown> & { items?: { id: string }[]; code?: string; error?: string } };
+};
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
+
+describe("a run that adds files at run time, on this install's GPUs", () => {
+ it("knows the look's LoRAs as the run's files beyond its workflow's own", () => {
+ expect(lookFiles).toEqual(expect.arrayContaining(["AWPortrait-Z.safetensors"]));
+ const p = previewGeneration(soulRun);
+ expect(p.route.provider).toBe("comfyui");
+ const r = runtimeNeeds(lookFiles, loadIndex(), p.route.endpoint);
+ expect(r.unknown).toEqual([]);
+ expect(r.files.map((f) => f.name).sort()).toEqual([...lookFiles].sort());
+ expect(r.files.every((f) => f.folder === "loras" && f.size > 0 && /^[0-9a-f]{64}$/.test(f.sha256 ?? ""))).toBe(true);
+ });
+
+ it("no worker verified them: the price check says the visitor's own GPU runs it, with its plain reason, and the run opens that setup", async () => {
+ standInWorker("no-loras");
+ const endpoint = previewGeneration(soulRun).route.endpoint;
+ // The workflow itself runs there: only the look's files keep it off.
+ expect(hosted.poolTakes(endpoint)).toBe(true);
+ expect(hosted.poolHasFiles(endpoint, lookFiles)).toBe(false);
+ const q = await poolQuote(account, soulRun, undefined);
+ expect(q?.quote).toMatchObject({ allowed: false, code: "not-offered", text: "This style runs on your own GPU", sub: "Connect your GPU to use this style, or pick another one." });
+ expect((q!.quote as { ownSetup?: unknown }).ownSetup).toMatchObject({ need: "gpu" });
+ // The press: never a run that a worker would refuse, never the LoRAs left out; Connect your GPU instead.
+ const d = await decidePlace(account, soulRun, undefined);
+ expect(d.kind).toBe("refuse");
+ const refusal = (d as { refusal: { body: Record<string, unknown> } }).refusal;
+ expect(refusal.body).toMatchObject({ error: "This style runs on your own GPU", code: "connect-gpu" });
+ const r = await press(soulRun);
+ expect(r.status).toBe(403);
+ expect(r.body).toMatchObject({ error: "This style runs on your own GPU", code: "connect-gpu" });
+ expect(db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE state = 'waiting'").get()).toEqual({ n: 0 });
+ });
+
+ it("a worker that verified every one: offered there, and the task goes only to a worker with those files", async () => {
+ const without = standInWorker("no-loras");
+ standInWorker("with-loras", lookFiles);
+ const endpoint = previewGeneration(soulRun).route.endpoint;
+ expect(hosted.poolHasFiles(endpoint, lookFiles)).toBe(true);
+ // Half of them is not enough.
+ expect(hosted.poolHasFiles(endpoint, [...lookFiles, "someone-else-trained.safetensors"])).toBe(false);
+ const q = await poolQuote(account, soulRun, undefined);
+ expect(q?.quote.allowed, JSON.stringify(q?.quote)).toBe(true);
+ const r = await press(soulRun);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const id = r.body.items![0].id;
+ let t: ReturnType<typeof taskOf>;
+ for (let i = 0; i < 200 && !(t = taskOf(id)); i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ }
+ expect(t!, "the run's task").toBeDefined();
+ const needs = JSON.parse(t!.needs_json ?? "{}") as { runtime?: { name: string }[] };
+ expect(needs.runtime?.map((f) => f.name).sort()).toEqual([...lookFiles].sort());
+ // The worker without them never takes it; the one with them does.
+ expect(pool.workerClaim(row(without.id), [])).toBeNull();
+ const withRow = db().prepare("SELECT * FROM relay_workers WHERE name = 'with-loras'").get() as import("@/server/computer/workers").WorkerRow;
+ expect(pool.workerClaim(withRow, [])?.id).toBe(t!.id);
+ });
+
+ it("a file no worker can verify (no pin) keeps it off, and the owner's error names the files", () => {
+ standInWorker("with-loras", lookFiles);
+ const endpoint = previewGeneration(soulRun).route.endpoint;
+ expect(hosted.poolHasFiles(endpoint, ["my-trained-face.safetensors"])).toBe(false);
+ expect(noWorkerForFiles(["AWPortrait-Z.safetensors"])).toContain("AWPortrait-Z.safetensors");
+ expect(noWorkerForFiles(["a.safetensors", "b.safetensors"])).toMatch(/^No worker has these files yet: a\.safetensors, b\.safetensors\./);
+ });
+
+ it("an inventory keeps the library's pinned files and nothing else beyond the index", () => {
+ const w = standInWorker("lists");
+ const index = loadIndex();
+ const own = Object.values(index.files)
+ .slice(0, 3)
+ .map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ const look = runtimeNeeds(lookFiles, index).files;
+ pool.saveInventory(row(w.id), { files: [...own, ...look, { folder: "loras", name: "not-in-the-library.safetensors", size: 10, sha256: "0".repeat(64) }], nodePacks: [] });
+ const kept = pool.inventoryOf(row(w.id)).files.map((f) => `${f.folder}/${f.name}`);
+ expect(kept).toEqual(expect.arrayContaining(look.map((f) => `loras/${f.name}`)));
+ expect(kept).not.toContain("loras/not-in-the-library.safetensors");
+ expect(kept).toHaveLength(own.length + look.length);
+ });
+
+ it("a preset card whose LoRAs no worker verified says the visitor's own GPU before the press; with them it doesn't", () => {
+ // A DoP motion or effect on its own model: a route of the preset that adds pinned LoRAs.
+ const pinned = (r: ReturnType<typeof presetRoutes>[number]) => !r.end && (r.loras?.length ?? 0) > 0 && r.loras!.every((l) => runtimeNeeds([l.file], loadIndex()).unknown.length === 0);
+ const preset = PRESETS.find((p) => presetRoutes(p, "open", (id) => !!getModel(id)).some(pinned))!;
+ expect(preset, "a preset whose open route adds pinned LoRAs").toBeDefined();
+ const route = presetRoutes(preset, "open", (id) => !!getModel(id)).find(pinned)!;
+ const step = { modelId: route.modelId, op: route.op, loras: route.loras!.map((l) => l.file) };
+ const endpoint = getModel(route.modelId)!.routes.find((x) => x.provider === "comfyui" && x.op === route.op)!.endpoint;
+ standInWorker("no-loras");
+ expect(hosted.poolTakes(endpoint)).toBe(true);
+ expect(poolOwnPresets([{ id: preset.id, steps: [step] }], hosted.poolTakes, hosted.poolHasFiles)[preset.id]).toMatchObject({ need: "gpu" });
+ // Without the files check (as before), the card would say these GPUs run it.
+ expect(poolOwnPresets([{ id: preset.id, steps: [step] }], hosted.poolTakes)[preset.id]).toBeUndefined();
+ standInWorker("with-loras", step.loras);
+ expect(poolOwnPresets([{ id: preset.id, steps: [step] }], hosted.poolTakes, hosted.poolHasFiles)[preset.id]).toBeUndefined();
+ expect(getPreset(preset.id)).toBeDefined();
+ });
+
+ it("a workflow's own LoRA is its lane's to say, not a run-time file", () => {
+ const index = loadIndex();
+ const [id, wf] = Object.entries(index.workflows).find(([, w]) => w.files.some((k) => k.startsWith("loras/")))!;
+ const own = wf.files.find((k) => k.startsWith("loras/"))!.slice("loras/".length);
+ expect(runtimeNeeds([own], index, id)).toEqual({ files: [], unknown: [] });
+ expect(needsOf(index, id)!.files.some((f) => f.folder === "loras" && f.name === own)).toBe(true);
+ });
+});
diff --git a/tests/worker-runtime-files.test.ts b/tests/worker-runtime-files.test.ts
new file mode 100644
index 00000000..273a0273
--- /dev/null
+++ b/tests/worker-runtime-files.test.ts
@@ -0,0 +1,147 @@
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { graphCheck } from "../bin/lib/worker/checks.mjs";
+import { modelFiles, runtimeFileList } from "../bin/lib/worker/inventory.mjs";
+import { runtimeFilePins, workerFiles } from "../scripts/lib/worker-build.mjs";
+import { allowedNodeList, inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";
+import { injectLoras } from "@/lib/comfy";
+import { LORA_LIBRARY } from "@/lib/catalog/lora-library.generated";
+import { hasFiles } from "@/lib/lanes";
+import { graphLoraNames, LORA_FOLDER, runtimeFiles, runtimeNeeds } from "@/lib/runtime-files";
+import type { RequirementIndex } from "@/lib/gpu/types";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Run-time files on the worker (docs/gpu-workers.md "Run-time files"): its build lists the LoRA library's pinned files,
+ * it verifies the ones on its PC as it verifies the catalog's (folder, name, exact size and SHA-256) and reports them, so
+ * a graph that loads a look's LoRA passes its own check only when that file is the pinned one.
+ */
+
+const sha = (data: string) => crypto.createHash("sha256").update(data).digest("hex");
+const root = path.resolve(__dirname, "..");
+
+describe("the run-time files a worker verifies", () => {
+ it("are the LoRA library's entries with a pinned size and SHA-256, the same in the worker's build and the studio", () => {
+ const studio = runtimeFiles();
+ expect(studio.length).toBeGreaterThan(50);
+ expect(studio.every((f) => f.folder === LORA_FOLDER && f.sizeBytes > 0 && /^[0-9a-f]{64}$/.test(f.sha256))).toBe(true);
+ expect(studio.map((f) => f.file)).toContain("AWPortrait-Z.safetensors");
+ // An entry with no pin (or no size) is never one.
+ const unpinned = LORA_LIBRARY.filter((e) => !e.sha256 || !e.sizeBytes).map((e) => e.file);
+ for (const f of unpinned) expect(studio.some((x) => x.file === f)).toBe(false);
+ // The worker's build reads the same library, without running the studio's code.
+ expect(runtimeFilePins(root)).toEqual(studio);
+ const built = JSON.parse((workerFiles().files as unknown as Record<string, string>)["runtime-files.json"]);
+ expect(built.files).toEqual(studio);
+ });
+
+ it("an entry is kept once by name, and only with a real SHA-256 and a whole positive size", () => {
+ const good = { file: "a.safetensors", sha256: "a".repeat(64), sizeBytes: 3 };
+ expect(runtimeFiles([good, { ...good, sizeBytes: 9 }, { file: "b.safetensors", sha256: "nope", sizeBytes: 3 }, { file: "c.safetensors", sha256: "c".repeat(64), sizeBytes: 0 }, { file: "d.safetensors", sha256: "d".repeat(64) }])).toEqual([
+ { folder: "loras", file: "a.safetensors", sizeBytes: 3, sha256: "a".repeat(64) },
+ ]);
+ });
+
+ it("the worker reads its built list, and none from a build without one", () => {
+ const dir = tempDir("fuobe-worker-runtime-list-");
+ const file = path.join(dir, "runtime-files.json");
+ expect(runtimeFileList(file)).toEqual([]);
+ const ok = { folder: "loras", file: "a.safetensors", sizeBytes: 3, sha256: "a".repeat(64) };
+ fs.writeFileSync(file, JSON.stringify({ files: [ok, { ...ok, file: "b.safetensors", sha256: "short" }, { ...ok, file: "c.safetensors", sizeBytes: "3" }, null] }));
+ expect(runtimeFileList(file)).toEqual([ok]);
+ });
+});
+
+describe("the worker's run-time files", () => {
+ const look = { folder: "loras", file: "look.safetensors", sizeBytes: 5, sha256: sha("LOOK!") };
+
+ it("are verified as the catalog's are: reported with their hash, never a copy of another size or hash", async () => {
+ const models = tempDir("fuobe-worker-runtime-");
+ fs.mkdirSync(path.join(models, "loras"));
+ fs.writeFileSync(path.join(models, "loras", "look.safetensors"), "LOOK!");
+ fs.writeFileSync(path.join(models, "loras", "other.safetensors"), "EVIL!");
+ fs.writeFileSync(path.join(models, "loras", "short.safetensors"), "hi");
+ const index = { files: {} };
+ const runtime = [look, { ...look, file: "other.safetensors" }, { ...look, file: "short.safetensors" }, { ...look, file: "missing.safetensors" }];
+ const cache = path.join(models, "hash-cache.json");
+ expect(await modelFiles([models], index, cache, {}, { runtime })).toEqual([{ folder: "loras", name: "look.safetensors", size: 5, sha256: sha("LOOK!") }]);
+ // None asked: only the catalog's own, as before.
+ expect(await modelFiles([models], index, cache, {})).toEqual([]);
+ });
+
+ it("a file the catalog names too counts once, with the catalog's pin", async () => {
+ const models = tempDir("fuobe-worker-runtime-twice-");
+ fs.mkdirSync(path.join(models, "loras"));
+ fs.writeFileSync(path.join(models, "loras", "look.safetensors"), "LOOK!");
+ const index = { files: { a: { folder: "loras", file: "look.safetensors", sizeBytes: 5 } } };
+ const found = await modelFiles([models], index, path.join(models, "hash-cache.json"), { "loras/look.safetensors": sha("LOOK!") }, { runtime: [look] });
+ expect(found).toEqual([{ folder: "loras", name: "look.safetensors", size: 5, sha256: sha("LOOK!") }]);
+ });
+
+ it('with fileCheck "size", a run-time file of the exact size counts until its hash is known', async () => {
+ const models = tempDir("fuobe-worker-runtime-size-");
+ fs.mkdirSync(path.join(models, "loras"));
+ fs.writeFileSync(path.join(models, "loras", "look.safetensors"), "LOOK!");
+ const found = await modelFiles([models], { files: {} }, path.join(models, "hash-cache.json"), {}, { runtime: [look], fileCheck: "size" });
+ expect(found).toEqual([{ folder: "loras", name: "look.safetensors", size: 5, sha256: look.sha256 }]);
+ });
+
+ it("a graph that loads a look's LoRA passes the worker's check only once that file is verified", () => {
+ const catalog = readCatalog(root);
+ const rules = inputRules(catalog);
+ const allowed = new Set(allowedNodeList(root, catalog));
+ const base = {
+ "1": { class_type: "UNETLoader", inputs: { unet_name: "z_image_turbo_bf16.safetensors", weight_dtype: "default" } },
+ "2": { class_type: "ModelSamplingAuraFlow", inputs: { model: ["1", 0], shift: 3 } },
+ };
+ const graph = injectLoras(base as never, [{ file: "AWPortrait-Z.safetensors", strength: 0.6 }]) as unknown as Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+ const own = [{ folder: "diffusion_models", name: "z_image_turbo_bf16.safetensors" }];
+ expect(graphCheck(graph, allowed, own, { rules, staged: [] })).toMatchObject({ reason: "model-unverified", cls: "LoraLoaderModelOnly", input: "lora_name" });
+ expect(graphCheck(graph, allowed, [...own, { folder: "loras", name: "AWPortrait-Z.safetensors" }], { rules, staged: [] })).toBeNull();
+ // The studio reads the same LoRA from the graph, as a file a worker must have.
+ expect(graphLoraNames(graph)).toEqual(["AWPortrait-Z.safetensors"]);
+ });
+});
+
+describe("a run's run-time files, as the studio reads them", () => {
+ const index = {
+ files: {
+ "loras/own.safetensors": { folder: "loras", file: "own.safetensors", sizeBytes: 4, sha256: "1".repeat(64) },
+ "loras/option.safetensors": { folder: "loras", file: "option.safetensors", sizeBytes: 6, sha256: "2".repeat(64) },
+ },
+ workflows: { wf: { files: ["loras/own.safetensors"] } },
+ } as unknown as Pick<RequirementIndex, "files" | "workflows">;
+ const library = [{ folder: "loras", file: "look.safetensors", sizeBytes: 5, sha256: "3".repeat(64) }];
+
+ it("leaves the workflow's own files to its lane, takes an index file by its entry, a library file by its pin, and names the rest", () => {
+ const r = runtimeNeeds(["own.safetensors", "option.safetensors", "look.safetensors", "mine.safetensors", "look.safetensors"], index, "wf", library);
+ expect(r.files).toEqual([
+ { folder: "loras", name: "option.safetensors", size: 6, sha256: "2".repeat(64) },
+ { folder: "loras", name: "look.safetensors", size: 5, sha256: "3".repeat(64) },
+ ]);
+ expect(r.unknown).toEqual(["mine.safetensors"]);
+ });
+
+ it("a worker has them only with the exact size and hash of each", () => {
+ const need = runtimeNeeds(["look.safetensors"], index, "wf", library).files;
+ const inv = (size: number, sha256: string) => ({ files: [{ folder: "loras", name: "look.safetensors", size, sha256 }], nodePacks: [] });
+ expect(hasFiles(inv(5, "3".repeat(64)), need)).toBe(true);
+ expect(hasFiles(inv(5, "4".repeat(64)), need)).toBe(false);
+ expect(hasFiles(inv(6, "3".repeat(64)), need)).toBe(false);
+ expect(hasFiles({ files: [], nodePacks: [] }, [])).toBe(true);
+ });
+
+ it("reads every LoRA loader's file from a graph, once each, and no placeholder", () => {
+ const g = {
+ "1": { class_type: "LoraLoaderModelOnly", inputs: { lora_name: "a.safetensors", model: ["0", 0] } },
+ "2": { class_type: "WanVideoLoraSelect", inputs: { lora: "sub\\b.safetensors", strength: 1 } },
+ "3": { class_type: "LoraLoader", inputs: { lora_name: "a.safetensors" } },
+ "4": { class_type: "LoraLoaderModelOnly", inputs: { lora_name: "None" } },
+ "5": { class_type: "CLIPTextEncode", inputs: { text: "lora_name a.safetensors" } },
+ "6": { class_type: "LoraLoaderModelOnly", inputs: { lora_name: ["7", 0] } },
+ };
+ expect(graphLoraNames(g)).toEqual(["a.safetensors", "sub/b.safetensors"]);
+ });
+});