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.

Workers: safe clip reads, the model copy ComfyUI loads, one worker per folder, and runs that finish

Adarsh0306519598e2
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjs
index ce256fc6..a9e3b9cd 100644
--- a/bin/lib/worker/comfy.mjs
+++ b/bin/lib/worker/comfy.mjs
@@ -68,16 +68,32 @@ export const folders = (workDir) => ({
temp: path.join(workDir, "temp"),
});
-/** extra_model_paths.yaml: the model folders, for reading. */
-export function modelPathsYaml(modelDirs, folderNames) {
+/**
+ * extra_model_paths.yaml: the model folders, for reading. With `o.first` (a ComfyUI that knows `is_default`), its search
+ * looks in them before anywhere else, in the order given: before its own models folder and the folders that its own
+ * extra_model_paths.yaml adds. ComfyUI puts each `is_default` folder at the front of its list, so they are written in
+ * reverse. The worker checks the copy that this search finds first (inventory.mjs).
+ */
+export function modelPathsYaml(modelDirs, folderNames, o = {}) {
const lines = [];
- modelDirs.forEach((dir, i) => {
- lines.push(`fuobe_worker_${i}:`, ` base_path: ${JSON.stringify(dir)}`);
+ const entries = modelDirs.map((dir, i) => [dir, i]);
+ for (const [dir, i] of o.first ? entries.reverse() : entries) {
+ lines.push(`fuobe_worker_${i}:`, ` base_path: ${JSON.stringify(dir)}`, ...(o.first ? [" is_default: true"] : []));
for (const f of folderNames) lines.push(` ${f}: ${f}`);
- });
+ }
return `${lines.join("\n")}\n`;
}
+/** This ComfyUI reads `is_default` in an extra_model_paths.yaml (an older one stops on it). */
+export function defaultPathsFlag(comfyDir) {
+ for (const file of [path.join(comfyDir ?? "", "utils", "extra_config.py"), path.join(comfyDir ?? "", "main.py")]) {
+ try {
+ if (fs.readFileSync(file, "utf8").includes("is_default")) return true;
+ } catch {}
+ }
+ return false;
+}
+
/** This ComfyUI can leave out its partner nodes (the paid API nodes): its own argument list names the flag. */
export function partnerFlag(comfyDir) {
try {
@@ -150,6 +166,22 @@ export function comfyEnv(env = process.env, extra = {}) {
return { ...out, ...OFFLINE_ENV };
}
+/**
+ * How long a request to its ComfyUI waits for the answer to begin: a plain request, one that sends a body (an input, a
+ * prompt), and the quick ones that the worker's main loop waits for (a look at its memory, freeing its memory).
+ */
+export const REQUEST_MS = { plain: 15_000, withBody: 120_000, loop: 5_000 };
+
+/**
+ * Python's flags for the guard: isolated mode (-I: neither the guard's folder nor the user's site folder is on the
+ * import path, and PYTHON* variables don't apply to it), with UTF-8 mode kept as PYTHONUTF8 asks (the guard applies
+ * PYTHONIOENCODING itself). ComfyUI's own child processes still get every variable of its environment.
+ */
+export function guardFlags(env = {}) {
+ const utf8 = env.PYTHONUTF8;
+ return ["-I", ...(utf8 === "1" || utf8 === "0" ? ["-X", `utf8=${utf8}`] : [])];
+}
+
/** At most this many times an hour its ComfyUI may stop by itself with no job running; then the worker pauses itself. */
export const MAX_RESTARTS_AN_HOUR = 3;
/** The wait before a start after its ComfyUI stopped: 5 s, then twice as long each time in a row, at most 2 minutes. */
@@ -226,7 +258,9 @@ export class OwnComfy {
/**
* @param cfg the worker's settings (comfyDir, workDir, port (pins one), modelDirs, comfyEnv, python; `comfyCommand`
* replaces the whole command, for tests, with {port} in it, and `comfyGuard` says that command keeps the guard)
- * @param o { now, log, fetch, folderNames, env (this PC's environment), commandLineOf, killTree, randomPort (tests) }
+ * @param o { now, log, fetch, folderNames, env (this PC's environment), commandLineOf, killTree, randomPort (tests),
+ * owner (the worker that starts it: { pid, id, script }, kept in the pid file), workerLives (does a worker that a pid
+ * file names still run?) }
*/
constructor(cfg, o = {}) {
this.cfg = cfg;
@@ -247,8 +281,9 @@ export class OwnComfy {
this.log = null;
}
+ /** This start's address (port 0, which nothing answers, while no ComfyUI of its own is up). */
get base() {
- return `http://127.0.0.1:${this.port ?? this.cfg.port ?? 0}`;
+ return `http://127.0.0.1:${this.port ?? 0}`;
}
get pid() {
@@ -289,17 +324,41 @@ export class OwnComfy {
return this.guarded && this.key ? { [GUARD.key]: this.key } : {};
}
- /** A request to its own ComfyUI (its address and key are this start's). */
- fetch(url, init = {}) {
+ /**
+ * A request to its own ComfyUI (its address and key are this start's), only while the process it started is up: never
+ * to whatever listens on an old port. A ComfyUI that takes the connection but doesn't answer is given up on after
+ * `answerMs` (REQUEST_MS.plain, or REQUEST_MS.withBody for a request with a body; `init.signal` replaces it). Only the
+ * wait for the answer counts: a long download of a result isn't cut short.
+ */
+ fetch(url, init = {}, answerMs = init.body ? REQUEST_MS.withBody : REQUEST_MS.plain) {
+ if (!this.alive() || !this.port) return Promise.reject(new Error("Its own ComfyUI isn't running"));
const headers = new Headers(init.headers);
for (const [k, v] of Object.entries(this.headers())) headers.set(k, v);
- return (this.o.fetch ?? fetch)(this.rebase(url), { ...init, headers }).then((res) => {
- this.answeredAt = (this.o.now ?? Date.now)();
- return res;
- });
+ let timer = null;
+ let signal = init.signal;
+ if (!signal) {
+ const ctrl = new AbortController();
+ timer = setTimeout(() => ctrl.abort(new Error("Its ComfyUI didn't answer in time")), answerMs);
+ timer.unref?.();
+ signal = ctrl.signal;
+ }
+ return (this.o.fetch ?? fetch)(this.rebase(url), { ...init, headers, signal }).then(
+ (res) => {
+ if (timer) clearTimeout(timer);
+ this.answeredAt = (this.o.now ?? Date.now)();
+ return res;
+ },
+ (e) => {
+ if (timer) clearTimeout(timer);
+ throw e;
+ },
+ );
}
- /** A ComfyUI left running by a worker that stopped without stopping it (its pid file says): stop it. True when it did. */
+ /**
+ * A ComfyUI left running by a worker that stopped without stopping it (its pid file says): stop it. True when it did.
+ * One whose worker still runs (another worker on this folder) is left alone, with its pid file.
+ */
async stopLeftover() {
let rec;
try {
@@ -307,6 +366,10 @@ export class OwnComfy {
} catch {
return false;
}
+ if (rec?.worker && rec.worker.id !== this.o.owner?.id && (await this.o.workerLives?.(rec.worker))) {
+ this.o.log?.("The ComfyUI in its pid file belongs to a worker that still runs: left alone.");
+ return false;
+ }
let stopped = false;
if (Number.isInteger(rec?.pid) && rec.pid > 0 && typeof rec.marker === "string" && rec.marker) {
// Only that process: its command line still names what this worker started (a reused pid doesn't).
@@ -321,51 +384,65 @@ export class OwnComfy {
return stopped;
}
- /** The process on the port proves it is the one the worker started, and has this start's key. */
+ /**
+ * The process on the port proves it has this start's key and is the one the worker started: its own process id, or
+ * its parent's (a venv's python.exe on Windows starts the real Python as a process of its own).
+ */
async proven(pid) {
const challenge = crypto.randomBytes(16).toString("hex");
- const r = await (this.o.fetch ?? fetch)(`${this.base}${GUARD.hello}`, { headers: { [GUARD.challenge]: challenge } });
+ const r = await (this.o.fetch ?? fetch)(`${this.base}${GUARD.hello}`, { headers: { [GUARD.challenge]: challenge }, signal: AbortSignal.timeout(REQUEST_MS.plain) });
if (!r.ok) return false;
const a = await r.json().catch(() => ({}));
const want = crypto.createHmac("sha256", this.key).update(challenge).digest("hex");
- if (typeof a.proof !== "string" || a.proof.length !== want.length || !crypto.timingSafeEqual(Buffer.from(a.proof), Buffer.from(want)) || a.pid !== pid) {
+ if (typeof a.proof !== "string" || a.proof.length !== want.length || !crypto.timingSafeEqual(Buffer.from(a.proof), Buffer.from(want)) || !(a.pid === pid || a.ppid === pid)) {
throw new PortBusy(`Another program answered on port ${this.port}`);
}
return true;
}
- /** Start its own ComfyUI and wait until it answers. Throws PortBusy when the port is taken, GuardMissing without the guard. */
- async start(packs = []) {
+ /**
+ * Start its own ComfyUI and wait until it answers. Throws PortBusy when the port is taken, GuardMissing without the
+ * guard. `o.signal` ends a start under way (its ComfyUI stops, and it throws).
+ */
+ async start(packs = [], o = {}) {
if (this.alive()) return;
+ const ended = () => new Error("Its ComfyUI's start was called off");
await this.stopLeftover();
this.port = await pickPort(this.cfg.port, this.o.randomPort);
if (!(await portFree(this.port))) throw new PortBusy(`Port ${this.port} is in use by another program`);
+ if (o.signal?.aborted) {
+ this.port = null;
+ throw ended();
+ }
const f = folders(this.cfg.workDir);
for (const dir of Object.values(f)) fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(path.join(this.cfg.workDir, "extra_model_paths.yaml"), modelPathsYaml(this.cfg.modelDirs ?? [], this.o.folderNames ?? []));
+ fs.writeFileSync(path.join(this.cfg.workDir, "extra_model_paths.yaml"), modelPathsYaml(this.cfg.modelDirs ?? [], this.o.folderNames ?? [], { first: defaultPathsFlag(this.cfg.comfyDir) }));
this.key = crypto.randomBytes(32).toString("hex");
let cmd;
let marker;
if (this.cfg.comfyCommand) {
cmd = this.cfg.comfyCommand.map((a) => String(a).replaceAll("{port}", String(this.port)));
marker = cmd.slice(1).find((a) => /[\\/]/.test(a)) ?? cmd.join(" ");
- } else {
- // The guard is written fresh into the worker folder at each start, and ComfyUI starts through it.
- const guard = path.join(this.cfg.workDir, "guard", "comfy_guard.py");
- fs.mkdirSync(path.dirname(guard), { recursive: true });
- fs.copyFileSync(path.join(here, "comfy_guard.py"), guard);
- cmd = [this.cfg.python || pythonFor(this.cfg.comfyDir), "-s", guard, path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs, { port: this.port, partnerFlag: partnerFlag(this.cfg.comfyDir) })];
- marker = guard;
}
this.crashes = this.crashes.filter((c) => (this.o.now ?? Date.now)() - c.at < 3_600_000);
this.expectExit = false;
this.ready = false;
const env = { ...comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv), ...(this.guarded && { [GUARD.env]: this.key }) };
+ if (!this.cfg.comfyCommand) {
+ // The guard is written into an emptied folder at each start (nothing else stays beside it), and ComfyUI starts
+ // through it in Python's isolated mode: no script folder, no user site and no PYTHON* variable on its import path.
+ const guard = path.join(this.cfg.workDir, "guard", "comfy_guard.py");
+ fs.rmSync(path.dirname(guard), { recursive: true, force: true });
+ fs.mkdirSync(path.dirname(guard), { recursive: true });
+ fs.copyFileSync(path.join(here, "comfy_guard.py"), guard);
+ cmd = [this.cfg.python || pythonFor(this.cfg.comfyDir), ...guardFlags(env), guard, path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs, { port: this.port, partnerFlag: partnerFlag(this.cfg.comfyDir) })];
+ marker = guard;
+ }
// Its working folder is the worker folder: a node that writes a relative path writes there, not into ComfyUI's.
const child = spawn(cmd[0], cmd.slice(1), { cwd: this.cfg.workDir, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
this.child = child;
this.startedAt = (this.o.now ?? Date.now)();
- if (child.pid) fs.writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, port: this.port, marker, at: this.startedAt }), { mode: 0o600 });
+ if (child.pid) fs.writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, port: this.port, marker, at: this.startedAt, worker: this.o.owner ?? null }), { mode: 0o600 });
this.log?.close();
const log = (this.log = new RotatingLog(path.join(this.cfg.workDir, "comfyui.log")));
child.stdout.on("data", (d) => log.write(d));
@@ -382,6 +459,10 @@ export class OwnComfy {
// Only now, with its own process up, does the worker talk to the port: first the proof, then with the key.
let proof = !this.guarded;
for (let i = 0; i < 360; i++) {
+ if (o.signal?.aborted) {
+ await this.stop();
+ throw ended();
+ }
if (!this.alive()) throw new Error("ComfyUI stopped while starting (see comfyui.log in the worker folder)");
try {
if (!proof) proof = await this.proven(child.pid);
@@ -390,7 +471,7 @@ export class OwnComfy {
if (r.ok) {
if (this.guarded) {
// Without the key it must refuse: else the guard isn't there, and the worker won't use this ComfyUI.
- const open = await (this.o.fetch ?? fetch)(`${this.base}/system_stats`).catch(() => null);
+ const open = await (this.o.fetch ?? fetch)(`${this.base}/system_stats`, { signal: AbortSignal.timeout(REQUEST_MS.plain) }).catch(() => null);
if (open?.status !== 403) {
await this.stop();
throw new GuardMissing("Its ComfyUI answered without the worker's guard");
@@ -430,16 +511,18 @@ export class OwnComfy {
}
this.child = null;
this.key = null;
+ // No address any more: nothing is sent to that port until the next start has proved its own process there.
+ this.port = null;
fs.rmSync(this.pidFile, { force: true });
this.log?.close();
this.log = null;
}
- /** Its own VRAM, from its own /system_stats (MB), or null. */
+ /** Its own VRAM, from its own /system_stats (MB), or null (also when it doesn't answer within REQUEST_MS.loop). */
async vramMb() {
if (!this.ready) return null;
try {
- const s = await (await this.fetch(`${this.base}/system_stats`)).json();
+ const s = await (await this.fetch(`${this.base}/system_stats`, { signal: AbortSignal.timeout(REQUEST_MS.loop) })).json();
const d = s?.devices?.[0];
const bytes = d?.torch_vram_total ?? null;
return typeof bytes === "number" ? Math.round(bytes / 2 ** 20) : null;
@@ -448,10 +531,13 @@ export class OwnComfy {
}
}
- /** Free its memory: models unloaded, caches emptied (before a retry after running out of memory). */
+ /**
+ * Free its memory: models unloaded, caches emptied (before a retry after running out of memory, and for local work
+ * after a turn). ComfyUI only notes the request, so it answers at once: it waits at most REQUEST_MS.loop.
+ */
async free() {
if (!this.ready) return;
- await this.fetch(`${this.base}/free`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ unload_models: true, free_memory: true }) }).catch(() => null);
+ await this.fetch(`${this.base}/free`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ unload_models: true, free_memory: true }) }, REQUEST_MS.loop).catch(() => null);
}
/** Nothing of a job stays in it: the running prompt stopped, the queue and the whole history emptied. */
diff --git a/bin/lib/worker/comfy_guard.py b/bin/lib/worker/comfy_guard.py
index 675187b6..675282d5 100644
--- a/bin/lib/worker/comfy_guard.py
+++ b/bin/lib/worker/comfy_guard.py
@@ -11,8 +11,12 @@ X-Fuobe-Worker-Key. A web page that points its own name at 127.0.0.1 (DNS rebind
nothing.
One request needs no key: GET /fuobe-worker/hello with X-Fuobe-Worker-Challenge (16 to 128 hex digits). The answer is
-the challenge signed with the key (HMAC-SHA-256) and this process's id. The worker checks both before it sends the key,
-so a program that took the port first never learns it.
+the challenge signed with the key (HMAC-SHA-256), this process's id and its parent's (a venv's python.exe on Windows
+starts the real Python as a child of its own). The worker checks both before it sends the key, so a program that took
+the port first never learns it.
+
+The worker starts this file in Python's isolated mode (-I), so its own folder is never on the import path. That mode
+also ignores PYTHONIOENCODING, which this file applies to its output itself.
Only the Python standard library and aiohttp (which ComfyUI needs anyway).
"""
@@ -58,7 +62,7 @@ def make_middleware(web, key: str, host: str):
challenge = request.headers.get(CHALLENGE_HEADER, "")
if not CHALLENGE.match(challenge):
return web.Response(status=403)
- return web.json_response({"proof": proof(key, challenge), "pid": os.getpid()})
+ return web.json_response({"proof": proof(key, challenge), "pid": os.getpid(), "ppid": os.getppid()})
if not allowed(request.headers, key, host):
return web.Response(status=403)
return await handler(request)
@@ -87,7 +91,22 @@ def port_of(args: list[str]) -> int:
raise SystemExit("The worker's guard needs --port")
+def output_encoding(env) -> None:
+ """PYTHONIOENCODING ("encoding[:errors]") for this process's output, as Python applies it outside isolated mode."""
+ value = env.get("PYTHONIOENCODING", "")
+ if not value or not sys.flags.ignore_environment:
+ return
+ encoding, _, errors = value.partition(":")
+ options = {k: v for k, v in (("encoding", encoding), ("errors", errors)) if v}
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(**options)
+ except (AttributeError, LookupError, ValueError):
+ pass
+
+
def main(argv: list[str]) -> None:
+ output_encoding(os.environ)
key = os.environ.pop(KEY_ENV, "")
if len(key) < 32:
raise SystemExit("The worker's guard has no key: start ComfyUI from the worker")
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index 1ea04abd..ee9f111d 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -4,7 +4,8 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-export const PROTOCOL = 1;
+/** 2: it says which inputs it takes, makes every clip and sound again, and keeps its ComfyUI behind the guard. */
+export const PROTOCOL = 2;
/** Where the worker keeps its settings: %LOCALAPPDATA%\FuobeWorker on Windows, ~/.config/fuobe-worker elsewhere. */
export function workerHome(env = process.env, home = os.homedir()) {
@@ -16,12 +17,14 @@ export function workerHome(env = process.env, home = os.homedir()) {
export const DEFAULTS = {
/** Its ComfyUI's port: none set takes a free one at random at each start (`port` in worker.json pins one). */
port: null,
- /** A job that makes no progress for this many minutes goes back to the line, and a stuck ComfyUI is started again. */
- stallMin: 10,
+ // stallMin (no default): a job that makes no progress for this many minutes goes back to the line. The studio gives
+ // its limit with each job; a stallMin in worker.json wins over it on this PC.
/** Its ComfyUI answering nothing for this many minutes is stuck: the worker stops it and starts it again. */
hungMin: 3,
- /** ffmpeg, which makes every clip and sound again before its ComfyUI reads them. None: the worker takes pictures only. */
- ffmpeg: null,
+ // ffmpeg (no default): the ffmpeg that makes every clip and sound again before its ComfyUI reads them. Not in
+ // worker.json: the ffmpeg on the PATH, when there is one. null or "-": none, and the worker takes pictures only.
+ /** A studio address with http:// on a private network (10.x, 172.16-31.x, 192.168.x, fd00::/8): allowed only when true. */
+ allowHttpSite: false,
/** Another program's VRAM above this pauses the worker. */
busyVramMb: 1024,
/** The automatic resume: off unless switched on for this PC (here, or on the studio's Workers page). */
@@ -81,6 +84,15 @@ export function loadConfig(home, env = process.env) {
export const saveConfig = (home, c) => writePrivate(file(home, "worker.json"), c);
+/** worker.json as saved: no defaults, no token or address from the environment. */
+export const savedConfig = (home) => {
+ const c = readJson(file(home, "worker.json"), {});
+ return c && typeof c === "object" && !Array.isArray(c) ? c : {};
+};
+
+/** The ffmpeg to use: worker.json's, else the PATH's when worker.json doesn't name one; null for none ("-" or null). */
+export const ffmpegOf = (cfg) => (cfg.ffmpeg === undefined ? "ffmpeg" : cfg.ffmpeg && cfg.ffmpeg !== "-" ? String(cfg.ffmpeg) : null);
+
/** The pause switch on this PC: { paused, now, until, at }. */
export const readControl = (home) => readJson(file(home, "control.json"), { paused: false });
export const writeControl = (home, c) => writePrivate(file(home, "control.json"), { ...c, at: Date.now() });
diff --git a/bin/lib/worker/hold.mjs b/bin/lib/worker/hold.mjs
index 6ea84165..2ab12d7c 100644
--- a/bin/lib/worker/hold.mjs
+++ b/bin/lib/worker/hold.mjs
@@ -2,7 +2,9 @@
// studio hears of it, the worker copies every file the job's history entries name into hold/<task id>/ with a note of
// the entries (held.json). The results stay there until the studio has them all. If the worker or its ComfyUI stops in
// between, the next claim gives the job back to this worker, and it uploads the kept files from where the studio's copy
-// got to, instead of running the job again. Kept results of a job that is no longer this worker's are deleted.
+// got to, instead of running the job again. The beat names the jobs kept here, so a pause doesn't send them back in
+// line. Kept results are deleted when the studio has them all, when the worker takes another job, when the studio no
+// longer has the job, or after a day.
import fs from "node:fs";
import path from "node:path";
import { Readable } from "node:stream";
@@ -114,6 +116,35 @@ export class Hold {
if (TASK_ID.test(String(id))) fs.rmSync(path.join(this.dir, id), { recursive: true, force: true });
}
+ /**
+ * Let go of kept results older than `maxAgeMs` (by the time they were kept), and of anything else in the folder that
+ * old (a copy that stopped halfway). Returns the task ids let go.
+ */
+ expire(now, maxAgeMs) {
+ let names = [];
+ try {
+ names = fs.readdirSync(this.dir);
+ } catch {
+ return [];
+ }
+ const gone = [];
+ for (const name of names) {
+ const p = path.join(this.dir, name);
+ let at = this.has(name) ? Number(this.note(name)?.at) : NaN;
+ if (!Number.isFinite(at)) {
+ try {
+ at = fs.statSync(p).mtimeMs;
+ } catch {
+ continue;
+ }
+ }
+ if (now - at < maxAgeMs) continue;
+ fs.rmSync(p, { recursive: true, force: true });
+ gone.push(name);
+ }
+ return gone;
+ }
+
/** Let go of every task's kept results but `keep`'s, and of anything else in the folder. */
dropAllBut(keep = null) {
let names = [];
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjs
index 668e1ddd..8ff5490d 100644
--- a/bin/lib/worker/index.mjs
+++ b/bin/lib/worker/index.mjs
@@ -2,7 +2,7 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { loadConfig, parseFor, readControl, readStatus, saveConfig, syncedFolder, workerHome, writeControl } from "./config.mjs";
+import { loadConfig, parseFor, readControl, readStatus, saveConfig, savedConfig, syncedFolder, workerHome, writeControl } from "./config.mjs";
import { installScript } from "./install.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
@@ -25,16 +25,6 @@ export async function choosePause(io) {
return null;
}
-/** worker.json as saved (no defaults, no token from the environment). */
-function savedConfig(home) {
- try {
- const c = JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8"));
- return c && typeof c === "object" ? c : {};
- } catch {
- return {};
- }
-}
-
/** The worker command. Returns the exit code. */
export async function worker(args, io) {
const [sub = "status", ...rest] = args;
@@ -53,8 +43,8 @@ export async function worker(args, io) {
io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");
return 2;
}
- const { runWorker, siteProblem } = await import("./run.mjs");
- const problem = siteProblem(cfg.site);
+ const { runWorker, siteProblem, withoutOldPort } = await import("./run.mjs");
+ const problem = siteProblem(cfg.site, cfg);
if (problem) {
io.stderr.write(`${problem} Run: fuobe worker setup\n`);
return 2;
@@ -63,10 +53,17 @@ export async function worker(args, io) {
// Ctrl+C, or a stop from the system: the worker stops its ComfyUI and cleans up before it exits (finished results
// stay for its next start).
const off = (io.onStop ?? io.onInterrupt)?.(() => ctrl.abort());
- say(`Fuobe worker for ${cfg.site}. ${cfg.port ? `Its own ComfyUI uses port ${cfg.port}` : "Its own ComfyUI takes a free local port at each start"}. Ctrl+C stops it.`);
+ const port = withoutOldPort(cfg).port;
+ say(`Fuobe worker for ${cfg.site}. ${port ? `Its own ComfyUI uses port ${port}` : "Its own ComfyUI takes a free local port at each start"}. Ctrl+C stops it.`);
let why;
try {
why = await runWorker(cfg, { home, signal: ctrl.signal });
+ } catch (e) {
+ // Another worker runs on this worker folder: this one leaves it alone. Not 0, so a scheduled start tries again later.
+ const { WorkerRunning } = await import("./lock.mjs");
+ if (!(e instanceof WorkerRunning)) throw e;
+ io.stderr.write(`${e.message}\n`);
+ return 4;
} finally {
off?.();
}
@@ -121,15 +118,23 @@ export async function worker(args, io) {
}
case "baseline": {
// The desktop's usual share of the GPU, for studio jobs first. Local ComfyUI work may stay open; it isn't counted.
- const { measureBaseline } = await import("./local-work.mjs");
- const mb = await measureBaseline(loadConfig(home, io.env), io.gpu ?? {});
- if (mb === null) {
+ // The worker's own ComfyUI isn't counted either, so the worker may keep running.
+ const { BASELINE_CAP_MB, measureBaseline } = await import("./local-work.mjs");
+ const m = await measureBaseline(loadConfig(home, io.env), io.gpu ?? {});
+ if (m === null) {
io.stderr.write("Couldn't read the GPU counters or the port table on this PC, so nothing changed.\n");
return 1;
}
- saveConfig(home, { ...savedConfig(home), desktopBaselineMb: mb });
- say(`The desktop uses about ${mb} MB of the GPU's memory. Saved as desktopBaselineMb in worker.json.`);
- say("Measure again with no game or other GPU program open if that number looks too high.");
+ saveConfig(home, { ...savedConfig(home), desktopBaselineMb: m.mb });
+ say(`The GPU's memory in use: ${m.usedMb} MB. Not counted: the worker's own ComfyUI (${m.ownMb} MB) and local ComfyUI work (${m.workMb} MB).`);
+ if (m.top.length) say(`Counted: ${m.measuredMb} MB, mostly ${m.top.map((p) => `${p.name} (process ${p.pid}, ${p.mb} MB)`).join(", ")}.`);
+ if (m.capped) {
+ say(`That is more than a desktop uses: another GPU program was open. Saved ${BASELINE_CAP_MB} MB as desktopBaselineMb in worker.json, the most it saves.`);
+ say("Close the programs above and measure again.");
+ } else {
+ say(`The desktop uses about ${m.mb} MB of the GPU's memory. Saved as desktopBaselineMb in worker.json.`);
+ say("Measure again with no game or other GPU program open if that number looks too high.");
+ }
return 0;
}
case "install": {
@@ -163,8 +168,8 @@ async function setup(home, io, say) {
const ask = async (q, def, o = {}) => ((await io.ask(`${q}${def ? ` [${def}]` : ""}: `, o)) || def || "").trim();
say("Set up this PC as a Fuobe worker. It takes the studio's jobs over HTTPS and runs them on its own ComfyUI.");
const site = await ask("The studio's address", old.site ?? "https://");
- const { siteProblem } = await import("./run.mjs");
- const bad = siteProblem(site);
+ const { OLD_SETUP_PORT, siteProblem } = await import("./run.mjs");
+ const bad = siteProblem(site, old);
if (bad) {
io.stderr.write(`${bad}\n`);
return 2;
@@ -190,10 +195,10 @@ async function setup(home, io, say) {
}
// ffmpeg makes every clip and sound again before its ComfyUI reads them. Without it, the worker takes pictures only.
const { ffmpegVersion } = await import("./media.mjs");
- const ffmpegAnswer = await ask("ffmpeg's path, for clips and sound (leave empty for pictures only)", old.ffmpeg ?? ((await ffmpegVersion("ffmpeg")) ? "ffmpeg" : ""));
+ const ffmpegAnswer = await ask("ffmpeg's path, for clips and sound (- for pictures only)", old.ffmpeg ?? ((await ffmpegVersion("ffmpeg")) ? "ffmpeg" : "-"));
const ffmpeg = ffmpegAnswer && ffmpegAnswer !== "-" ? ffmpegAnswer : null;
if (ffmpeg && !(await ffmpegVersion(ffmpeg))) {
- io.stderr.write(`There's no working ffmpeg at ${ffmpeg}. Give its full path, or leave it empty for pictures only.\n`);
+ io.stderr.write(`There's no working ffmpeg at ${ffmpeg}. Give its full path, or - for pictures only.\n`);
return 2;
}
const autoResume = /^y/i.test(await ask("Resume by itself when the GPU has been free for 10 minutes? (y/N)", old.autoResume ? "y" : "n"));
@@ -203,8 +208,12 @@ async function setup(home, io, say) {
const { spawnSync } = await import("node:child_process");
spawnSync("attrib", ["+I", workDir], { windowsHide: true });
}
- // No port is kept: its ComfyUI takes a free one at random at each start (`port` in worker.json pins one by hand).
- saveConfig(home, { ...old, port: null, site: site.replace(/\/+$/, ""), token: token || old.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume });
+ // A port pinned by hand stays; the one every older setup saved (8190) goes, so its ComfyUI takes a free port at random
+ // at each start. Only what was asked here changes: the rest of worker.json stays as it was, with no defaults written in.
+ const saved = savedConfig(home);
+ const port = Number(saved.port) === OLD_SETUP_PORT ? null : (saved.port ?? null);
+ // A token given in FUOBE_WORKER_TOKEN stays out of the file.
+ saveConfig(home, { ...saved, port, site: site.replace(/\/+$/, ""), token: token || saved.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume });
writeControl(home, { paused: true, now: false, until: null });
say(`Saved in ${path.join(home, "worker.json")} (readable by you only). The worker starts paused here.`);
say("Next: fuobe worker run. Resume it here with fuobe worker resume, and on the website in Settings → Workers.");
diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjs
index e5729895..666ab83d 100644
--- a/bin/lib/worker/inventory.mjs
+++ b/bin/lib/worker/inventory.mjs
@@ -4,6 +4,7 @@
// 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 os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -70,12 +71,109 @@ function gitCommit(dir) {
}
}
+/** ComfyUI's older folder names and the ones they stand for (its folder_paths.map_legacy). */
+const LEGACY = { unet: "diffusion_models", clip: "text_encoders" };
+/** ComfyUI's own models folder: the subfolders it reads for a folder name, where they aren't just that name. */
+const OWN_SUBFOLDERS = { diffusion_models: ["unet", "diffusion_models"], text_encoders: ["text_encoders", "clip"] };
+const canonical = (folder) => LEGACY[folder] ?? folder;
+
+/** A path from an extra_model_paths.yaml with ~ and environment variables ($X, ${X}, and %X% on Windows) filled in. */
+function expand(p, env, home) {
+ const vars = (name, whole) => env[name] ?? env[Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase()) ?? ""] ?? whole;
+ let out = String(p).replace(/\$\{([^}]+)\}|\$(\w+)/g, (whole, a, b) => vars(a ?? b, whole));
+ if (process.platform === "win32") out = out.replace(/%([^%]+)%/g, (whole, a) => vars(a, whole));
+ return /^~(?=$|[\\/])/.test(out) ? path.join(home, out.slice(1)) : out;
+}
+
+const unquote = (v) => {
+ const s = v.trim();
+ if (s.length >= 2 && s[0] === '"' && s.at(-1) === '"') {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return s.slice(1, -1);
+ }
+ }
+ return s.length >= 2 && s[0] === "'" && s.at(-1) === "'" ? s.slice(1, -1).replaceAll("''", "'") : s;
+};
+
+/**
+ * The folders an extra_model_paths.yaml adds, as ComfyUI reads it (utils/extra_config.py): { folder name → [folders] }.
+ * It reads the shape ComfyUI's example uses: entries of `base_path`, `is_default` and `name: subfolder` (or a `|` block
+ * with one subfolder a line), a subfolder joined to base_path, or to the file's own folder when it isn't a full path.
+ * @param {string} text
+ * @param {string} yamlDir
+ * @param {Record<string, string | undefined>} [env]
+ * @param {string} [home]
+ * @returns {Record<string, string[]>}
+ */
+export function yamlModelDirs(text, yamlDir, env = process.env, home = os.homedir()) {
+ const entries = [];
+ let entry = null;
+ const lines = String(text).split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].replace(/(^|\s)#.*$/, "");
+ if (!line.trim()) continue;
+ const indent = line.length - line.trimStart().length;
+ if (indent === 0) {
+ entry = /^[^:]+:\s*$/.test(line) ? {} : null;
+ if (entry) entries.push(entry);
+ continue;
+ }
+ const m = /^\s+([^:\s][^:]*?)\s*:\s*(.*)$/.exec(line);
+ if (!entry || !m) continue;
+ let value = m[2];
+ if (/^[|>][+-]?$/.test(value.trim())) {
+ // A block: the lines indented more than this one, each one subfolder.
+ const block = [];
+ while (i + 1 < lines.length && (!lines[i + 1].trim() || lines[i + 1].length - lines[i + 1].trimStart().length > indent)) block.push(lines[++i].trim());
+ value = block.filter(Boolean).join("\n");
+ } else value = unquote(value);
+ entry[m[1]] = value;
+ }
+ const out = {};
+ for (const e of entries) {
+ let base = typeof e.base_path === "string" && e.base_path ? expand(e.base_path, env, home) : null;
+ if (base && !path.isAbsolute(base)) base = path.resolve(yamlDir, base);
+ for (const [name, value] of Object.entries(e)) {
+ if (name === "base_path" || name === "is_default" || typeof value !== "string") continue;
+ for (const sub of value.split("\n").map((s) => s.trim()).filter(Boolean)) {
+ const full = base ? path.join(base, sub) : path.isAbsolute(sub) ? sub : path.resolve(yamlDir, sub);
+ (out[canonical(name)] ??= []).push(path.normalize(full));
+ }
+ }
+ }
+ return out;
+}
+
/**
- * The verified files: for every file the catalog names, found in one of the model folders under its folder with the
- * 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.
+ * Where ComfyUI itself also looks for a folder's files, outside the worker's model folders: its own models folder (which
+ * some node packs read directly), and the folders its own extra_model_paths.yaml adds.
*/
-export async function modelFiles(modelDirs, index, cacheFile, pins = filePins()) {
+export function comfyModelDirs(comfyDir, env = process.env, home = os.homedir()) {
+ if (!comfyDir) return () => [];
+ let fromYaml = {};
+ try {
+ fromYaml = yamlModelDirs(fs.readFileSync(path.join(comfyDir, "extra_model_paths.yaml"), "utf8"), comfyDir, env, home);
+ } catch {}
+ return (folder) => {
+ const name = canonical(folder);
+ return [...(OWN_SUBFOLDERS[name] ?? [name]).map((sub) => path.join(comfyDir, "models", sub)), ...(fromYaml[name] ?? [])];
+ };
+}
+
+/** The same file, by its full path (whatever its case on Windows). */
+const samePath = (a, b) => (process.platform === "win32" ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
+
+/**
+ * The verified files: for every file the catalog names with a pinned SHA-256 (`pins`, else the index's own), the copy
+ * that ComfyUI finds first, with the exact size and that hash. ComfyUI looks in the model folders in order and takes the
+ * first one that has the file, so only that copy counts: one of the wrong size or with another hash isn't reported,
+ * even when a later folder has a good copy. 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.
+ */
+export async function modelFiles(modelDirs, index, cacheFile, pins = filePins(), o = {}) {
const cache = (() => {
try {
return JSON.parse(fs.readFileSync(cacheFile, "utf8"));
@@ -83,25 +181,48 @@ export async function modelFiles(modelDirs, index, cacheFile, pins = filePins())
return {};
}
})();
+ const elsewhere = comfyModelDirs(o.comfyDir, o.env, o.home);
+ /** The file at `p` (or null when there's none), and whether it is the pinned one. */
+ const look = async (p, f, want) => {
+ let st;
+ try {
+ st = fs.statSync(p);
+ } catch {
+ return null;
+ }
+ if (!st.isFile()) return null;
+ if (st.size !== f.sizeBytes) return { ok: false };
+ const key = `${p}|${st.size}|${st.mtimeMs}`;
+ const sha = cache[key] ?? (cache[key] = await sha256File(p));
+ return { ok: sha === want, size: st.size, sha };
+ };
const out = [];
for (const f of Object.values(index.files ?? {})) {
const want = pins[`${f.folder}/${f.file}`] ?? f.sha256;
if (typeof want !== "string" || !/^[0-9a-f]{64}$/.test(want)) continue;
+ let first = null;
+ let firstPath = null;
for (const root of modelDirs ?? []) {
const p = path.join(root, f.folder, f.file);
- let st;
- try {
- st = fs.statSync(p);
- } catch {
- continue;
+ first = await look(p, f, want);
+ if (first) {
+ firstPath = p;
+ break;
+ }
+ }
+ if (!first?.ok) continue;
+ let shadowed = false;
+ for (const dir of elsewhere(f.folder)) {
+ const p = path.join(dir, f.file);
+ if (samePath(p, firstPath)) continue;
+ const other = await look(p, f, want);
+ if (other && !other.ok) {
+ shadowed = true;
+ break;
}
- if (!st.isFile() || st.size !== f.sizeBytes) 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;
}
+ if (shadowed) continue;
+ out.push({ folder: f.folder, name: f.file, size: first.size, sha256: first.sha });
}
try {
fs.writeFileSync(cacheFile, JSON.stringify(cache));
diff --git a/bin/lib/worker/local-work.mjs b/bin/lib/worker/local-work.mjs
index 72e0661c..3f73d495 100644
--- a/bin/lib/worker/local-work.mjs
+++ b/bin/lib/worker/local-work.mjs
@@ -13,6 +13,7 @@
// usual share (measured at setup).
import { execFile } from "node:child_process";
import fs from "node:fs";
+import path from "node:path";
import { CONTEXT_ALLOWANCE_MB } from "./gpu.mjs";
/** ComfyUI's own default port and the next few: where local ComfyUIs listen unless worker.json says otherwise. */
@@ -192,9 +193,26 @@ export function splitMemory(o) {
return { ownMb: torchOwn, workMb: 0, othersMb: rest, who: o.lock !== null && o.lock !== undefined ? "another program" : (named ?? "another program"), work: { pids: [], port: null }, source: o.lock !== null && o.lock !== undefined ? "lock" : "total" };
}
+/** The most `fuobe worker baseline` saves: a desktop alone uses less, so more means another program was open. */
+export const BASELINE_CAP_MB = 4096;
+
+/** The worker's own ComfyUI as its pid file in the worker folder says ({ pid, port }), or null when it has none. */
+export function ownComfyOf(workDir) {
+ try {
+ const rec = JSON.parse(fs.readFileSync(path.join(workDir, "comfyui.pid"), "utf8"));
+ const pid = Number.isInteger(rec?.pid) && rec.pid > 0 ? rec.pid : null;
+ const port = Number.isInteger(rec?.port) && rec.port > 0 ? rec.port : null;
+ return pid || port ? { pid, port } : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* The desktop's usual share of the GPU, measured once at setup with no game or other GPU program open: the used memory
- * minus local ComfyUI work, from the counters. Null when the counters or the port table can't be read.
+ * minus local ComfyUI work and minus the worker's own ComfyUI (by its pid file: its process, and the one on its port),
+ * from the counters. Null when the counters or the port table can't be read. Otherwise { mb (what to save: at most
+ * BASELINE_CAP_MB), measuredMb, capped, usedMb, ownMb, workMb, top (the biggest of the rest: [{ name, pid, mb }]) }.
*/
export async function measureBaseline(cfg, deps = {}) {
const { readGpu } = await import("./gpu.mjs");
@@ -203,6 +221,18 @@ export async function measureBaseline(cfg, deps = {}) {
const counters = await (deps.readCounters ?? readCounters)(cfg.gpuCounters);
const listing = counters ? await (deps.readListeners ?? readListeners)(cfg.powershell) : null;
if (!counters || !listing) return null;
- const split = splitMemory({ usedMb: reading.usedMb, apps: reading.apps, counters, listing, own: { pid: null, port: null, running: false, mb: null }, ports: cfg.localComfyPorts, excludePorts: cfg.localComfyExcludePorts, excludePids: cfg.localComfyExcludePids, baselineMb: 0, gpu: cfg.gpuLuid });
- return Math.round(split.othersMb);
+ const mine = cfg.workDir ? ownComfyOf(cfg.workDir) : null;
+ const own = { pid: mine?.pid ?? null, port: mine?.port ?? null, running: false, mb: null };
+ const o = { ports: cfg.localComfyPorts, excludePorts: cfg.localComfyExcludePorts, excludePids: cfg.localComfyExcludePids };
+ const split = splitMemory({ usedMb: reading.usedMb, apps: reading.apps, counters, listing, own, ...o, baselineMb: 0, gpu: cfg.gpuLuid });
+ // The rest, by process, for the owner to see what was counted.
+ const pids = workPids(listing, { ...o, ownPid: own.pid, ownPort: own.port });
+ const gpu = pickGpu(counters, cfg.gpuLuid);
+ const top = counters
+ .filter((c) => c.gpu === gpu && c.mb > 0 && !pids.own.has(c.pid) && !pids.work.has(c.pid))
+ .sort((a, b) => b.mb - a.mb)
+ .slice(0, 5)
+ .map((c) => ({ pid: c.pid, mb: Math.round(c.mb), name: listing.names?.[c.pid] ?? reading.apps?.find((a) => a.pid === c.pid)?.name ?? "a program" }));
+ const measuredMb = Math.round(split.othersMb);
+ return { mb: Math.min(measuredMb, BASELINE_CAP_MB), measuredMb, capped: measuredMb > BASELINE_CAP_MB, usedMb: Math.round(reading.usedMb), ownMb: Math.round(split.ownMb), workMb: Math.round(split.workMb), top };
}
diff --git a/bin/lib/worker/lock.mjs b/bin/lib/worker/lock.mjs
new file mode 100644
index 00000000..9c7cb2c0
--- /dev/null
+++ b/bin/lib/worker/lock.mjs
@@ -0,0 +1,98 @@
+// One worker at a time on a worker folder (docs/gpu-workers.md). A second `fuobe worker run` with the same folder (by
+// hand while the scheduled task's worker runs, say) would stop the first one's ComfyUI, empty its folders and take its
+// job, so it refuses to start instead. The lock is worker.lock in the worker folder: { pid, id, script, at }. A lock
+// whose worker has stopped (its process is gone, or its process id now belongs to another program) is taken over.
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { commandLineOf } from "./comfy.mjs";
+
+/** Another worker runs on this worker folder. */
+export class WorkerRunning extends Error {
+ constructor(pid, file) {
+ super(`Another worker is running on this worker folder (process ${pid}). Stop it first: Ctrl+C in its window, or end the "Fuobe worker" task. If no worker runs, delete ${file}.`);
+ this.pid = pid;
+ }
+}
+
+/** The locks this process holds now: lock file → its id (two workers in one process are told apart by it). */
+const held = new Map();
+
+const key = (file) => (process.platform === "win32" ? path.resolve(file).toLowerCase() : path.resolve(file));
+
+/** Is a process with this id running? (One that can't be signalled for lack of rights runs.) */
+function running(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return e?.code === "EPERM";
+ }
+}
+
+/**
+ * Does the worker that a lock (or a ComfyUI's pid file) names still run? In this process: while it holds its lock. In
+ * another: while that process runs and its command line is a worker's (`fuobe … worker`, or the script it named). A
+ * command line that can't be read counts as a worker's, so nothing is taken from a worker that might still run.
+ * `o.commandLineOf` replaces the lookup (tests).
+ */
+export async function workerLives(rec, o = {}) {
+ const pid = Number(rec?.pid);
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ if (pid === process.pid) return [...held.values()].includes(rec.id);
+ if (!running(pid)) return false;
+ const line = await (o.commandLineOf ?? commandLineOf)(pid);
+ if (line === null || line === undefined) return true;
+ return (typeof rec.script === "string" && rec.script.length > 0 && line.includes(rec.script)) || (/fuobe/i.test(line) && /\bworker\b/i.test(line));
+}
+
+/**
+ * Take the worker folder's lock, or throw WorkerRunning. Returns { owner: { pid, id, script }, release }: release lets
+ * go of it (only of this lock, never of one another worker took over since).
+ */
+export async function takeLock(workDir, o = {}) {
+ const file = path.join(workDir, "worker.lock");
+ const me = { pid: process.pid, id: crypto.randomBytes(8).toString("hex"), script: process.argv[1] ?? "", at: Date.now() };
+ for (let i = 0; i < 3; i++) {
+ try {
+ fs.writeFileSync(file, JSON.stringify(me), { flag: "wx", mode: 0o600 });
+ held.set(key(file), me.id);
+ const release = () => {
+ if (held.get(key(file)) !== me.id) return;
+ held.delete(key(file));
+ try {
+ if (JSON.parse(fs.readFileSync(file, "utf8")).id === me.id) fs.rmSync(file, { force: true });
+ } catch {}
+ };
+ return { owner: { pid: me.pid, id: me.id, script: me.script }, release };
+ } catch (e) {
+ if (e?.code !== "EEXIST") throw e;
+ }
+ let rec = null;
+ try {
+ rec = JSON.parse(fs.readFileSync(file, "utf8"));
+ } catch {}
+ if (rec && (await workerLives(rec, o))) throw new WorkerRunning(rec.pid, file);
+ // Its worker stopped without letting go (or the file is half written): take it over.
+ if (!rec) {
+ // A lock being written right now: give it a moment before calling it broken.
+ const age = (() => {
+ try {
+ return Date.now() - fs.statSync(file).mtimeMs;
+ } catch {
+ return Infinity;
+ }
+ })();
+ if (age < 2_000) {
+ await new Promise((r) => setTimeout(r, 2_000 - age));
+ continue;
+ }
+ }
+ fs.rmSync(file, { force: true });
+ }
+ let rec = null;
+ try {
+ rec = JSON.parse(fs.readFileSync(file, "utf8"));
+ } catch {}
+ throw new WorkerRunning(rec?.pid ?? "unknown", file);
+}
diff --git a/bin/lib/worker/media.mjs b/bin/lib/worker/media.mjs
index d45092e2..af782af4 100644
--- a/bin/lib/worker/media.mjs
+++ b/bin/lib/worker/media.mjs
@@ -3,7 +3,12 @@
// file (metadata, chapters, subtitles, attachments, data streams) is kept. Only ffmpeg ever reads the file as it came,
// in its own short-lived process at low priority. A worker without ffmpeg takes pictures only: it says so in its
// inventory, so no job that reads a clip or a sound comes to it.
+//
+// ffmpeg reads the file only as a plain local file in one of a short list of container formats: no playlist, list or
+// reference format that would make it open other files or addresses. What it writes has limits too: at most an hour,
+// at most 4096 pixels on the long side, and a size cap. A result that reaches the cap is refused.
import { execFile, spawn } from "node:child_process";
+import fs from "node:fs";
import os from "node:os";
const VIDEO_EXT = new Set(["mp4", "m4v", "mov", "mkv", "webm", "avi", "gif", "mpg", "mpeg", "wmv", "flv", "3gp", "ts", "mts", "m2ts"]);
@@ -29,7 +34,25 @@ export function mediaKind(input, graph) {
return null;
}
-const EVEN = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2"];
+/**
+ * What a clip or a sound made again may be: at most `maxSeconds` long and `maxSide` pixels on its long side, and at
+ * most `bytesPerInput` times its input's size, never under `minBytes` and never over `maxBytes`.
+ */
+export const MEDIA_LIMITS = { maxSeconds: 3600, maxSide: 4096, maxBytes: 2 * 2 ** 30, minBytes: 256 * 2 ** 20, bytesPerInput: 8 };
+
+/** The size cap of what ffmpeg writes for an input of `inputBytes`. */
+export const outputCap = (inputBytes) => Math.min(MEDIA_LIMITS.maxBytes, Math.max(MEDIA_LIMITS.minBytes, MEDIA_LIMITS.bytesPerInput * (Number(inputBytes) || 0)));
+
+/**
+ * The container formats ffmpeg may read a job's file as (its readers' names: "mov" covers MP4, MOV, M4A and 3GP, and
+ * "matroska" covers MKV and WebM). No playlist, list or reference format.
+ */
+export const INPUT_FORMATS = ["mov", "matroska", "avi", "gif", "mpegts", "mpeg", "flv", "asf", "wav", "mp3", "flac", "ogg", "aac", "aiff"];
+
+/** Down to `maxSide` pixels on the long side when bigger, keeping the shape, with even sides (H.264 and VP9 need them). */
+const side = (dim) => `trunc(min(${dim}\\,${MEDIA_LIMITS.maxSide})/2)*2`;
+export const FIT = `scale=w=if(gte(iw\\,ih)\\,${side("iw")}\\,-2):h=if(gte(iw\\,ih)\\,-2\\,${side("ih")})`;
+const EVEN = ["-vf", FIT];
const H264 = [...EVEN, "-c:v", "libx264", "-preset", "veryfast", "-crf", "16", "-pix_fmt", "yuv420p"];
const VIDEO = {
mp4: [...H264, "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-f", "mp4"],
@@ -38,7 +61,7 @@ const VIDEO = {
mkv: [...H264, "-c:a", "aac", "-b:a", "192k", "-f", "matroska"],
webm: [...EVEN, "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", "-row-mt", "1", "-crf", "20", "-b:v", "0", "-c:a", "libopus", "-b:a", "160k", "-f", "webm"],
avi: [...H264, "-c:a", "libmp3lame", "-q:a", "2", "-f", "avi"],
- gif: ["-an", "-filter_complex", "[0:v:0]split[a][b];[a]palettegen[p];[b][p]paletteuse", "-f", "gif"],
+ gif: ["-an", "-filter_complex", `[0:v:0]${FIT},split[a][b];[a]palettegen[p];[b][p]paletteuse`, "-f", "gif"],
};
const AUDIO = {
wav: ["-c:a", "pcm_s24le", "-f", "wav"],
@@ -58,16 +81,33 @@ const AUDIO = {
/**
* ffmpeg's arguments to make `src` again as `dst`: the first video stream and the first sound stream for a clip (the
* format its name says: H.264 and AAC in MP4 when it says nothing ffmpeg writes well), the first sound stream for a
- * sound; no metadata, chapters, subtitles or data.
+ * sound; no metadata, chapters, subtitles or data. ffmpeg reads `src` only as a local file (`file:` is the only protocol
+ * it may use) in one of INPUT_FORMATS, and writes at most MEDIA_LIMITS.maxSeconds and `capBytes`.
*/
-export function encodeArgs(kind, name, src, dst) {
+export function encodeArgs(kind, name, src, dst, capBytes = MEDIA_LIMITS.maxBytes) {
const ext = extOf(name);
- const head = ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", src, "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn"];
+ const head = [
+ "-hide_banner", "-nostdin", "-loglevel", "error", "-y",
+ "-protocol_whitelist", "file", "-format_whitelist", INPUT_FORMATS.join(","),
+ "-i", `file:${src}`,
+ "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn",
+ "-t", String(MEDIA_LIMITS.maxSeconds), "-fs", String(Math.floor(capBytes)),
+ ];
+ const out = `file:${dst}`;
if (kind === "video") {
const fmt = VIDEO[ext] ?? VIDEO.mp4;
- return ext === "gif" ? [...head, ...fmt, dst] : [...head, "-map", "0:v:0", "-map", "0:a:0?", ...fmt, dst];
+ return ext === "gif" ? [...head, ...fmt, out] : [...head, "-map", "0:v:0", "-map", "0:a:0?", ...fmt, out];
+ }
+ return [...head, "-vn", "-map", "0:a:0", ...(AUDIO[ext] ?? AUDIO.wav), out];
+}
+
+/** A file's size in bytes (0 when it isn't there). */
+export function fileSize(file) {
+ try {
+ return fs.statSync(file).size;
+ } catch {
+ return 0;
}
- return [...head, "-vn", "-map", "0:a:0", ...(AUDIO[ext] ?? AUDIO.wav), dst];
}
/** ffmpeg's version line, or null when there is no working ffmpeg at `bin`. */
@@ -83,13 +123,13 @@ export function ffmpegVersion(bin) {
/**
* Make a clip or a sound again (`encodeArgs`) in its own process at low priority, stopped after `timeoutMs`. True when
- * ffmpeg made it.
+ * ffmpeg made it under `capBytes` (ffmpeg stops writing at the cap, so a file that reached it is cut short: false).
*/
-export function reencode({ ffmpeg, kind, name, src, dst, timeoutMs = 20 * 60_000, spawnFn = spawn }) {
+export function reencode({ ffmpeg, kind, name, src, dst, capBytes = outputCap(fileSize(src)), timeoutMs = 20 * 60_000, spawnFn = spawn }) {
return new Promise((resolve) => {
let child;
try {
- child = spawnFn(ffmpeg, encodeArgs(kind, name, src, dst), { stdio: ["ignore", "ignore", "ignore"], windowsHide: true });
+ child = spawnFn(ffmpeg, encodeArgs(kind, name, src, dst, capBytes), { stdio: ["ignore", "ignore", "ignore"], windowsHide: true });
} catch {
return resolve(false);
}
@@ -98,6 +138,10 @@ export function reencode({ ffmpeg, kind, name, src, dst, timeoutMs = 20 * 60_000
} catch {}
const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
child.once("error", () => (clearTimeout(timer), resolve(false)));
- child.once("exit", (code) => (clearTimeout(timer), resolve(code === 0)));
+ child.once("exit", (code) => {
+ clearTimeout(timer);
+ const size = fileSize(dst);
+ resolve(code === 0 && size > 0 && size < capBytes);
+ });
});
}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index b197a8be..8331ae23 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -19,12 +19,13 @@ import { fileURLToPath } from "node:url";
import { StayAwake } from "./awake.mjs";
import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";
import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";
-import { PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";
+import { ffmpegOf, PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";
import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";
import { Hold } from "./hold.mjs";
import { inventoryHash, modelFiles, packFolders } from "./inventory.mjs";
import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";
-import { ffmpegVersion, mediaKind, reencode } from "./media.mjs";
+import { takeLock, workerLives } from "./lock.mjs";
+import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
import { retrying } from "./retry.mjs";
import { SiteTurns, writeSite } from "./turns.mjs";
@@ -49,11 +50,47 @@ const HOUR = 3_600_000;
/** The worker looks at its model folders again this often (a folder that comes back after a restart counts). */
export const RESCAN_MS = 10 * 60_000;
+/** Kept results that the studio hasn't taken for this long are deleted (the studio drops its jobs after a day). */
+export const HOLD_MAX_AGE_MS = 24 * HOUR;
+
+/**
+ * While it may not work, it asks for the job of its kept results at most this often after the studio said it has none
+ * for it (the job may still come back to it once it may work again, so the results stay).
+ */
+export const HELD_RETRY_MS = 60_000;
+
+/** The port an older setup saved for every worker; a worker.json that still pins it gets a free port at each start. */
+export const OLD_SETUP_PORT = 8190;
+
+/** The settings as the worker uses them: a port that an older setup saved (8190) is no pin (the same object otherwise). */
+export const withoutOldPort = (cfg) => (Number(cfg?.port) === OLD_SETUP_PORT ? { ...cfg, port: null } : cfg);
+
+/** An address on a private network: 10.x, 172.16.x to 172.31.x, 192.168.x, or IPv6 fc00::/7. */
+export function privateHost(hostname) {
+ const h = String(hostname).replace(/^\[|\]$/g, "");
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
+ if (m) {
+ const [a, b] = [Number(m[1]), Number(m[2])];
+ return m.slice(1).every((x) => Number(x) <= 255) && (a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168));
+ }
+ return /^f[cd][0-9a-f]{0,2}:/i.test(h);
+}
+
+/** The studio's address uses http (allowed only on this PC, or on a private network with allowHttpSite). */
+export const plainHttp = (site) => {
+ try {
+ return new URL(String(site)).protocol === "http:";
+ } catch {
+ return false;
+ }
+};
+
/**
* Why the studio's address won't do, or null: it must be https, so the token and people's files never cross the
- * network in the clear. This PC itself (127.0.0.1, localhost) may use http, for tests.
+ * network in the clear. This PC itself (127.0.0.1, localhost) may use http, for tests. An address on a private network
+ * may use http only when worker.json says `allowHttpSite: true` (`o` is the settings).
*/
-export function siteProblem(site) {
+export function siteProblem(site, o = {}) {
let u;
try {
u = new URL(String(site));
@@ -62,6 +99,9 @@ export function siteProblem(site) {
}
if (u.protocol === "https:") return null;
if (u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)) return null;
+ if (u.protocol === "http:" && privateHost(u.hostname)) {
+ return o?.allowHttpSite === true ? null : "The studio's address must start with https://. For an http:// address on your own network, set allowHttpSite to true in worker.json.";
+ }
return "The studio's address must start with https://.";
}
@@ -82,16 +122,11 @@ const arrayBuffer = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + b
const count = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null);
/**
- * What the beat says for studio jobs first: { claimable (the studio's jobs this worker may take now; null when the studio
- * doesn't say, and then local ComfyUI work counts as another program, as before), oldestWaitS, interrupt }.
+ * What the beat says for studio jobs first: { claimable }, the beat's claimableNow (people's jobs this worker may take
+ * now). It is null when the studio doesn't say, and then local ComfyUI work counts as another program, as before.
*/
export function siteOf(answer) {
- const w = answer?.worker ?? {};
- return {
- claimable: count(answer?.claimableNow) ?? count(w.claimableNow),
- oldestWaitS: count(answer?.oldestWaitS) ?? count(w.oldestWaitS),
- interrupt: w.yieldInterrupt === true || answer?.yieldInterrupt === true,
- };
+ return { claimable: count(answer?.claimableNow) };
}
/**
@@ -100,13 +135,31 @@ export function siteOf(answer) {
* signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own
* options), readCounters, readListeners, gpuEveryMs }.
*/
-export async function runWorker(cfg, deps) {
+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
+ // take its job. It refuses to start instead (WorkerRunning), before it touches anything.
+ fs.mkdirSync(saved.workDir, { recursive: true });
+ const lock = await takeLock(saved.workDir, { commandLineOf: deps.comfy?.commandLineOf });
+ try {
+ return await work(saved, deps, lock.owner);
+ } finally {
+ lock.release();
+ }
+}
+
+/** The worker's loop, with the worker folder's lock held (`owner`: { pid, id, script }, the lock's). */
+async function work(saved, deps, owner) {
const now = deps.now ?? Date.now;
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
const log = deps.log ?? ((line) => console.log(`[${new Date().toISOString().slice(11, 19)}] ${line}`));
+ const cfg = withoutOldPort(saved);
+ if (cfg !== saved) log(`worker.json pins port ${OLD_SETUP_PORT}, from an older setup: its ComfyUI takes a free port at each start instead. Run fuobe worker setup again to save the new settings.`);
const fetchFn = deps.fetch ?? fetch;
- const problem = siteProblem(cfg.site);
+ const problem = siteProblem(cfg.site, cfg);
if (problem) throw new Error(problem);
+ if (cfg.allowHttpSite === true && plainHttp(cfg.site) && privateHost(new URL(cfg.site).hostname)) {
+ log("The studio's address uses http:// (allowHttpSite): its token and people's files cross your network unencrypted.");
+ }
const index = deps.requirements ?? loadRequirements();
const { ComputerRunner } = deps.ComputerRunner ? { ComputerRunner: deps.ComputerRunner } : await import("./dist/computer-runner.mjs");
const site = cfg.site.replace(/\/+$/, "");
@@ -120,7 +173,9 @@ export async function runWorker(cfg, deps) {
const hold = new Hold(path.join(cfg.workDir, "hold"));
const allowed = deps.allowed ?? allowedNodes(cfg.allowNodesFile);
const rules = deps.rules ?? inputRules();
- const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, ...deps.comfy });
+ const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy });
+ // Only its own ComfyUI, and only while the process it started is up and ready: never whatever listens on that port.
+ const own = (url, init) => (comfy.alive() && comfy.ready ? comfy.fetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running")));
// A ComfyUI that a stopped worker left running is stopped now, before anything else uses the GPU.
await comfy.stopLeftover();
// Studio jobs first: only with a turns folder set in worker.json. Without one, every program counts the same, as before.
@@ -139,8 +194,16 @@ export async function runWorker(cfg, deps) {
// Two busy readings in a row pause it when it tells programs apart (a reading can catch memory on its way).
const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75, busyReadings: turns ? 2 : 1 });
const awake = deps.awake ?? new StayAwake({ now, log });
- const ffmpeg = await (deps.ffmpegVersion ?? ffmpegVersion)(cfg.ffmpeg);
- log(ffmpeg ? "ffmpeg is there: it takes clips and sound, and makes each one again first." : "No ffmpeg set (ffmpeg in worker.json): it takes pictures only.");
+ // ffmpeg: worker.json's, or the PATH's when worker.json names none (an older setup's never did).
+ const ffmpegBin = ffmpegOf(cfg);
+ const ffmpeg = ffmpegBin ? await (deps.ffmpegVersion ?? ffmpegVersion)(ffmpegBin) : null;
+ log(
+ ffmpeg
+ ? `ffmpeg is there${cfg.ffmpeg === undefined ? " (on the PATH)" : ""}: it takes clips and sound, and makes each one again first.`
+ : ffmpegBin
+ ? `No working ffmpeg at ${ffmpegBin}: it takes pictures only. Set ffmpeg in worker.json (its full path), or run fuobe worker setup again.`
+ : "No ffmpeg (ffmpeg in worker.json): it takes pictures only.",
+ );
let comfyTrouble = null;
let troubleAt = 0;
let answer = null;
@@ -153,17 +216,23 @@ export async function runWorker(cfg, deps) {
let busyJob = false;
let job = Promise.resolve();
let lastTask = null;
+ let heldRetryAt = 0;
+ let holdCheckedAt = -Infinity;
+ // Its ComfyUI's start, while it goes on (beats go on meanwhile), and the signal that ends a start when the worker stops.
+ let starting = null;
+ const stopStarts = new AbortController();
+ deps.signal?.addEventListener("abort", () => stopStarts.abort(), { once: true });
let guardMissingAt = -Infinity;
// Studio jobs first: the last port table, the last split of the GPU's memory, and the last turn step.
let listing = null;
let listedAt = -Infinity;
let split = null;
- let turn = { siteWaiting: 0, oldestWaitS: 0, interrupt: false, waitForYield: false, late: false, startsAt: null, ended: null };
+ let turn = { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null, waitForYield: false, late: false, startsAt: null, ended: null };
let siteWritten = "";
let siteAt = 0;
let siteFailed = false;
const writeTurn = (t, body) => {
- const key = JSON.stringify([body.siteWaiting, body.interrupt]);
+ const key = JSON.stringify([body.siteWaiting, body.interruptAt]);
siteWritten = key;
siteAt = t;
try {
@@ -202,7 +271,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"), deps.pins), 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 }), 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.
@@ -238,23 +307,28 @@ export async function runWorker(cfg, deps) {
// Without ffmpeg it takes no clip or sound: another worker that can make them again runs the job.
if (!ffmpeg) return "give-back";
const made = path.join(cacheDir, `${input.sha256}.${kind}`);
+ const cap = outputCap(data.length);
if (!fs.existsSync(made)) {
const part = `${made}.part`;
- if (!(await (deps.reencode ?? reencode)({ ffmpeg: cfg.ffmpeg, kind, name: input.name, src: kept, dst: part }))) {
+ if (!(await (deps.reencode ?? reencode)({ ffmpeg: ffmpegBin, kind, name: input.name, src: kept, dst: part, capBytes: cap }))) {
fs.rmSync(part, { force: true });
- log(`Job ${t.id}: ffmpeg couldn't read one of its ${kind === "video" ? "clips" : "sounds"}.`);
+ log(`Job ${t.id}: ffmpeg couldn't make one of its ${kind === "video" ? "clips" : "sounds"} again (unreadable, or over ${Math.round(cap / 2 ** 20)} MB).`);
return "input-unreadable";
}
fs.renameSync(part, made);
}
+ // Never more than the cap into memory.
+ if (fileSize(made) >= cap) {
+ fs.rmSync(made, { force: true });
+ return "input-unreadable";
+ }
return arrayBuffer(fs.readFileSync(made));
}
const runner = new ComputerRunner(
{
api: call,
- // Only its own ComfyUI, and only while the process it started is up: never whatever else listens on that port.
- local: (url, init) => (comfy.alive() && comfy.ready ? comfy.fetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running"))),
+ local: own,
sha256: async (data) => sha256(Buffer.from(data)),
origin: site,
socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
@@ -275,11 +349,13 @@ export async function runWorker(cfg, deps) {
},
ended: async (t, phase) => {
log(`Job ${t.id} ${phase}.`);
- // Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is.
+ // Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is,
+ // after a while (so a studio that won't take them now doesn't keep its ComfyUI from starting).
if (phase === "done") hold.drop(t.id);
+ else if (hold.has(t.id)) heldRetryAt = now() + HELD_RETRY_MS;
delete crashes[t.id];
saveCrashes();
- await cleanJob(f, comfy.base, (url, init) => comfy.fetch(url, init));
+ await cleanJob(f, comfy.base, own);
emptyCache();
},
beatExtra: () => ({
@@ -289,8 +365,13 @@ export async function runWorker(cfg, deps) {
gpu: gpuInfo,
inventoryHash: invHash,
warmLane: null,
+ // The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.
+ held: hold.ids().slice(0, 16),
}),
onBeat: (a) => {
+ // A studio that takes jobs only from a newer worker program: say so once (it sends this worker none).
+ const min = Number(a?.worker?.minProtocol);
+ if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");
answer = a;
// The owner's switch on the Workers page wins over worker.json; null leaves worker.json's.
const s = a?.worker?.autoResume;
@@ -299,21 +380,32 @@ export async function runWorker(cfg, deps) {
worker: {
hold,
input: takeInput,
- stallMs: (cfg.stallMin ?? 10) * 60_000,
+ // The studio's stall limit comes with each job; a stallMin in worker.json wins over it on this PC.
+ stallMs: 10 * 60_000,
+ stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
free: () => comfy.free(),
crashes: (t) => crashes[t.id] ?? 0,
stuck: async () => {
log("Its ComfyUI didn't let go of a job: starting it again.");
await comfy.stop();
},
- claimed: async (t) => {
- // Kept results of any other job aren't this worker's any more (one job at a time).
- hold.dropAllBut(t?.id ?? null);
- if (!t) return;
+ claimed: async (t, o = {}) => {
+ if (!t) {
+ // No job for it now. Its kept results stay (their job may come back to it); while it may not work it asks
+ // again for them only after a while. Its copies of inputs go.
+ if (o.onlyHeld) heldRetryAt = now() + HELD_RETRY_MS;
+ emptyCache();
+ return;
+ }
+ // Another job, given to a worker that may work: the kept results of any other job aren't this worker's any
+ // more (one job at a time).
+ if (!o.onlyHeld) hold.dropAllBut(t.id);
+ else if (!hold.has(t.id)) heldRetryAt = now() + HELD_RETRY_MS;
comfy.task = t.id;
- // Another job than the one its ComfyUI last had: nothing of that one stays.
+ // Another job than the one its ComfyUI last had: nothing of that one stays, in its ComfyUI or in the inputs.
if (t.id !== lastTask) {
- await cleanJob(f, comfy.base, (url, init) => comfy.fetch(url, init));
+ await cleanJob(f, comfy.base, own);
+ emptyCache();
lastTask = t.id;
}
},
@@ -478,8 +570,8 @@ export async function runWorker(cfg, deps) {
busy: busyJob && jobUsesGpu && !stopNow,
workHolds,
workThere: !!split && (split.work.pids.length > 0 || !!split.work.lock),
- serverInterrupt: s.interrupt,
- oldestWaitS: s.oldestWaitS,
+ // The beat has no request to interrupt local work, and no wait of its own: the worker counts the wait itself.
+ serverInterrupt: false,
});
if (turn.waitForYield && !was.waitForYield) log("Local ComfyUI work holds the GPU: asking it to make room for the studio's jobs.");
if (turn.late && !was.late) log("Local ComfyUI work hasn't made room after 3 minutes: still waiting, with the jobs kept in line.");
@@ -488,43 +580,57 @@ export async function runWorker(cfg, deps) {
log("No studio job for a minute: its ComfyUI lets go of its memory for local work.");
if (comfy.ready && !busyJob) await comfy.free();
}
- if (turns.folderOk() && (beaten || JSON.stringify([turn.siteWaiting, turn.interrupt]) !== siteWritten || t - siteAt >= 5000)) {
- writeTurn(t, { siteWaiting: turn.siteWaiting, oldestWaitS: turn.oldestWaitS, interrupt: turn.interrupt });
+ if (turns.folderOk() && (beaten || JSON.stringify([turn.siteWaiting, turn.interruptAt]) !== siteWritten || t - siteAt >= 5000)) {
+ writeTurn(t, { siteWaiting: turn.siteWaiting, oldestWaitS: turn.oldestWaitS, interrupt: turn.interrupt, interruptAt: turn.interruptAt });
}
// No new job while local ComfyUI work holds the GPU, unless a turn has begun and it made room.
holdBack = turn.waitForYield || (turnsReady(t) && workHolds && turn.siteWaiting === 0) || gpu.busyInARow > 0;
}
+ // Kept results go up before its ComfyUI starts (they need none, and a start can take minutes), unless the studio
+ // said a moment ago that their job isn't this worker's now.
+ const heldFirst = hold.ids().length > 0 && t >= heldRetryAt && (!busyJob || !jobUsesGpu);
if (mayWork()) {
- if (!comfy.alive() && !comfyTrouble && t >= comfy.restartAt) {
+ if (!comfy.alive() && !starting && !comfyTrouble && t >= comfy.restartAt && !heldFirst) {
if (comfy.crashedTooOften(t)) {
comfyTrouble = "comfy-crashes";
log("ComfyUI keeps stopping: pausing for an hour.");
} else {
- try {
- log("Starting its own ComfyUI.");
- // The packs by their folder names on disk, which is what ComfyUI matches (whatever the catalog's case).
- await comfy.start(packs.map((p) => p.folder));
- } catch (e) {
- if (e instanceof PortBusy) {
- comfyTrouble = "port-busy";
- troubleAt = t;
- log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
- } else if (e instanceof GuardMissing) {
- // Not again for an hour: it would only start the same ComfyUI again.
- comfyTrouble = "comfy-crashes";
- guardMissingAt = t;
- log(`${e.message}: it won't use it, and pauses for an hour.`);
- } else log(`ComfyUI didn't start: ${e.message}`);
- }
+ log("Starting its own ComfyUI.");
+ // In the background: beats go on while it starts. The packs by their folder names on disk, which is what
+ // ComfyUI matches (whatever the catalog's case).
+ starting = comfy
+ .start(
+ packs.map((p) => p.folder),
+ { signal: stopStarts.signal },
+ )
+ .catch((e) => {
+ if (stopStarts.signal.aborted) return;
+ if (e instanceof PortBusy) {
+ comfyTrouble = "port-busy";
+ troubleAt = now();
+ log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
+ } else if (e instanceof GuardMissing) {
+ // Not again for an hour: it would only start the same ComfyUI again.
+ comfyTrouble = "comfy-crashes";
+ guardMissingAt = now();
+ log(`${e.message}: it won't use it, and pauses for an hour.`);
+ } else if (mayWork()) log(`ComfyUI didn't start: ${e.message}`);
+ })
+ .finally(() => (starting = null));
}
}
- if (comfy.ready && answer?.runner && !busyJob && !holdBack) take();
+ if (comfy.ready && answer?.runner && !busyJob && !holdBack && !heldFirst) take();
} else if (comfy.alive() && (stopNow || !busyJob)) {
log("Stopping its own ComfyUI (paused).");
await comfy.stop();
}
- // Kept results go up even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.
- if (!busyJob && answer && hold.ids().length && !(mayWork() && comfy.ready && !holdBack)) take({ onlyHeld: true });
+ // Kept results the studio never took are deleted after a day.
+ if (t - holdCheckedAt >= 60_000) {
+ holdCheckedAt = t;
+ for (const id of hold.expire(t, HOLD_MAX_AGE_MS)) log(`Deleted the kept results of job ${id}: the studio didn't take them for a day.`);
+ }
+ // Kept results go up first, and even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.
+ if (!busyJob && answer && heldFirst) take({ onlyHeld: true });
// Awake while it holds a job, has results to send, or waits for work.
awake.set(!!answer?.worker && (busyJob || hold.ids().length > 0 || !!mayWork()));
// A taken port is tried again (a bind test, never a connection) once a minute.
@@ -544,7 +650,11 @@ export async function runWorker(cfg, deps) {
await Promise.race([job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);
awake.set(false);
// No turn any more: local ComfyUI work may go on at once.
- if (turns?.folderOk()) writeTurn(now(), { siteWaiting: 0, oldestWaitS: 0, interrupt: false });
+ if (turns?.folderOk()) writeTurn(now(), { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null });
+ // A start under way ends first (it stops at the signal), so no ComfyUI is left behind.
+ stopStarts.abort();
+ await comfy.stop();
+ await starting;
await comfy.stop();
emptyFolders(f);
emptyCache();
diff --git a/bin/lib/worker/turns.mjs b/bin/lib/worker/turns.mjs
index 1b8b94de..4c90b34a 100644
--- a/bin/lib/worker/turns.mjs
+++ b/bin/lib/worker/turns.mjs
@@ -1,10 +1,12 @@
// Studio jobs first (docs/gpu-workers.md): while local ComfyUI work holds the GPU, the worker asks for a turn through two
// small files in a folder that worker.json names, and a helper on the PC's side answers.
//
-// - site.json, which the worker writes on every beat: { siteWaiting, oldestWaitS, interrupt, at }. siteWaiting counts
-// the studio's jobs this worker may take now (the beat's claimableNow) plus the one it runs. While a turn lasts it is
-// at least 1, and it goes to 0 when the studio has had no job for it for a minute (the worker then frees its own
-// ComfyUI's memory), when it is paused, or when a local cap is reached.
+// - site.json, which the worker writes on every beat: { siteWaiting, oldestWaitS, interrupt, interruptAt, at }.
+// siteWaiting counts the studio's jobs this worker may take now (the beat's claimableNow) plus the one it runs. While
+// a turn lasts it is at least 1, and it goes to 0 when the studio has had no job for it for a minute (the worker then
+// frees its own ComfyUI's memory), when it is paused, or when a local cap is reached. interruptAt names one interrupt
+// the worker allows (the time it allowed it): the helper stops at most one local job per interruptAt value. Both
+// interrupt and interruptAt go back to false and null once the helper answers after that time.
// - yielded.json, which the helper writes: { state: "yielding" | "yielded", at, startsAt? }. A fresh "yielded" lets the
// worker start at once. "yielding" may carry the helper's estimate of the start (startsAt), which the beat passes on.
//
@@ -58,8 +60,9 @@ const dayOf = (t) => {
/**
* The turns on this PC. `step(t, facts)` runs once a loop and says what to write and whether to wait:
- * { siteWaiting, oldestWaitS, interrupt, waitForYield, late, startsAt, ended } — `ended` is "idle" when a turn ended
- * because no job came for a minute (free its own ComfyUI's memory), "stopped" when it ended for any other reason.
+ * { siteWaiting, oldestWaitS, interrupt, interruptAt, waitForYield, late, startsAt, ended } — `interruptAt` is the time
+ * the one allowed interrupt was given (null with none), `ended` is "idle" when a turn ended because no job came for a
+ * minute (free its own ComfyUI's memory), "stopped" when it ended for any other reason.
*/
export class SiteTurns {
/** `o`: { folder, stateFile, maxHoursPerDay, interruptGapMin, neverInterrupt, graceMs }. */
@@ -121,9 +124,10 @@ export class SiteTurns {
/**
* `f`: { may (the worker may ask for a turn now: the folder is there, the studio says what it can take, nothing pauses
* it), claimable (the beat's claimableNow), busy (a studio job runs here), workHolds (local ComfyUI work holds more
- * than busyVramMb), workThere (local ComfyUI work listens at all), serverInterrupt, oldestWaitS (the studio's, when
- * it says), unsure (another program showed in one reading, which may still become a pause: no new turn begins, and a
- * turn that has begun goes on, so one reading never makes the helper let go and ask again) }.
+ * than busyVramMb), workThere (local ComfyUI work listens at all), serverInterrupt (a request to stop local work
+ * instead of letting it finish; the beat has none, so the worker passes false), unsure (another program showed in one
+ * reading, which may still become a pause: no new turn begins, and a turn that has begun goes on, so one reading never
+ * makes the helper let go and ask again) }.
*/
step(t, f) {
const day = dayOf(t);
@@ -153,7 +157,7 @@ export class SiteTurns {
}
if (!this.active) {
this.waitSince = null;
- return { siteWaiting: 0, oldestWaitS: 0, interrupt: false, waitForYield: false, late: false, startsAt: null, ended };
+ return { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null, waitForYield: false, late: false, startsAt: null, ended };
}
if (f.workHolds) this.neededYield = true;
// The local ComfyUI work closed: nothing to wait for any more.
@@ -172,16 +176,23 @@ export class SiteTurns {
this.waitingSince = null;
if (yielded) this.interrupt = false;
}
+ // The helper answered after the interrupt was allowed (it is making room, or has): the interrupt has been seen.
+ if (this.interrupt) {
+ const y = readYielded(this.o.folder);
+ if (y && y.at >= this.saved.lastInterruptAt) this.interrupt = false;
+ }
if (this.o.neverInterrupt || f.serverInterrupt !== true) this.interrupt = false;
if (t - this.savedAt >= 30_000) this.save(t);
+ // How long people's jobs have waited for this worker, as it saw them (the beat doesn't say).
this.waitSince = claimable > 0 ? (this.waitSince ?? t) : null;
- const oldestWaitS = finite(f.oldestWaitS) ? Math.max(0, Math.round(f.oldestWaitS)) : this.waitSince === null ? 0 : Math.round((t - this.waitSince) / 1000);
+ const oldestWaitS = this.waitSince === null ? 0 : Math.round((t - this.waitSince) / 1000);
const y = waitForYield ? readYielded(this.o.folder) : null;
return {
// Jobs it may not take now (paused, with one still finishing) don't count.
siteWaiting: Math.max(1, (may ? claimable : 0) + (f.busy ? 1 : 0)),
oldestWaitS,
interrupt: this.interrupt,
+ interruptAt: this.interrupt ? this.saved.lastInterruptAt : null,
waitForYield,
late: waitForYield && t - this.waitingSince >= TURNS.lateMs,
startsAt: y?.state === "yielding" && y.at >= this.startAt - 1000 ? y.startsAt : null,
diff --git a/docs/cli.md b/docs/cli.md
index eecfc40e..4bb22912 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -286,9 +286,10 @@ Runs this PC's GPU as a worker for a studio: it takes the studio's ComfyUI jobs
ComfyUI, and it opens no port. See [gpu-workers.md](gpu-workers.md).
```bash
-node scripts/build-worker.mjs # once, in the checkout: the worker's shared parts
-fuobe worker setup # the studio's address, the token from Settings → Workers, ComfyUI's folder, a port
-fuobe worker run # until Ctrl+C
+pnpm install --frozen-lockfile # once, in the checkout: the build's tools
+node scripts/build-worker.mjs # then the worker's shared parts
+fuobe worker setup # the studio's address, the token, ComfyUI's folder, the model and worker folders, ffmpeg's path
+fuobe worker run # until Ctrl+C; exit code 4: another worker runs on the same worker folder
fuobe worker pause # finish the job, then stop its ComfyUI; --now: stop now; --for 2h: back by itself
fuobe worker pause --choose # asks for 1, 2 or 4 hours, then stops now (the Ctrl+Alt+P shortcut)
fuobe worker resume
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index bc6859d7..83a0e227 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -44,13 +44,16 @@ or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected
1. In **Settings → Workers**, press **Add a worker** and give it a name. The page shows the worker's token only once.
The worker starts paused, with no hours and no lanes.
-2. On the GPU's PC, you need Node 22 or later and git. Install the worker from a git checkout of Fuobe at a release tag
- that you have verified (see "Install and update"). Run `node scripts/build-worker.mjs`, then run
- `node bin/fuobe.mjs worker setup`.
+2. On the GPU's PC, you need Node 22 or later, git and pnpm (`corepack enable` installs pnpm). Install the worker from
+ a git checkout of Fuobe that you have verified (see "Install and update"). Run `node scripts/build-worker.mjs`, then
+ run `node bin/fuobe.mjs worker setup`.
Setup asks for the studio's address, the token (as hidden input), ComfyUI's folder, the model folders, a worker
folder and the path of ffmpeg (see "Clips and sound"). It refuses these:
- a studio address that does not start with `https://` (only `http://127.0.0.1` and `http://localhost` are allowed,
- for tests);
+ for tests). A studio on your own network (`http://10.x`, `http://172.16.x` to `172.31.x`, `http://192.168.x` or
+ an IPv6 address from `fc00::/7`) may use `http://` only when you set `"allowHttpSite": true` in `worker.json`
+ yourself. The studio can never set it. The worker's token and people's files then cross your network
+ unencrypted, and the worker says so in its log at each start;
- a folder that a cloud drive syncs;
- an ffmpeg path where no ffmpeg runs.
@@ -74,17 +77,27 @@ offer the worker as a download. Use a git checkout at a signed release tag:
3. Verify the tag that you want: `git verify-tag <tag>`. Go on only when git says that the signature is good and the
key is one that you trust.
4. Check it out: `git checkout <tag>`.
-5. Build the worker's parts: `node scripts/build-worker.mjs`.
+5. Install the build's tools: `pnpm install --frozen-lockfile`. The build needs TypeScript, which is a development
+ dependency.
+6. Build the worker's parts: `node scripts/build-worker.mjs`.
-To update, stop the worker, do steps 2 to 5 with the new tag, and start the worker again. Do not install the worker
-from a zip file, from a copy that someone sends you, or from a branch.
+**Release tags.** A maintainer makes each release tag with `git tag -s <version>` (a signed, annotated tag) and pushes
+it. Get the maintainer's public key from a source that you trust, and import it before step 3. Until the repository
+has a release tag, check out a commit instead, and verify it with `git verify-commit <commit>` in step 3.
+
+To update, stop the worker, do steps 2 to 6 with the new tag, and start the worker again. If the worker was set up by
+an older version, run `fuobe worker setup` again after the update. That clears the fixed port that older setups saved
+(8190), so its ComfyUI takes a free port at each start, and it asks for ffmpeg (without ffmpeg the worker takes no
+clips or sound). Until then, the worker treats a saved 8190 as no fixed port, and says when no ffmpeg is set. Do not
+install the worker from a zip file, from a copy that someone sends you, or from a branch.
### The worker's own ComfyUI
The worker always starts and stops its own ComfyUI process. It never uses a ComfyUI that it did not start. Its ComfyUI:
- listens on `127.0.0.1` only, on a free port that the worker picks at random (20000 to 59999) at each start. Port
- 8188 is never used. To fix one port instead, set `port` in `worker.json`;
+ 8188 is never used. To fix one port instead, set `port` in `worker.json` (8190, which older setups saved for every
+ worker, counts as no fixed port);
- starts through the worker's guard (see below), with the worker folder as its working folder. A node that writes to
a relative path writes into the worker folder, not into ComfyUI's folder;
- uses its own `user`, `input`, `output` and `temp` folders in the worker folder;
@@ -102,11 +115,21 @@ The worker always starts and stops its own ComfyUI process. It never uses a Comf
**The port guard.** Before each start, the worker binds the port itself and releases it at once. If the bind fails,
another program is using the port. The worker then does not start ComfyUI, pauses itself (its state says "port-busy")
and never connects to that port. The worker also talks to its ComfyUI only while the process that it started is
-running.
+running. When that process stops, the worker forgets its port, so nothing (not even the cleanup after a job) goes to
+whatever listens there later.
+
+A request to its ComfyUI waits at most 15 seconds for the answer to begin (2 minutes for a request that sends a file,
+and 5 seconds for the look at its memory that the worker takes every 5 seconds). A long download of a result is not
+cut short. So a ComfyUI that takes the connection but never answers holds nothing up: the worker goes on beating, and
+after `hungMin` minutes it starts that ComfyUI again.
**The guard.** The worker makes a new random key at each start. It starts ComfyUI through
-`bin/lib/worker/comfy_guard.py`, which it copies into the worker folder (`guard/`) first. The guard reads the key from
-the environment, removes it from there, and puts a check in front of every request to ComfyUI:
+`bin/lib/worker/comfy_guard.py`. At each start, it empties the worker folder's `guard/` folder and copies the guard
+into it, and it runs the guard in Python's isolated mode (`-I`). So no other file in that folder, and no `PYTHON*`
+variable, can change what the guard imports. (The guard applies `PYTHONIOENCODING` to its own output, and the worker
+passes `PYTHONUTF8` on as `-X utf8`. ComfyUI's own child processes still get every variable of its environment.) The
+guard reads the key from the environment, removes it from there, and puts a check in front of every request to
+ComfyUI:
- The `Host` header must be exactly `127.0.0.1:<port>`. A web page that points its own name at 127.0.0.1 (DNS
rebinding) sends its own name, so it is refused.
@@ -114,22 +137,31 @@ the environment, removes it from there, and puts a check in front of every reque
socket. Without it, the answer is 403.
Before the worker sends the key, the process on the port must prove two things. It signs a random challenge with the
-key (`GET /fuobe-worker/hello`, HMAC-SHA-256), and it names its process id, which must be the one that the worker
-started. A program that took the port first learns nothing. When ComfyUI is ready, the worker also checks that a
-request without the key is refused. If it is not refused, the guard is missing. The worker then stops that ComfyUI,
-does not use it, and pauses itself for an hour ("comfy-crashes").
-
-**A ComfyUI left running.** The worker writes its ComfyUI's process id to `comfyui.pid` in the worker folder. If the
-worker stops without stopping ComfyUI (a crash), the next start finds that file. It stops that process, but only when
-the process's command line still names the guard in this worker folder, so a reused process id is never stopped.
+key (`GET /fuobe-worker/hello`, HMAC-SHA-256), and it names its process id and its parent's. One of them must be the
+process that the worker started. (On Windows, a venv's `python.exe` starts the real Python as a process of its own, so
+there the parent is the one that the worker started.) A program that took the port first learns nothing. When ComfyUI
+is ready, the worker also checks that a request without the key is refused. If it is not refused, the guard is
+missing. The worker then stops that ComfyUI, does not use it, and pauses itself for an hour ("comfy-crashes").
+
+**A ComfyUI left running.** The worker writes its ComfyUI's process id to `comfyui.pid` in the worker folder, with
+its own process id. If the worker stops without stopping ComfyUI (a crash), the next start finds that file. It stops
+that process, but only when the worker that started it no longer runs, and only when the process's command line still
+names the guard in this worker folder, so a reused process id is never stopped.
+
+**One worker on a worker folder.** At each start, the worker makes `worker.lock` in the worker folder, with its process
+id. A second worker with the same worker folder (for example `fuobe worker run` by hand while the sign-in task's worker
+runs) does not start: it says that another worker runs, and it touches nothing (exit code 4). A lock whose worker has
+stopped is taken over. The worker counts a lock as stopped when its process is gone, or when that process id now
+belongs to a program that is not a Fuobe worker. If the command line of that process can't be read, the lock counts
+as held.
**Its log.** ComfyUI's output goes to `comfyui.log` in the worker folder. Each start begins a new file, and so does a
file that passes 20 MB. The worker keeps the two files before it (`comfyui.1.log`, `comfyui.2.log`).
**When its ComfyUI stops by itself.** The worker starts it again after a short wait: 5 seconds, then twice as long each
time in a row, at most 2 minutes. If ComfyUI stops twice while it runs the same job, that job fails with plain words
-("This run stopped twice at the same point"), and the worker goes on with the next job. If ComfyUI stops more than 3
-times in one hour with no job running, the worker pauses itself ("ComfyUI keeps stopping").
+("This run couldn't finish with these files or settings"), and the worker goes on with the next job. If ComfyUI
+stops more than 3 times in one hour with no job running, the worker pauses itself ("ComfyUI keeps stopping").
### Pauses
@@ -182,7 +214,10 @@ The worker never connects to your other ComfyUIs. It reads three things only:
Every 5 seconds, the worker splits the GPU's used memory three ways. **Others** are the total, minus its own ComfyUI,
minus local ComfyUI work, minus the desktop's usual share (`desktopBaselineMb`). Run `fuobe worker baseline` once,
-with no game open, to measure that share. Local ComfyUI work may stay open while you measure.
+with no game open, to measure that share. Local ComfyUI work may stay open while you measure, and the worker may keep
+running: its own ComfyUI is not counted (the process in `comfyui.pid` in the worker folder, and the process that
+listens on its port). The command shows what it counted, with the biggest programs by name. It saves at most 4096 MB.
+More than that means that another GPU program was open: it says so, and you can close that program and measure again.
- If others are above `busyVramMb` in two readings in a row, the worker pauses as before ("Your GPU is busy"). After
one such reading, it starts no new job, and a turn stays as it is: it doesn't begin, and it doesn't end.
@@ -195,10 +230,11 @@ folder. The worker never makes it, so the folder keeps the rights that the setup
local ComfyUI work counts as another program.
- `site.json` is written by the worker on every beat, and at least every 5 seconds:
- `{ siteWaiting, oldestWaitS, interrupt, at }`. `siteWaiting` is the number of studio jobs that this worker may take
- now (from the beat's `claimableNow`), plus the job that it runs. During a turn it is at least 1. It goes to 0 when no
- studio job has come for a minute, when the worker is paused, or when a local cap is reached. When the worker stops,
- it writes 0.
+ `{ siteWaiting, oldestWaitS, interrupt, interruptAt, at }`. `siteWaiting` is the number of studio jobs that this
+ worker may take now (from the beat's `claimableNow`), plus the job that it runs. During a turn it is at least 1. It
+ goes to 0 when no studio job has come for a minute, when the worker is paused, or when a local cap is reached. When
+ the worker stops, it writes 0. `oldestWaitS` is how long the worker has seen people's jobs waiting for it, by its
+ own clock.
- `yielded.json` is written by a helper on the PC's side: `{ state, at, startsAt }`. The state `"yielding"` can carry
the helper's estimate of the start time (`startsAt`, in ms). The worker passes it on in its beat. The state
`"yielded"` means that local ComfyUI work has made room. A "yielded" counts when it was written after the turn began,
@@ -212,8 +248,11 @@ and in its beat (`waiting-for-yield:no-answer`). It goes on waiting, with the jo
- `yieldMaxHoursPerDay` (20): the most hours of turns in one day, on the PC's clock. After that, local ComfyUI work
counts as another program until the next day. A restart doesn't reset the count.
-- `interruptGapMin` (30): the studio can ask the helper to stop your current local job instead of letting it finish
- (`interrupt: true`). The worker passes that request on at most once in this many minutes.
+- `interruptGapMin` (30): a request to stop your current local job instead of letting it finish passes on at most
+ once in this many minutes, as one interrupt: `interrupt: true` with `interruptAt`, the time the worker allowed it.
+ The helper stops at most one local job for each `interruptAt` value. Both go back to `false` and `null` as soon as
+ the helper writes `yielded.json` after that time. The beat's answer has no such request yet, so today `interrupt`
+ is always false and the helper lets your local job finish.
- `neverInterrupt` (false): when it is true, `interrupt` is always false.
**You first.** A pause by hand always wins. While the worker is paused, `siteWaiting` is 0. With a plain
@@ -282,7 +321,20 @@ Before its ComfyUI gets a graph, the worker checks all of these. The studio cann
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.
+does not read the files again. The catalog's files that still have no pin are listed in `UNPINNED_FILES`
+(`scripts/lib/worker-catalog.mjs`). A test fails when a workflow for workers needs a file that 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.
+
+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
+ worker's `extra_model_paths.yaml`), and takes the first folder that has the file. So the worker checks only that
+ first copy. If that copy has the wrong size or hash, the file is not reported, even when a later folder has a good
+ copy.
+- Some node packs read ComfyUI's own `models` folder directly. And an older ComfyUI that does not know `is_default`
+ looks in its own folders first. So a copy with the same name in ComfyUI's own `models` folder (`unet` and `clip`
+ count for `diffusion_models` and `text_encoders`), or in a folder that ComfyUI's own `extra_model_paths.yaml` adds,
+ must be the same file too. If it is not, the file is not reported.
After each job, however it ended, nothing of it stays in its ComfyUI: the worker empties the queue, stops a prompt that
still runs, and clears the whole history (a meta-batch's passes too). It also deletes the job's inputs and results from
@@ -304,8 +356,15 @@ sound that a job sends again, into a fresh file, before its ComfyUI sees it:
- nothing else of the file is kept: no metadata, chapters, subtitles, attachments or data streams.
The worker knows a clip or a sound by its type, by its name, or by the loader that reads it in the graph. ffmpeg runs
-in its own process, at low priority, for at most 20 minutes. If ffmpeg cannot read a file, the job fails with plain
-words ("A clip or a sound in this run couldn't be read").
+in its own process, at low priority, for at most 20 minutes. It reads the file only as a local file
+(`-protocol_whitelist file`), and only as one of these container formats (`-format_whitelist`): MP4 and MOV (with M4A
+and 3GP), Matroska and WebM, AVI, GIF, MPEG-TS, MPEG-PS, FLV, ASF, WAV, MP3, FLAC, Ogg, AAC and AIFF. A playlist, a
+list or any other format that would make ffmpeg open other files or addresses is refused.
+
+What ffmpeg writes has limits too: at most one hour, at most 4096 pixels on the long side (a bigger picture is made
+smaller, in the same shape), and at most 8 times the input's size (at least 256 MB, at most 2 GB). A result that
+reaches the size cap is refused before the worker reads it. If ffmpeg cannot read a file, or its result is too big,
+the job fails with plain words ("A clip or a sound in this run couldn't be read").
Without `ffmpeg`, the worker takes pictures only. Its inventory says so (`media: ["image"]`), and the studio sends it no
workflow that reads a clip or a sound. If such a job comes anyway, the worker gives it back to the line.
@@ -318,7 +377,10 @@ The worker keeps its jobs going by itself:
`hold/<job>/` in the worker folder before it tells the studio. The copy stays until the studio has every file. If
the worker or its ComfyUI stops in between, the next claim gives the job back to this worker, and it uploads the
kept files from where the studio's copy got to. The job never runs twice. Kept results go up even while the worker
- is paused, because they need no GPU. Kept results of a job that is no longer this worker's are deleted.
+ is paused, because they need no GPU. Each beat names the jobs whose results the worker keeps (`held`), so a pause,
+ even a pause now, leaves those jobs with this worker instead of sending them back in line. Kept results are deleted
+ when the studio has them all, when the worker takes another job, when the studio no longer has the job, or after a
+ day. A claim that finds nothing for the worker keeps them: their job may still come back to it.
- **One retry policy for the studio.** A studio that restarts, a proxy that answers 502, 503 or 52x, a network that
drops, or a busy studio that says when to come back is waited out. The pause grows from 1 second to at most 30
seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a call
@@ -328,14 +390,19 @@ The worker keeps its jobs going by itself:
run limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps
its place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and
starts it again. A job that is given back counts as an attempt; the third time, it fails.
+- **The run limit** counts from when its ComfyUI starts running the job (the model load included), not while the job
+ waits. The studio gives 3 times the lane's 90th-percentile time on that worker plus the lane's model load, at least
+ 10 minutes and at most the run ceiling (45 minutes). For a lane with no times on that worker yet, it gives the run
+ ceiling, so a first long job can finish. The worker ignores a run limit under 10 minutes.
- **A ComfyUI that stops answering** for `hungMin` minutes (3) is stopped and started again.
- **A job that the studio took back** (its token for the job no longer works, for example after the worker was out of
touch) is stopped in its ComfyUI at once, so it never keeps the GPU busy for nothing.
- **Out of memory.** The worker frees its ComfyUI's memory (`/free`) and sends the job once more. Only a second time
- fails the job.
+ fails the job. The execution time that it reports is the retry's only.
- **Inputs are read once.** The worker keeps a copy of each input (by its SHA-256) while its job runs, so a job that
is sent again reads nothing from the studio twice. If the studio will not send an input again (429 with no
- `Retry-After`), the job fails at once instead of looping.
+ `Retry-After`), the job fails at once instead of looping. The copies go when the job ends, and also when a claim
+ brings another job or none, however the last job ended.
- **The PC stays awake** while the worker holds a job, has results to send, or waits for work. A small helper asks the
system to stay awake (`SetThreadExecutionState` on Windows, `caffeinate` on macOS, `systemd-inhibit` on Linux). The
screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.
@@ -354,30 +421,41 @@ gets 403 everywhere else. It is never the owner, and an owner API token can neve
token on every call, so a revoked token stops at once.
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {
- otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
+ otherApps, tempC }, inventoryHash, warmLane, held }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
insideHours, nextChangeAt, lanes, minProtocol, sendInventory }`.
+ - `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUI
+ behind the guard.
+ - `held` (optional) names the jobs whose finished results the worker keeps on its disk. A pause now sends those
+ jobs back in line only when the worker doesn't name them.
- While the worker waits for its turn (see "Studio jobs first"), `local` is `{ paused: false, why:
"waiting-for-yield", until }`, where `until` is the helper's estimate of the start time, or null. After 3 minutes
with no answer, `why` is `"waiting-for-yield:no-answer"`. The worker may still take jobs, and its jobs keep their
place.
- - For studio jobs first, the answer may also carry `claimableNow` (the jobs that this worker may take now: its
- lanes, files, VRAM and hours), `oldestWaitS`, and `worker.yieldInterrupt` (true: the studio asks for local
- ComfyUI work to be stopped instead of finished, within the PC's own limits). Each one is optional.
+ - The answer also carries `claimableNow`, for studio jobs first: the number of people's jobs (never the owner's own)
+ that this worker may take now. It counts the jobs in the worker's pool that it can run (its lanes, files and VRAM)
+ and that end before its hours do. It is 0 while the worker is paused on the website, drains, is outside its hours
+ or runs an older worker program. The worker's own pause on the PC does not change it. The answer has no wait time
+ and no request to interrupt local work: the worker measures `oldestWaitS` itself.
- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }], media }`
→ `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,
- `audio`). With no `media`, the studio counts every kind.
+ `audio`). With no `media` (a worker from before it was added, which doesn't make clips and sound again), the studio
+ counts pictures only.
- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,
- models }`.
+ models }`. See "The run limit" above for `runLimitMs`.
- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finished
job also count: the last 20 jobs in each lane give the median and the 90th percentile.
- Reports, inputs and results work as they do for the browser, with these additions:
- `finished`, and the last `passes` report, carry `execMs` (the time that its ComfyUI spent executing the job, from
ComfyUI's own timestamps: no waits, no uploads) and `device` (the GPU's name). The studio keeps both with the job.
+ It keeps at most the job's run ceiling, and at most the time since the job was sent to its ComfyUI (plus a minute,
+ because ComfyUI starts a job a moment before the studio hears that it was sent).
- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and
counts as an attempt. Only a worker's job can be given back.
- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
`input-crashed` (its ComfyUI stopped twice on the job) or `input-unreadable` (ffmpeg could not read a clip or a
- sound) as the reason. The worker's own log names the node and the input, never the value.
+ sound) as the reason. The worker's own log names the node and the input, never the value. For
+ `input-crashed` and `input-unreadable`, and for a job that a worker gave back for the last time, the person who
+ started the run sees one plain sentence with no technical detail.
Each worker counts against its own rate limits, so three workers that beat every 5 seconds never hold each other up.
@@ -409,7 +487,8 @@ routes.
recovery tests run the worker against the studio's routes and a stand-in ComfyUI that the worker starts: they kill
its ComfyUI halfway, stop the worker before an upload, make its ComfyUI hang, and check that the output arrives
each time, once. The guard tests run the real guard in front of a stand-in ComfyUI when a Python with aiohttp is
- there (`FUOBE_TEST_PYTHON`, else `python3` or `python`); the clip tests need `ffmpeg` on the `PATH`.
+ there (`FUOBE_TEST_PYTHON`, else `python3` or `python`), also through a venv's Python (that Python itself when it is
+ a venv's, else a venv made from it); the clip tests need `ffmpeg` on the `PATH`.
- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). These
use a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.
- `python -m unittest discover -s tests` in `integrations/fuobe-connect`
diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
index d02f46b5..98075b0c 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -18,11 +18,13 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
const e = b.event;
if (typeof e !== "string" || !EVENTS.has(e)) return null;
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+ // A worker's results kept from an earlier try (nothing new runs).
+ const kept = b.kept === true ? { kept: true } : {};
// A worker's measured execution time and GPU name, with a finished job.
- const exec = { ...(num(b.execMs) !== undefined && { execMs: num(b.execMs) }), ...(typeof b.device === "string" && { device: b.device }) };
+ const exec = { ...measured(b), ...kept };
switch (e) {
case "sent":
- return typeof b.promptId === "string" ? { event: e, promptId: b.promptId, number: num(b.number) } : null;
+ return typeof b.promptId === "string" ? { event: e, promptId: b.promptId, number: num(b.number), ...kept } : null;
case "refused":
return { event: e, status: num(b.status) ?? 400, body: b.body };
case "queued":
@@ -44,6 +46,13 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
}
}
+/** A worker's measured run: its ComfyUI's time on the job (at most a day) and its GPU's name, as far as each is sound. */
+function measured(b: Record<string, unknown>): { execMs?: number; device?: string } {
+ const ms = typeof b.execMs === "number" && Number.isFinite(b.execMs) && b.execMs >= 0 && b.execMs <= 24 * 3_600_000 ? Math.round(b.execMs) : undefined;
+ const device = typeof b.device === "string" ? b.device.replace(/[^\p{L}\p{N} ._:()+/-]/gu, "").trim().slice(0, 120) : "";
+ return { ...(ms !== undefined && { execMs: ms }), ...(device && { device }) };
+}
+
/** The most a report about this job may weigh now: a finished entry while ComfyUI has it, a refusal while it sends. */
const capFor = (t: TaskRow) => (t.state === "queued" || t.state === "running" ? RELAY_LIMITS.reportBytes : t.state === "sending" ? RELAY_LIMITS.refusalBytes : RELAY_LIMITS.smallReportBytes);
/** The reports that carry ComfyUI's own answer; every other one is a few words. */
@@ -99,8 +108,9 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
// Where the job is now (it may have moved while the body arrived).
const t = leased(principal, id, lease);
const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => planRelayOutputs(t, entries, passes)));
- // A worker's finished job counts toward its lane's times there.
- if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running") noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
+ // A worker's finished job counts toward its lane's times there (not results kept from an earlier try: their time
+ // there would be only the upload's).
+ if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running" && !event.kept) noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
return Response.json(answer, { headers: { "Cache-Control": "no-store" } });
} catch (e) {
return relayAnswer(e);
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index bc0a9523..6a73c8ec 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -95,6 +95,8 @@ export interface WorkerHooks {
/** One kept file, or null. */
file(t: ClaimedTask, w: ResultFile): Promise<Blob | null>;
has(taskId: string): boolean;
+ /** Let go of one task's kept results. */
+ drop(taskId: string): void;
};
/**
* An input as its ComfyUI gets it. `read` fetches it from the studio (or says why it couldn't); the worker may keep a
@@ -102,16 +104,23 @@ export interface WorkerHooks {
* worker can't, the job goes back to the line ("give-back").
*/
input(t: ClaimedTask, i: TaskInput, read: () => Promise<ArrayBuffer | TabFailure>): Promise<ArrayBuffer | TabFailure | "give-back">;
- /** A job with no progress for this long (ms) goes back to the line. */
+ /**
+ * A job with no progress for this long (ms) goes back to the line: the claim's `stallMs` (the studio's limit), else
+ * this. `stallLocalMs`, when the PC sets one, wins over both.
+ */
stallMs: number;
+ stallLocalMs?: number | null;
/** Free its ComfyUI's memory (before the one retry after it ran out). */
free(): Promise<void>;
/** How many times its ComfyUI stopped while it ran this task. */
crashes(t: ClaimedTask): number;
/** Its ComfyUI won't let go of a prompt: stop it (the worker starts it again). */
stuck(): Promise<void>;
- /** What a claim answered, before the job runs: a task, or null (none was this worker's or waiting for it). */
- claimed(t: ClaimedTask | null): void | Promise<void>;
+ /**
+ * What a claim answered, before the job runs: a task, or null (none was this worker's or waiting for it).
+ * `onlyHeld`: the claim was made only to send kept results (the worker may not take other work now).
+ */
+ claimed(t: ClaimedTask | null, o: { onlyHeld: boolean }): void | Promise<void>;
}
/** ComfyUI's words for running out of memory (lib/gpu/fix-codes.ts says the same). */
@@ -186,7 +195,20 @@ export interface RunnerView {
facts?: ComputerFacts;
}
-class Stopped extends Error {}
+/** The job stops here. `gone`: the studio no longer has it for this principal (404), so nothing of it is worth keeping. */
+class Stopped extends Error {
+ constructor(readonly gone = false) {
+ super(gone ? "The studio no longer has this job" : "Stopped");
+ }
+}
+
+/**
+ * The shortest run limit a worker obeys: a claim's runLimitMs below this (an older studio's 5-minute floor for a lane
+ * it has no times for) is ignored, and the stall rule and the studio's own clocks still apply.
+ */
+export const MIN_RUN_LIMIT_MS = 10 * 60_000;
+/** The shortest stall limit a worker takes from a claim (a shorter one would give back jobs between two looks). */
+export const MIN_STALL_MS = 60_000;
const PROGRESS_EVERY_MS = 500;
const POLL_MS = 1000;
@@ -426,7 +448,7 @@ export class ComputerRunner {
throw new Stopped();
}
// The job ended or another tab has it: this tab lets go.
- if (res.status === 404 || res.status === 409) throw new Stopped();
+ if (res.status === 404 || res.status === 409) throw new Stopped(res.status === 404);
if (res.status === 429 && this.now() < until) {
await this.sleep(retryAfter(res));
continue;
@@ -549,14 +571,14 @@ export class ComputerRunner {
const res = await this.deps.api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: this.o.device, running }) });
if (res.status !== 200) {
if (res.status === 401) this.stop("signed-out");
- if (res.status === 204) await this.deps.worker?.claimed(null);
+ if (res.status === 204) await this.deps.worker?.claimed(null, { onlyHeld: !!o.onlyHeld });
return false;
}
const { task } = (await res.json()) as { task: ClaimedTask };
this.leases.set(task.id, task.lease);
const worker = this.deps.worker;
if (worker) {
- await worker.claimed(task);
+ await worker.claimed(task, { onlyHeld: !!o.onlyHeld });
// Only kept results now: any other job waits for its ComfyUI (one never sent goes back to the line at once).
if (o.onlyHeld && !worker.hold.has(task.id)) {
await this.deps.api(`/api/gpu/computer/tasks/${task.id}/release`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: task.lease }) }).catch(() => null);
@@ -613,9 +635,10 @@ export class ComputerRunner {
let wanted = t.wanted;
let phase = t.resume ?? "sending";
if (held && phase !== "collecting") {
- // The studio hasn't heard that it finished (or it went back in line since, and came back here).
- if (phase === "sending") await this.report(t, { event: "sent", promptId: t.promptId });
- const a = await this.report(t, this.endReport(held));
+ // The studio hasn't heard that it finished (or it went back in line since, and came back here). Nothing runs
+ // again: the reports say so, so this isn't another attempt and its time isn't a new one for the lane.
+ if (phase === "sending") await this.report(t, { event: "sent", promptId: t.promptId, kept: true });
+ const a = await this.report(t, this.endReport(held, true));
if (a.stop) throw new Stopped();
if (!a.wanted) return this.job(t, { phase: a.state === "done" ? "done" : "failed" });
wanted = a.wanted;
@@ -656,15 +679,22 @@ export class ComputerRunner {
if (!entries) entries = await this.ownEntries(t);
await this.collect(t, wanted, entries, t.received ?? []);
} catch (e) {
- if (e instanceof Stopped) return this.job(t, { phase: "failed" });
+ if (e instanceof Stopped) {
+ // The studio has no such job any more: a worker's kept results of it are of no use.
+ if (e.gone) this.deps.worker?.hold.drop(t.id);
+ return this.job(t, { phase: "failed" });
+ }
throw e;
}
}
- /** A worker's report of a finished job: its entries, its ComfyUI's execution time and its GPU's name. */
- private endReport(held: HeldResults): ReportEvent {
+ /**
+ * A worker's report of a finished job: its entries, its ComfyUI's execution time and its GPU's name (`kept`: results
+ * kept from an earlier try).
+ */
+ private endReport(held: HeldResults, kept = false): ReportEvent {
const device = deviceName(this.view.facts?.device);
- const exec = { ...(held.execMs !== undefined && { execMs: Math.round(held.execMs) }), ...(device && { device }) };
+ const exec = { ...(held.execMs !== undefined && { execMs: Math.round(held.execMs) }), ...(device && { device }), ...(kept && { kept }) };
return held.kind === "passes" ? { event: "passes", running: false, entries: held.entries.map(slim), ...exec } : { event: "finished", entry: slim(held.entries[0] ?? {}), ...exec };
}
@@ -832,9 +862,8 @@ export class ComputerRunner {
let lastSent = 0;
let lastKey = "";
let following: string | undefined;
- // A worker's watchdog: when the job started here, and when it last moved (a step, a node, its place, a pass).
- const began = this.now();
- let movedAt = began;
+ // A worker's watchdog: when the job last moved (a step, a node, its place, a pass).
+ let movedAt = this.now();
let moveKey = "";
const moved = (key: string) => {
if (key !== moveKey) {
@@ -842,11 +871,16 @@ export class ComputerRunner {
movedAt = this.now();
}
};
- // Execution time: what ComfyUI's entries say, else the time it was seen running here.
+ // The run limit counts from when its ComfyUI first runs the job (its wait in ComfyUI's own queue doesn't count). A
+ // limit under MIN_RUN_LIMIT_MS (an older studio's floor for a lane it has no times for) isn't one to obey.
+ const runLimit = t.runLimitMs && t.runLimitMs >= MIN_RUN_LIMIT_MS ? t.runLimitMs : null;
+ // The stall limit: the PC's own when it sets one, else the claim's (at least MIN_STALL_MS), else the worker's default.
+ const stallMs = worker ? (worker.stallLocalMs ?? (t.stallMs && t.stallMs >= MIN_STALL_MS ? t.stallMs : worker.stallMs)) : Infinity;
+ // Execution time: what ComfyUI's entries say, else the time it was seen running here. After the retry for running
+ // out of memory, only the retry's own time counts (the first try was this worker's, not the run's).
let runningSince: number | null = null;
- let spentMs = 0;
let oomRetried = false;
- const execOf = (entries: HistoryEntryLike[]) => spentMs + (execTime(entries) ?? (runningSince !== null ? this.now() - runningSince : 0));
+ const execOf = (entries: HistoryEntryLike[]) => execTime(entries) ?? (runningSince !== null ? this.now() - runningSince : 0);
const exec = (ms: number) => {
const device = deviceName(this.view.facts?.device);
return worker ? { execMs: Math.round(ms), ...(device && { device }) } : {};
@@ -854,8 +888,8 @@ export class ComputerRunner {
for (;;) {
if (!this.alive) throw new Stopped();
if (worker) {
- if (t.runLimitMs && this.now() - began > t.runLimitMs) return { giveBack: "run-limit" };
- if (this.now() - movedAt > worker.stallMs) return { giveBack: "stalled" };
+ if (runLimit && runningSince !== null && this.now() - runningSince > runLimit) return { giveBack: "run-limit" };
+ if (this.now() - movedAt > stallMs) return { giveBack: "stalled" };
}
if (following) {
// A meta-batch: its passes run under new ids, all with its prefix.
@@ -867,6 +901,7 @@ export class ComputerRunner {
}
const queued = [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].filter((r) => hasPrefix(r[2], following!));
const running = queued.length > 0;
+ if (running) runningSince ??= this.now();
const passes = Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], following!));
const ev = this.events.get(String(queued[0]?.[1] ?? ""));
moved(JSON.stringify([queued.map((r) => r[1]), passes.length, ev?.value, ev?.node, ev?.nodesDone]));
@@ -889,7 +924,6 @@ export class ComputerRunner {
// A worker's ComfyUI ran out of memory: free it, and send the prompt once more before saying anything.
if (worker && !oomRetried && outOfMemory(w.entry)) {
oomRetried = true;
- spentMs = execOf([w.entry]);
runningSince = null;
await worker.free().catch(() => {});
if (await this.resend(t)) {
diff --git a/src/lib/lanes.ts b/src/lib/lanes.ts
index b1d12ac3..93679ccb 100644
--- a/src/lib/lanes.ts
+++ b/src/lib/lanes.ts
@@ -104,7 +104,8 @@ export function mediaOf(wf: Pick<IndexWorkflow, "core" | "packs">): ("video" | "
/**
* A worker's verified files and node packs (PUT /api/gpu/computer/inventory), and the kinds of input it takes (`media`:
- * a worker without a way to make clips and sound again takes pictures only). No `media`: every kind.
+ * a worker without a way to make clips and sound again takes pictures only). No `media` (a worker from before workers
+ * made clips and sound again): pictures only.
*/
export interface Inventory {
files: FileNeed[];
@@ -129,7 +130,7 @@ export function lanesFor(
sha: Sha,
): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {
const packs = new Set(inv.nodePacks.map((p) => p.name));
- const takes = new Set<string>(inv.media ?? MEDIA_KINDS);
+ const takes = new Set<string>(inv.media ?? ["image"]);
const ok = new Map<string, boolean>();
const workflows: string[] = [];
const lacking = new Map<string, Map<string, number>>();
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 0d0a7b2c..7223d849 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -40,8 +40,11 @@ export type GiveBackWhy = (typeof GIVE_BACK)[number];
/** What the tab reports about one task. */
export type ReportEvent =
- /** ComfyUI took the prompt (`promptId`: the id it answered, the server's own unless an older ComfyUI minted one). */
- | { event: "sent"; promptId: string; number?: number }
+ /**
+ * ComfyUI took the prompt (`promptId`: the id it answered, the server's own unless an older ComfyUI minted one).
+ * `kept`: a worker sends results it kept from an earlier try instead (nothing new runs, so it isn't another attempt).
+ */
+ | { event: "sent"; promptId: string; number?: number; kept?: boolean }
/** ComfyUI's /prompt refused it (its answer, as it was). */
| { event: "refused"; status: number; body: unknown }
/** Waiting in ComfyUI's queue: how many prompts are before it. */
@@ -50,14 +53,15 @@ export type ReportEvent =
| { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }
/**
* Finished: its /history entry. A worker adds the most VRAM it took (for the benchmarks), how long its ComfyUI spent
- * executing the job (`execMs`: execution only, no waits, no uploads) and its GPU's name (`device`).
+ * executing the job (`execMs`: execution only, no waits, no uploads), its GPU's name (`device`), and `kept` when the
+ * results are ones it kept from an earlier try (their time doesn't count toward the lane's times).
*/
- | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string }
+ | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string; kept?: boolean }
/**
* A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. The
- * last one (not running) is the job's end: a worker adds `execMs` and `device` as for "finished".
+ * last one (not running) is the job's end: a worker adds `execMs`, `device` and `kept` as for "finished".
*/
- | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string }
+ | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string; kept?: boolean }
/** A worker gives the task back to the line (it counts as an attempt). */
| { event: "give-back"; why: GiveBackWhy }
/** ComfyUI has no trace of it (restarted): the server sends it again once. */
@@ -129,10 +133,14 @@ export interface ClaimedTask {
/** Collecting: the files still to upload, and how far each got. */
wanted?: WantedFile[];
received?: { n: number; bytes: number; done: boolean }[];
- /** A worker's task (docs/gpu-workers.md): its lane, how long it should take there, when to stop it, and its files. */
+ /**
+ * A worker's task (docs/gpu-workers.md): its lane, how long it should take there, when to stop it (`runLimitMs`: running
+ * past it; `stallMs`: no progress for that long), and its files.
+ */
lane?: string;
estMs?: number | null;
runLimitMs?: number;
+ stallMs?: number;
notAfter?: number | null;
attempt?: number;
models?: { folder: string; name: string; size: number; sha256: string | null }[];
@@ -167,6 +175,8 @@ export interface BeatAnswer {
waiting: number;
/** Prompts to take off this computer's ComfyUI. */
stops: { task: string; promptId: string; prefix?: string }[];
+ /** A worker's: people's tasks (never the owner's own) it may claim now; its own pause doesn't count here. */
+ claimableNow?: number;
/** A worker's own (docs/gpu-workers.md): what the studio says about it now. */
worker?: WorkerAnswer;
}
@@ -206,6 +216,8 @@ export interface WorkerBeat {
warmLane: string | null;
running: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
stopped: string[];
+ /** The tasks whose finished results the worker keeps on its disk (a stop-now leaves them its own, to send them up). */
+ held?: string[];
}
/** Task timings (DESIGN 5.5): the runner lease, how often the tab beats, when a computer counts as gone. */
@@ -376,9 +388,9 @@ export function tabFailureWords(reason: TabFailure, status?: number): string {
case "model-unverified":
return "The GPU that took this run refused it: it needs a model file that GPU couldn't verify.";
case "input-crashed":
- return "This run stopped twice at the same point. Try another file or different settings.";
+ return "This run couldn't finish with these files or settings.";
case "input-unreadable":
- return "A clip or a sound in this run couldn't be read. Try another file.";
+ return "A clip or sound in this run couldn't be read.";
default:
return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;
}
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index ff82f7f1..135e632c 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -5,7 +5,7 @@ import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type Compu
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
-import { cleanFacts, endTask, getTask, json, noteProgress, setPoolClocks, setPoolGiveBack, setTask, takeTask, type TaskRow } from "./tasks";
+import { cleanFacts, endTask, getTask, json, noteProgress, setPoolCeiling, setPoolClocks, setPoolGiveBack, setTask, takeTask, type TaskRow } from "./tasks";
import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
/**
@@ -16,16 +16,38 @@ import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./work
* lanes, and the owner's controls. Nothing here runs unless the owner adds a worker.
*/
-/** The oldest worker program this studio still talks to. */
-export const MIN_PROTOCOL = 1;
+/**
+ * The oldest worker program that may take tasks: 2 says which inputs it takes, makes every clip and sound again, checks
+ * every input against its rules, and keeps its ComfyUI behind the guard. An older one is told to update.
+ */
+export const MIN_PROTOCOL = 2;
/** A task avoids workers that lost or failed it, unless no other worker that can run it beat this recently. */
export const RETRY_WINDOW_MS = 10 * 60_000;
/** Attempts in all before a task fails. */
export const MAX_ATTEMPTS = 3;
/** A worker that beat this recently may claim. */
const FRESH_BEAT_MS = 30_000;
-/** The run limit: 3 × the lane's p90 on that worker, at least 5 minutes, at most 45. */
-export const runLimitMs = (p90?: number | null) => Math.min(45 * 60_000, Math.max(5 * 60_000, 3 * (p90 ?? 0)));
+/** The longest one attempt at a job may run on a worker (the generation's own clock is the same 45 minutes). */
+export const RUN_CEILING_MS = 45 * 60_000;
+/** Run ceilings of their own for some lanes (none yet: every lane has RUN_CEILING_MS). */
+const LANE_CEILINGS: Readonly<Record<string, number>> = {};
+/** A lane's run ceiling. */
+export const runCeilingMs = (lane?: string | null) => (lane && LANE_CEILINGS[lane]) || RUN_CEILING_MS;
+/** A job that makes no progress for this long goes back in line (a worker's own worker.json may set another). */
+export const STALL_MS = 10 * 60_000;
+/** Stall limits of their own for some lanes (none yet: every lane has STALL_MS). */
+const LANE_STALLS: Readonly<Record<string, number>> = {};
+/** A lane's stall limit, which the claim gives the worker. */
+export const stallLimitMs = (lane?: string | null) => (lane && LANE_STALLS[lane]) || STALL_MS;
+/**
+ * The run limit of one attempt: 3 × the lane's p90 on that worker plus its model load, at least 10 minutes, and never
+ * past the lane's run ceiling. With no p90 yet (a new worker, a new lane), the ceiling: a first long job finishes.
+ */
+export const runLimitMs = (p90?: number | null, lane?: string | null, loadMs?: number | null) => {
+ const ceiling = runCeilingMs(lane);
+ if (!p90 || p90 <= 0) return ceiling;
+ return Math.min(ceiling, Math.max(10 * 60_000, 3 * p90 + Math.max(0, loadMs ?? 0)));
+};
/** The owner's own tasks go ahead of everyone else's by this much (rank_at = created_at - boost). */
export const OWNER_BOOST_MS = 24 * 60 * 60_000;
@@ -53,6 +75,7 @@ export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerStat
const tz = hoursOf(w) && "tz" in hoursOf(w)! ? (hoursOf(w) as { tz: string }).tz : undefined;
if (!w.seen_at) return { state: "new", words: "Not connected yet" };
if (now - w.seen_at > RELAY_TIMES.poolSilentMs) return { state: "offline", words: "Offline" };
+ if ((w.protocol ?? 0) < MIN_PROTOCOL) return { state: "paused", words: "Takes no jobs until its worker program is updated" };
const why = w.local_why ?? "";
if (w.paused_local) {
if (why.startsWith("gpu-busy")) return { state: "gpu-busy", words: `Your GPU is busy${why.includes(":") ? ` (${why.split(":").slice(1).join(":")})` : ""}` };
@@ -112,6 +135,7 @@ export function cleanBeat(b: unknown): WorkerBeat {
warmLane: text(o.warmLane, 16),
running: Array.isArray(o.running) ? (o.running.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],
stopped: Array.isArray(o.stopped) ? o.stopped.filter((x): x is string => typeof x === "string").slice(0, 64) : [],
+ held: Array.isArray(o.held) ? o.held.filter((x): x is string => typeof x === "string").slice(0, 16) : [],
};
}
@@ -147,8 +171,11 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
// 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")));
if (stopNow) {
+ const held = new Set(b.held ?? []);
for (const t of d.prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(w.id) as TaskRow[]) {
- if (t.state === "collecting") continue; // Its result is being saved: let it finish.
+ // Its result is being saved, or the worker keeps the finished results on its disk (the studio may not have heard
+ // that it finished): let it send them, which needs no GPU, instead of running the job again.
+ if (t.state === "collecting" || held.has(t.id)) continue;
backInLine(t, { blame: false });
stops.push({ task: t.id, promptId: t.prompt_id, ...(t.prefix && { prefix: t.prefix }) });
}
@@ -164,6 +191,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
runner: eligible(fresh, now),
heldElsewhere: false,
waiting,
+ claimableNow: claimableNow(fresh, now),
stops,
worker: {
paused: !!fresh.paused_server,
@@ -180,6 +208,20 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
})();
}
+/**
+ * People's tasks (an account's, never the owner's own) this worker may claim right now: in its pool, in a lane it is
+ * allowed and able to run, with the files and VRAM they need, past their delays, and ending before its hours do. Its
+ * own pause doesn't count here (its PC reads this to know whether a person's run waits for it); a pause on the website,
+ * a drain, an older worker program or being outside its hours does.
+ */
+export function claimableNow(w: WorkerRow, now = Date.now()): number {
+ if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;
+ const rows = db()
+ .prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS NOT NULL AND INSTR(',' || pools || ',', ?) > 0 ORDER BY rank_at LIMIT ?")
+ .all(`,${w.pool},`, LOOK_AT) as TaskRow[];
+ return rows.filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;
+}
+
// ---------------------------------------------------------------------------
// Inventory
@@ -199,7 +241,8 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; wo
const name = text(x?.name, 128);
return name ? [{ name, commit: text(x?.commit, 64) }] : [];
});
- // The kinds of input it takes (none said: every kind, as before workers said so).
+ // The kinds of input it takes. None said: an older worker, which doesn't make clips and sound again, so lanesFor gives
+ // it pictures only (the list is kept as sent, so its hash stays the one the worker computes).
const media = Array.isArray(o.media) ? MEDIA_KINDS.filter((k) => (o.media as unknown[]).includes(k)) : undefined;
const inv: Inventory = { files, nodePacks, ...(media && { media }) };
const r = lanesFor(loadIndex(), inv, sha);
@@ -247,13 +290,16 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now()):
function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {
const needs = json<Needs | null>(t.needs_json, null);
- const p90 = t.lane ? benchOf(w)[t.lane]?.p90Ms : undefined;
+ const bench = t.lane ? benchOf(w)[t.lane] : undefined;
const c = takeTask(t, device, now, { worker_id: w.id });
return {
...c,
lane: t.lane ?? undefined,
estMs: estOn(t, w),
- runLimitMs: runLimitMs(p90),
+ // A job given back once for running past its limit gets the whole run ceiling on its next try (a lane's times may
+ // come from shorter jobs than this one); past that, it fails.
+ runLimitMs: runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs),
+ stallMs: stallLimitMs(t.lane),
notAfter: t.not_after,
attempt: t.requeues + 1,
models: needs?.files ?? [],
@@ -318,10 +364,10 @@ function pick(w: WorkerRow, now: number): TaskRow | null {
* its ComfyUI down: the worker is noted in tried_json and it counts as an attempt). The third lost attempt fails it.
* The old worker's lease stops working, so its late calls get 409.
*/
-export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): void {
+export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; last?: boolean }): void {
const tried = json<string[]>(t.tried_json, []);
const requeues = t.requeues + (o.blame ? 1 : 0);
- if (o.blame && requeues >= MAX_ATTEMPTS) {
+ if (o.blame && (requeues >= MAX_ATTEMPTS || o.last)) {
endTask(t.id, "failed", { error: o.why ?? "The GPUs couldn't finish this run. Press Retry.", requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);
return;
}
@@ -368,15 +414,28 @@ setPoolClocks((t, now) => {
return getTask(t.principal, t.id) ?? t;
});
-/** The words of a run whose worker gave it back the third time. */
-export const GAVE_BACK_WORDS = "This run couldn't finish. Press Retry.";
+/** The words of a run that a worker gave back for the last time. */
+export const GAVE_BACK_WORDS = "This run couldn't finish.";
+
+/** A task a worker gave back for running past its run limit (its next try gets the whole run ceiling). */
+const runLimitedOf = (t: TaskRow) => json<{ runLimited?: boolean }>(t.extra_json, {}).runLimited === true;
/**
* A worker gives its task back (it stalled, ran past its run limit, or takes clips or sound the worker can't make
* again): it goes back in line with its place kept, and counts as an attempt, so another worker that can run it is
- * preferred and the third time fails it.
+ * preferred and the third time fails it. Past its run limit a second time (that try had the whole run ceiling), it
+ * fails at once: one more try would only hold a GPU as long again.
*/
-setPoolGiveBack((t) => backInLine(t, { blame: true, why: GAVE_BACK_WORDS }));
+setPoolGiveBack((t, why) => {
+ if (why === "run-limit") {
+ if (runLimitedOf(t)) return backInLine(t, { blame: true, why: GAVE_BACK_WORDS, last: true });
+ setTask(t.id, { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), runLimited: true }) });
+ }
+ backInLine(t, { blame: true, why: GAVE_BACK_WORDS });
+});
+
+/** A worker's reported execution time is never more than its task's run ceiling. */
+setPoolCeiling((t) => runCeilingMs(t.lane));
// ---------------------------------------------------------------------------
// Place in line and the wait (4.4)
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index e0183b87..5f98cefd 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -546,7 +546,8 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
case "sent": {
const promptId = typeof e.promptId === "string" && UUID.test(e.promptId) ? e.promptId : typeof e.promptId === "string" && /^[\w-]{1,64}$/.test(e.promptId) ? e.promptId : null;
if (!promptId) throw new RelayError(400, "Bad prompt id");
- setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + 1 });
+ // Results a worker kept from an earlier try go up instead: no new attempt.
+ setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + (t.pools && e.kept ? 0 : 1) });
return { ok: true };
}
case "refused":
@@ -570,7 +571,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
const entries = e.event === "finished" ? [e.entry] : e.entries;
if (!Array.isArray(entries) || entries.some((x) => !x || typeof x !== "object")) throw new RelayError(400, "Bad history entry");
// A worker's measured execution time and GPU, kept with the task for metering.
- const exec = execFields(e);
+ const exec = execFields(e, t);
const extra = (more: Record<string, unknown> = {}) => ({ ...(exec || Object.keys(more).length ? { extra_json: JSON.stringify({ ...extraOf(t), ...(exec && { exec }), ...more }) } : {}) });
const p = plan(entries, e.event === "passes");
if ("follow" in p) {
@@ -812,15 +813,29 @@ export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (pool
let poolGiveBack: ((t: TaskRow, why: GiveBackWhy) => void) | null = null;
export const setPoolGiveBack = (fn: (t: TaskRow, why: GiveBackWhy) => void) => (poolGiveBack = fn);
-/** The execution time (ms, at most a week) and GPU name a worker reported with a finished job, as kept. */
+/** A task's run ceiling (pool.ts sets this): the most a worker's reported execution time may be. */
+let poolCeiling: ((t: TaskRow) => number) | null = null;
+export const setPoolCeiling = (fn: (t: TaskRow) => number) => (poolCeiling = fn);
+
+/** The execution time (ms) and GPU name a worker reported with a finished job, as kept. */
export interface ExecFacts {
ms: number;
device?: string;
}
-function execFields(e: ReportEvent): ExecFacts | null {
+/** ComfyUI starts a job as soon as it takes it, a little before the studio hears "sent": the time allowed for that. */
+const SENT_SLACK_MS = 60_000;
+
+/**
+ * The execution time a worker reports, held to what is possible: at most a day, at most the task's run ceiling, and at
+ * most the time since it sent the job to its ComfyUI (or, with no send noted, since the task was made). Results kept from
+ * an earlier try ran before their "sent" (it notes only the upload): for them, the time since the task was made.
+ */
+function execFields(e: ReportEvent, t: TaskRow, now = Date.now()): ExecFacts | null {
if (e.event !== "finished" && e.event !== "passes") return null;
- const ms = typeof e.execMs === "number" && Number.isFinite(e.execMs) && e.execMs >= 0 ? Math.min(Math.round(e.execMs), 7 * 24 * 3_600_000) : null;
+ const since = e.kept ? t.created_at : (t.sent_at ?? t.created_at);
+ const most = Math.max(0, Math.min(24 * 3_600_000, poolCeiling?.(t) ?? Infinity, now - since + SENT_SLACK_MS));
+ const ms = typeof e.execMs === "number" && Number.isFinite(e.execMs) && e.execMs >= 0 ? Math.min(Math.round(e.execMs), most) : null;
if (ms === null) return null;
const device = typeof e.device === "string" && e.device.trim() ? e.device.trim().slice(0, FACT_LIMITS.text) : undefined;
return { ms, ...(device && { device }) };
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 8137c6da..5b85363a 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -2322,8 +2322,10 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
if (!found) return { state: "failed", error: "This run was lost. Press Retry." };
const t = checkClocks(found);
// A run on the workers: while it waits, its place in line; once a worker has it, that worker's reports (a worker that
- // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer").
- if (t.pools && t.state === "waiting") return { state: "queued", message: t.note === "resent" ? "Back in line for another GPU" : poolWaitWords(t) };
+ // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer"). Back in line after an attempt
+ // (a worker paused, went quiet, gave it back), it shows its kept place as any waiting run does, and once a worker has
+ // it again, the usual words: never a restart.
+ if (t.pools && t.state === "waiting") return { state: "queued", message: poolWaitWords(t) };
const p = taskProgress(t.id);
const kind = extraOf(t).made ?? made ?? "image";
const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;
@@ -2340,7 +2342,7 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
return { state: "queued", message, timeoutError: RELAY_WORDS.waitedTooLong(waitMs) };
}
case "sending":
- return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMs), ...(sentAt && { sentAt }) };
+ return { state: "queued", message: down ?? (t.note === "resent" && !t.pools ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMs), ...(sentAt && { sentAt }) };
case "queued":
return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };
case "running": {
diff --git a/tests/worker-environment.test.ts b/tests/worker-environment.test.ts
index ee6de1b3..9ddc91db 100644
--- a/tests/worker-environment.test.ts
+++ b/tests/worker-environment.test.ts
@@ -4,8 +4,8 @@ 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 { modelFiles, nodePacks, packFolders } from "../bin/lib/worker/inventory.mjs";
+import { comfyArgs, comfyEnv, defaultPathsFlag, modelPathsYaml, OFFLINE_ENV, OwnComfy } from "../bin/lib/worker/comfy.mjs";
+import { modelFiles, nodePacks, packFolders, yamlModelDirs } 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";
@@ -70,6 +70,99 @@ describe("the worker's model files", () => {
// The hashes are kept, so the next start reads nothing again.
expect(Object.keys(JSON.parse(fs.readFileSync(cache, "utf8")))).toHaveLength(3);
});
+
+ it("counts only the copy ComfyUI finds first: a wrong copy in an earlier folder isn't made up for by a good one later", async () => {
+ const a = tempDir("fuobe-worker-models-a-");
+ const b = tempDir("fuobe-worker-models-b-");
+ for (const d of [a, b]) fs.mkdirSync(path.join(d, "loras"));
+ // The same name and size in both: the first folder's copy is another file.
+ fs.writeFileSync(path.join(a, "loras", "x.safetensors"), "EVIL!");
+ fs.writeFileSync(path.join(b, "loras", "x.safetensors"), "GOOD!");
+ // A folder (not a file) under the name doesn't count as a copy, as for ComfyUI: the next folder's file is the one.
+ fs.mkdirSync(path.join(a, "loras", "y.safetensors"));
+ fs.writeFileSync(path.join(b, "loras", "y.safetensors"), "GOOD!");
+ const index = { files: { x: { folder: "loras", file: "x.safetensors", sizeBytes: 5 }, y: { folder: "loras", file: "y.safetensors", sizeBytes: 5 } } };
+ const pins = { "loras/x.safetensors": sha("GOOD!"), "loras/y.safetensors": sha("GOOD!") };
+ const cache = path.join(tempDir("fuobe-worker-cache-"), "hash-cache.json");
+ expect(await modelFiles([a, b], index, cache, pins)).toEqual([{ folder: "loras", name: "y.safetensors", size: 5, sha256: sha("GOOD!") }]);
+ // The good copy first: reported.
+ expect((await modelFiles([b, a], index, cache, pins)).map((f) => f.name).sort()).toEqual(["x.safetensors", "y.safetensors"]);
+ });
+
+ it("refuses a file that ComfyUI's own models folder or its own extra_model_paths.yaml has with other content", async () => {
+ const models = tempDir("fuobe-worker-models-");
+ const comfyDir = tempDir("fuobe-worker-comfy-");
+ const extra = tempDir("fuobe-worker-extra-");
+ fs.mkdirSync(path.join(models, "loras"));
+ fs.mkdirSync(path.join(models, "diffusion_models"));
+ for (const f of ["a", "b", "c", "d"]) fs.writeFileSync(path.join(models, "loras", `${f}.safetensors`), "GOOD!");
+ fs.writeFileSync(path.join(models, "diffusion_models", "u.safetensors"), "GOOD!");
+ // ComfyUI's own models folder: another a, and the same b; its older name for diffusion_models (unet) holds another u.
+ fs.mkdirSync(path.join(comfyDir, "models", "loras"), { recursive: true });
+ fs.mkdirSync(path.join(comfyDir, "models", "unet"), { recursive: true });
+ fs.writeFileSync(path.join(comfyDir, "models", "loras", "a.safetensors"), "EVIL!");
+ fs.writeFileSync(path.join(comfyDir, "models", "loras", "b.safetensors"), "GOOD!");
+ fs.writeFileSync(path.join(comfyDir, "models", "unet", "u.safetensors"), "EVIL!");
+ // Its own extra_model_paths.yaml adds a folder with another c (another size, too).
+ fs.mkdirSync(path.join(extra, "my-loras"));
+ fs.writeFileSync(path.join(extra, "my-loras", "c.safetensors"), "EVIL!!!");
+ fs.writeFileSync(path.join(comfyDir, "extra_model_paths.yaml"), `other:\n base_path: ${extra}\n loras: my-loras/\n`);
+ type F = { folder: string; file: string; sizeBytes: number };
+ const entries: [string, F][] = [..."abcd"].map((f) => [f, { folder: "loras", file: `${f}.safetensors`, sizeBytes: 5 }]);
+ const index: { files: Record<string, F> } = { files: Object.fromEntries([...entries, ["u", { folder: "diffusion_models", file: "u.safetensors", sizeBytes: 5 }]]) };
+ const pins = Object.fromEntries(Object.values(index.files).map((f) => [`${f.folder}/${f.file}`, sha("GOOD!")]));
+ const found = await modelFiles([models], index, path.join(models, "hash-cache.json"), pins, { comfyDir });
+ expect(found.map((f) => f.name).sort()).toEqual(["b.safetensors", "d.safetensors"]);
+ // The worker's model folder is ComfyUI's own models folder (setup's default): the same files, all reported.
+ const same = await modelFiles([path.join(comfyDir, "models")], { files: { b: index.files.b } }, path.join(models, "hash-cache.json"), pins, { comfyDir });
+ expect(same.map((f) => f.name)).toEqual(["b.safetensors"]);
+ });
+
+ it("reads the folders an extra_model_paths.yaml adds as ComfyUI does", () => {
+ const dir = path.resolve("/comfy");
+ const text = [
+ "# ComfyUI's own example shape",
+ "a111:",
+ " base_path: ~/sd # a comment",
+ " is_default: true",
+ " checkpoints: models/Stable-diffusion",
+ " unet: models/unet",
+ " loras: |",
+ " models/Lora",
+ " models/LyCORIS",
+ " clip: \"models/clip\"",
+ "rel:",
+ " base_path: ../shared",
+ " vae: vae",
+ "noBase:",
+ " upscale_models: up",
+ "nothing:",
+ ].join("\n");
+ const d = yamlModelDirs(text, dir, {}, path.resolve("/home/me"));
+ expect(d.checkpoints).toEqual([path.normalize(path.resolve("/home/me/sd/models/Stable-diffusion"))]);
+ expect(d.diffusion_models).toEqual([path.normalize(path.resolve("/home/me/sd/models/unet"))]);
+ expect(d.loras).toEqual([path.resolve("/home/me/sd/models/Lora"), path.resolve("/home/me/sd/models/LyCORIS")].map((p) => path.normalize(p)));
+ expect(d.text_encoders).toEqual([path.normalize(path.resolve("/home/me/sd/models/clip"))]);
+ expect(d.vae).toEqual([path.resolve("/shared/vae")]);
+ expect(d.upscale_models).toEqual([path.resolve("/comfy/up")]);
+ expect(d.is_default).toBeUndefined();
+ });
+
+ it("puts its model folders first in ComfyUI's search, in their order, when its ComfyUI knows is_default", () => {
+ const first = modelPathsYaml(["D:/a", "E:/b"], ["loras"], { first: true });
+ expect(first).toBe(['fuobe_worker_1:', ' base_path: "E:/b"', " is_default: true", " loras: loras", 'fuobe_worker_0:', ' base_path: "D:/a"', " is_default: true", " loras: loras", ""].join("\n"));
+ // ComfyUI (folder_paths.add_model_folder_path) puts each is_default folder at the front, in the order it reads them.
+ const search = ["<its own models>/loras"];
+ for (const m of first.matchAll(/base_path: "(.+)"/g)) search.unshift(`${m[1]}/loras`);
+ expect(search).toEqual(["D:/a/loras", "E:/b/loras", "<its own models>/loras"]);
+ // An older ComfyUI stops on is_default: none, in the order given.
+ expect(modelPathsYaml(["D:/a", "E:/b"], ["loras"])).toBe(['fuobe_worker_0:', ' base_path: "D:/a"', " loras: loras", 'fuobe_worker_1:', ' base_path: "E:/b"', " loras: loras", ""].join("\n"));
+ const comfyDir = tempDir("fuobe-worker-comfy-");
+ expect(defaultPathsFlag(comfyDir)).toBe(false);
+ fs.mkdirSync(path.join(comfyDir, "utils"));
+ fs.writeFileSync(path.join(comfyDir, "utils", "extra_config.py"), 'is_default = False\nif "is_default" in conf:\n is_default = conf.pop("is_default")\n');
+ expect(defaultPathsFlag(comfyDir)).toBe(true);
+ });
});
describe("its own ComfyUI's environment", () => {
diff --git a/tests/worker-guard.test.ts b/tests/worker-guard.test.ts
index 5689a4a3..ffd4f24e 100644
--- a/tests/worker-guard.test.ts
+++ b/tests/worker-guard.test.ts
@@ -14,7 +14,7 @@ import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { comfyArgs, GUARD, GuardMissing, OwnComfy, partnerFlag, pickPort, PortBusy, restartDelayMs, RotatingLog } from "../bin/lib/worker/comfy.mjs";
+import { comfyArgs, GUARD, guardFlags, GuardMissing, OwnComfy, partnerFlag, pickPort, PortBusy, REQUEST_MS, restartDelayMs, RotatingLog } from "../bin/lib/worker/comfy.mjs";
import { tempDir } from "./helpers/temp-dir";
vi.setConfig({ testTimeout: 60_000 });
@@ -31,6 +31,22 @@ function pythonWithAiohttp(): string | null {
}
const python = pythonWithAiohttp();
+/**
+ * A venv's Python with aiohttp: that Python itself when it is a venv's, else a new venv made from it (with its site
+ * packages). On Windows a venv's python.exe starts the real Python as a process of its own. Null when none can be made.
+ */
+function venvPython(base: string | null): string | null {
+ if (!base) return null;
+ const inVenv = spawnSync(base, ["-I", "-c", "import sys; print(sys.prefix != sys.base_prefix)"], { encoding: "utf8", timeout: 20_000 });
+ if (inVenv.stdout?.trim() === "True") return base;
+ const dir = tempDir("fuobe-guard-venv-");
+ const made = spawnSync(base, ["-m", "venv", "--system-site-packages", "--without-pip", dir], { encoding: "utf8", timeout: 120_000 });
+ if (made.status !== 0) return null;
+ const exe = process.platform === "win32" ? path.join(dir, "Scripts", "python.exe") : path.join(dir, "bin", "python");
+ return spawnSync(exe, ["-I", "-c", "import aiohttp"], { timeout: 20_000 }).status === 0 ? exe : null;
+}
+const venv = venvPython(python);
+
/** A raw request, with any Host (fetch can't send another one). */
function raw(port: number, p: string, headers: Record<string, string>): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> {
return new Promise((resolve, reject) => {
@@ -46,7 +62,7 @@ function raw(port: number, p: string, headers: Record<string, string>): Promise<
/** A stand-in for ComfyUI's main.py: its server made as server.py makes it, with its own middleware and a sub-app. */
const STAND_IN_MAIN = String.raw`
-import argparse, os
+import argparse, os, sys
from aiohttp import web
p = argparse.ArgumentParser()
@@ -64,7 +80,7 @@ async def stats(request):
return web.json_response({"system": {"comfyui_version": "stand-in", "os": "nt"}, "devices": []})
async def env(request):
- return web.json_response({"keyInEnv": "FUOBE_WORKER_GUARD_KEY" in os.environ, "cwd": os.getcwd()})
+ return web.json_response({"keyInEnv": "FUOBE_WORKER_GUARD_KEY" in os.environ, "cwd": os.getcwd(), "isolated": sys.flags.isolated})
async def files(request):
return web.json_response(["a"])
@@ -112,6 +128,9 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()
const comfyDir = tempDir("fuobe-guard-comfy-");
const workDir = tempDir("fuobe-guard-work-");
fs.writeFileSync(path.join(comfyDir, "main.py"), STAND_IN_MAIN);
+ // A file left beside the guard from before (as a node writing a relative path could): gone, and never imported.
+ fs.mkdirSync(path.join(workDir, "guard"));
+ fs.writeFileSync(path.join(workDir, "guard", "hmac.py"), "raise SystemExit('a planted module ran')\n");
const c = new OwnComfy({ comfyDir, workDir, python, modelDirs: [] });
started.push(c);
await c.start();
@@ -119,8 +138,9 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()
const port = c.port!;
expect(port).toBeGreaterThanOrEqual(20_000);
expect(port).not.toBe(8188);
- // ComfyUI started from the guard, written into the worker folder, with the worker folder as its working folder.
- expect(fs.existsSync(path.join(workDir, "guard", "comfy_guard.py"))).toBe(true);
+ // ComfyUI started from the guard, written into an emptied folder in the worker folder, in Python's isolated mode,
+ // with the worker folder as its working folder.
+ expect(fs.readdirSync(path.join(workDir, "guard"))).toEqual(["comfy_guard.py"]);
const host = `127.0.0.1:${port}`;
const key = { [GUARD.key]: c.headers()[GUARD.key] };
// The worker's own requests: through, ComfyUI's own middleware still runs, its sub-app answers too.
@@ -128,8 +148,9 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()
expect(ok.status).toBe(200);
expect(ok.headers.get("x-own-middleware")).toBe("1");
expect((await c.fetch(`${c.base}/internal/files`)).status).toBe(200);
- const env = (await (await c.fetch(`${c.base}/env`)).json()) as { keyInEnv: boolean; cwd: string };
+ const env = (await (await c.fetch(`${c.base}/env`)).json()) as { keyInEnv: boolean; cwd: string; isolated: number };
expect(env.keyInEnv).toBe(false);
+ expect(env.isolated).toBe(1);
expect(fs.realpathSync(env.cwd)).toBe(fs.realpathSync(workDir));
// No key, a wrong key, another Host (a rebinding page's name, localhost): refused.
expect((await raw(port, "/system_stats", { Host: host })).status).toBe(403);
@@ -142,9 +163,9 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()
const challenge = crypto.randomBytes(16).toString("hex");
const hello = await raw(port, GUARD.hello, { Host: host, [GUARD.challenge]: challenge });
expect(hello.status).toBe(200);
- const proof = JSON.parse(hello.body) as { proof: string; pid: number };
+ const proof = JSON.parse(hello.body) as { proof: string; pid: number; ppid: number };
expect(proof.proof).toBe(crypto.createHmac("sha256", key[GUARD.key]).update(challenge).digest("hex"));
- expect(proof.pid).toBe(c.pid);
+ expect([proof.pid, proof.ppid]).toContain(c.pid);
expect((await raw(port, GUARD.hello, { Host: host })).status).toBe(403);
expect((await raw(port, GUARD.hello, { Host: `evil.example:${port}`, [GUARD.challenge]: challenge })).status).toBe(403);
// The live socket: only with the key.
@@ -159,6 +180,100 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()
});
});
+describe.skipIf(!venv)("the guard started through a venv's Python", () => {
+ it("starts and proves itself, though the venv's python.exe may start the real Python as a process of its own", async () => {
+ const comfyDir = tempDir("fuobe-guard-venv-comfy-");
+ const workDir = tempDir("fuobe-guard-venv-work-");
+ fs.writeFileSync(path.join(comfyDir, "main.py"), STAND_IN_MAIN);
+ const c = new OwnComfy({ comfyDir, workDir, python: venv, modelDirs: [] });
+ started.push(c);
+ await c.start();
+ expect(c.ready).toBe(true);
+ const host = `127.0.0.1:${c.port}`;
+ const hello = JSON.parse((await raw(c.port!, GUARD.hello, { Host: host, [GUARD.challenge]: "ab".repeat(16) })).body) as { pid: number; ppid: number };
+ expect([hello.pid, hello.ppid]).toContain(c.pid);
+ expect((await c.fetch(`${c.base}/system_stats`)).status).toBe(200);
+ expect((await raw(c.port!, "/system_stats", { Host: host })).status).toBe(403);
+ });
+});
+
+describe("Python's flags for the guard", () => {
+ it("are isolated mode, with UTF-8 mode kept as PYTHONUTF8 asks", () => {
+ expect(guardFlags({})).toEqual(["-I"]);
+ expect(guardFlags({ PYTHONUTF8: "1" })).toEqual(["-I", "-X", "utf8=1"]);
+ expect(guardFlags({ PYTHONUTF8: "0" })).toEqual(["-I", "-X", "utf8=0"]);
+ expect(guardFlags({ PYTHONUTF8: "yes" })).toEqual(["-I"]);
+ });
+});
+
+describe("requests to its own ComfyUI", () => {
+ const fakeCommand = () => [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--worker-guard", "1"];
+
+ it("go only to the process it started: before the first start and after a stop, nothing is sent to the old port", async () => {
+ // Another program on the port an older setup pinned (and on the port its last ComfyUI had).
+ const hits: string[] = [];
+ const other = http.createServer((q, s) => {
+ hits.push(`${q.method} ${q.url}`);
+ s.end("{}");
+ });
+ await new Promise<void>((r) => other.listen(0, "127.0.0.1", () => r()));
+ const otherPort = (other.address() as { port: number }).port;
+ try {
+ const workDir = tempDir("fuobe-guard-oldport-");
+ const c = new OwnComfy({ workDir, comfyDir: workDir, port: otherPort, comfyCommand: fakeCommand(), comfyGuard: true });
+ expect(c.base).toBe("http://127.0.0.1:0");
+ await expect(c.fetch(`http://127.0.0.1:${otherPort}/queue`, { method: "POST", body: "{}" })).rejects.toThrow(/isn't running/);
+ await c.free();
+ await c.clear();
+ expect(await c.vramMb()).toBeNull();
+ expect(hits).toEqual([]);
+ // Its own start on a port of its own, then a stop: the port is forgotten.
+ const d = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true });
+ started.push(d);
+ await d.start();
+ expect((await d.fetch(`${d.base}/system_stats`)).status).toBe(200);
+ await d.stop();
+ expect(d.port).toBeNull();
+ await expect(d.fetch(`http://127.0.0.1:${otherPort}/interrupt`, { method: "POST", body: "{}" })).rejects.toThrow(/isn't running/);
+ expect(hits).toEqual([]);
+ } finally {
+ other.close();
+ }
+ });
+
+ it("give up on a ComfyUI that takes the connection and never answers, without cutting a long answer short", async () => {
+ const dir = tempDir("fuobe-guard-silent-");
+ // Proves itself, then holds every other request open without an answer, except /slow, which answers at once and
+ // sends its body slowly.
+ fs.writeFileSync(
+ path.join(dir, "silent.mjs"),
+ `import http from "node:http"; import crypto from "node:crypto"; const key = process.env.${GUARD.env}; const port = Number(process.argv[2]);
+http.createServer((q, s) => {
+ if (q.url.startsWith("${GUARD.hello}")) { s.writeHead(200, { "content-type": "application/json" });
+ return s.end(JSON.stringify({ proof: crypto.createHmac("sha256", key).update(String(q.headers["${GUARD.challenge.toLowerCase()}"])).digest("hex"), pid: process.pid })); }
+ if (q.headers["${GUARD.key.toLowerCase()}"] !== key) { s.writeHead(403); return s.end(); }
+ if (q.url === "/system_stats" && !globalThis.ready) { globalThis.ready = true; s.writeHead(200, { "content-type": "application/json" }); return s.end("{}"); }
+ if (q.url === "/slow") { s.writeHead(200); let i = 0; const t = setInterval(() => { s.write("x"); if (++i === 6) { clearInterval(t); s.end(); } }, 100); return; }
+}).listen(port, "127.0.0.1");`,
+ );
+ const c = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: [process.execPath, path.join(dir, "silent.mjs"), "{port}"], comfyGuard: true });
+ started.push(c);
+ await c.start();
+ // The two requests the worker's main loop waits for: each gives up within REQUEST_MS.loop.
+ const t0 = Date.now();
+ expect(await c.vramMb()).toBeNull();
+ expect(Date.now() - t0).toBeLessThan(REQUEST_MS.loop + 3_000);
+ const tFree = Date.now();
+ await c.free();
+ expect(Date.now() - tFree).toBeLessThan(REQUEST_MS.loop + 3_000);
+ const t1 = Date.now();
+ await expect(c.fetch(`${c.base}/queue`, {}, 300)).rejects.toThrow();
+ expect(Date.now() - t1).toBeLessThan(3_000);
+ // The wait is for the answer to begin: a body that takes longer than that still arrives whole.
+ expect(await (await c.fetch(`${c.base}/slow`, {}, 300)).text()).toBe("xxxxxx");
+ });
+});
+
describe("the guard as the worker checks it", () => {
const fakeCommand = (more: string[] = []) => [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--worker-guard", "1", ...more];
@@ -232,6 +347,26 @@ http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/js
other.kill();
}
});
+
+ it("leaves alone a ComfyUI whose worker still runs (another worker on the same folder), and its pid file", async () => {
+ const workDir = tempDir("fuobe-guard-leftover-");
+ const alive = new Set(["A"]);
+ const workerLives = async (rec: { id: string }) => alive.has(rec.id);
+ const a = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true }, { owner: { pid: process.pid, id: "A", script: "" }, workerLives });
+ started.push(a);
+ await a.start();
+ expect(JSON.parse(fs.readFileSync(a.pidFile, "utf8")).worker).toEqual({ pid: process.pid, id: "A", script: "" });
+ const b = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true }, { owner: { pid: process.pid, id: "B", script: "" }, workerLives });
+ expect(await b.stopLeftover()).toBe(false);
+ expect(a.alive()).toBe(true);
+ expect(fs.existsSync(a.pidFile)).toBe(true);
+ // Its worker stopped (without stopping it): now it is a leftover.
+ alive.delete("A");
+ const pid = a.pid!;
+ expect(await b.stopLeftover()).toBe(true);
+ await new Promise((r) => setTimeout(r, 500));
+ expect(() => process.kill(pid, 0)).toThrow();
+ });
});
describe("its start, its restarts and its log", () => {
diff --git a/tests/worker-parts.test.ts b/tests/worker-parts.test.ts
index 3e75dd10..f558deef 100644
--- a/tests/worker-parts.test.ts
+++ b/tests/worker-parts.test.ts
@@ -3,13 +3,21 @@
* the PC awake while it works (awake.mjs), how it makes clips and sound again (media.mjs), and the studio's address.
* It also covers the stop signals the command line ends on (bin/lib/signals.mjs).
*/
+import { spawn, spawnSync } from "node:child_process";
import { EventEmitter } from "node:events";
+import fs from "node:fs";
+import path from "node:path";
import { describe, expect, it } from "vitest";
import { helperCommand, StayAwake } from "../bin/lib/worker/awake.mjs";
-import { encodeArgs, mediaKind } from "../bin/lib/worker/media.mjs";
+import { encodeArgs, FIT, INPUT_FORMATS, MEDIA_LIMITS, mediaKind, outputCap, reencode } from "../bin/lib/worker/media.mjs";
import { RETRY, retrying } from "../bin/lib/worker/retry.mjs";
-import { siteProblem } from "../bin/lib/worker/run.mjs";
+import { ffmpegOf } from "../bin/lib/worker/config.mjs";
+import { takeLock, workerLives, WorkerRunning } from "../bin/lib/worker/lock.mjs";
+import { privateHost, siteProblem, withoutOldPort } from "../bin/lib/worker/run.mjs";
import { onSignals, STOP_SIGNALS } from "../bin/lib/signals.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+const hasFfmpeg = spawnSync("ffmpeg", ["-hide_banner", "-version"]).status === 0;
/** A clock that moves only when the policy sleeps. */
function clock() {
@@ -163,11 +171,90 @@ describe("clips and sound, made again", () => {
expect(mediaKind({ name: "fuobe_bbbbbbbbbbbb.bin", contentType: "image/png" }, graph)).toBe("audio");
});
+ it("reads the file only as a local file in a plain container format, and writes at most an hour, 4096 pixels and a size cap", () => {
+ for (const args of [encodeArgs("video", "fuobe_a.mp4", "in", "out", 1234), encodeArgs("video", "fuobe_a.gif", "in", "out", 1234), encodeArgs("audio", "fuobe_a.wav", "in", "out", 1234)]) {
+ const at = (flag: string) => args[args.indexOf(flag) + 1];
+ // Before the input, so they apply to it: only the file protocol, only these readers.
+ expect(args.indexOf("-protocol_whitelist")).toBeLessThan(args.indexOf("-i"));
+ expect(args.indexOf("-format_whitelist")).toBeLessThan(args.indexOf("-i"));
+ expect(at("-protocol_whitelist")).toBe("file");
+ expect(at("-format_whitelist").split(",")).toEqual(INPUT_FORMATS);
+ expect(at("-i")).toBe("file:in");
+ expect(args.at(-1)).toBe("file:out");
+ expect(at("-t")).toBe(String(MEDIA_LIMITS.maxSeconds));
+ expect(at("-fs")).toBe("1234");
+ }
+ // No playlist, list, reference or image-sequence reader.
+ for (const reader of ["hls", "concat", "image2", "tee", "subfile", "data", "lavfi", "rtsp", "http"]) expect(INPUT_FORMATS).not.toContain(reader);
+ // Pictures bigger than 4096 on the long side are made smaller, keeping the shape.
+ expect(encodeArgs("video", "fuobe_a.mp4", "in", "out")).toContain(FIT);
+ expect(encodeArgs("video", "fuobe_a.gif", "in", "out").find((a) => a.includes("palettegen"))).toContain(FIT);
+ expect(FIT).toContain("4096");
+ // The size cap grows with the input, within its bounds.
+ expect(outputCap(1)).toBe(MEDIA_LIMITS.minBytes);
+ expect(outputCap(100 * 2 ** 20)).toBe(800 * 2 ** 20);
+ expect(outputCap(1e12)).toBe(MEDIA_LIMITS.maxBytes);
+ });
+
+ it("refuses what ffmpeg made at or over the size cap (ffmpeg stops writing there, so the file is cut short)", async () => {
+ const dir = tempDir("fuobe-worker-media-");
+ const spawnFn = (_bin: string, args: string[]) => {
+ const child = new EventEmitter() as EventEmitter & { pid: number; kill: () => void };
+ child.pid = 0;
+ child.kill = () => {};
+ const out = args.at(-1)!.replace(/^file:/, "");
+ const size = Number(args[args.indexOf("-fs") + 1]);
+ setTimeout(() => {
+ fs.writeFileSync(out, Buffer.alloc(out.endsWith("big.part") ? size + 10 : 10));
+ child.emit("exit", 0);
+ }, 5);
+ return child;
+ };
+ const src = path.join(dir, "in.mp4");
+ fs.writeFileSync(src, Buffer.alloc(100));
+ expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "a.mp4", src, dst: path.join(dir, "ok.part"), capBytes: 1000, spawnFn: spawnFn as never })).toBe(true);
+ expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "a.mp4", src, dst: path.join(dir, "big.part"), capBytes: 1000, spawnFn: spawnFn as never })).toBe(false);
+ });
+
+ it.runIf(hasFfmpeg)("ffmpeg refuses a playlist that names another file on this PC, and makes a plain clip again", async () => {
+ const dir = tempDir("fuobe-worker-playlist-");
+ const clip = path.join(dir, "clip.mp4");
+ const made = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", clip]);
+ expect(made.status).toBe(0);
+ // A "clip" that is a playlist naming that file (or any file this PC's user can read): without the rules, ffmpeg
+ // would open it and copy what it holds into the clip made again.
+ const playlist = path.join(dir, "fuobe_aaaaaaaaaaaa.m3u8");
+ fs.writeFileSync(playlist, `#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\nfile:${clip}\n#EXT-X-ENDLIST\n`);
+ expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "fuobe_aaaaaaaaaaaa.mp4", src: playlist, dst: path.join(dir, "out1.part") })).toBe(false);
+ expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "fuobe_aaaaaaaaaaaa.mp4", src: clip, dst: path.join(dir, "out2.part") })).toBe(true);
+ expect(fs.readFileSync(path.join(dir, "out2.part")).subarray(4, 8).toString("latin1")).toBe("ftyp");
+ });
+
+ it.runIf(hasFfmpeg)("ffmpeg refuses a DASH, HLS or ffconcat list that names another file, even under a clip's name", async () => {
+ const dir = tempDir("fuobe-worker-lists-");
+ const clip = path.join(dir, "elsewhere.mp4");
+ const made = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", clip]);
+ expect(made.status).toBe(0);
+ const url = `file:${clip.replaceAll("\\", "/")}`;
+ const lists = {
+ dash: `<?xml version="1.0"?>\n<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT1S" minBufferTime="PT1S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011"><Period><AdaptationSet mimeType="video/mp4"><Representation id="1" bandwidth="100000" codecs="avc1.42c00a" width="64" height="48"><BaseURL>${url}</BaseURL></Representation></AdaptationSet></Period></MPD>\n`,
+ hls: `#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\n${url}\n#EXT-X-ENDLIST\n`,
+ ffconcat: `ffconcat version 1.0\nfile '${clip.replaceAll("\\", "/")}'\n`,
+ };
+ for (const [kind, text] of Object.entries(lists)) {
+ // Under the name a clip has in the worker's cache (it reads the file by its contents, not its name).
+ const src = path.join(dir, `${kind}.mp4`);
+ fs.writeFileSync(src, text);
+ const dst = path.join(dir, `${kind}-out.part`);
+ expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "fuobe_aaaaaaaaaaaa.mp4", src, dst }), kind).toBe(false);
+ }
+ });
+
it("keeps one picture and one sound stream and nothing else of the file, in the format its name says", () => {
const mp4 = encodeArgs("video", "fuobe_a.mp4", "in", "out");
- expect(mp4.slice(0, 7)).toEqual(["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", "in"]);
+ expect(mp4.slice(0, 5)).toEqual(["-hide_banner", "-nostdin", "-loglevel", "error", "-y"]);
expect(mp4).toEqual(expect.arrayContaining(["-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn", "-map", "0:v:0", "0:a:0?", "libx264", "aac", "mp4"]));
- expect(mp4.at(-1)).toBe("out");
+ expect(mp4.at(-1)).toBe("file:out");
expect(encodeArgs("video", "fuobe_a.webm", "in", "out")).toEqual(expect.arrayContaining(["libvpx-vp9", "libopus", "webm"]));
expect(encodeArgs("video", "fuobe_a.xyz", "in", "out")).toEqual(expect.arrayContaining(["libx264", "mp4"]));
const wav = encodeArgs("audio", "fuobe_a.wav", "in", "out");
@@ -177,6 +264,17 @@ describe("clips and sound, made again", () => {
});
});
+describe("an older setup's port", () => {
+ it("8190, which an older setup saved for every worker, is no pin: its ComfyUI takes a free port at each start", () => {
+ const old = { site: "https://studio.example", port: 8190 };
+ expect(withoutOldPort(old)).toEqual({ site: "https://studio.example", port: null });
+ const pinned = { site: "https://studio.example", port: 41_000 };
+ expect(withoutOldPort(pinned)).toBe(pinned);
+ const none = { site: "https://studio.example", port: null };
+ expect(withoutOldPort(none)).toBe(none);
+ });
+});
+
describe("the studio's address", () => {
it("is https, or this PC itself", () => {
expect(siteProblem("https://studio.example")).toBeNull();
@@ -187,6 +285,77 @@ describe("the studio's address", () => {
expect(siteProblem("ftp://studio.example")).toMatch(/https/);
expect(siteProblem("studio")).toMatch(/web address/);
});
+
+ it("may be http on a private network only when worker.json allows it, and never a public one", () => {
+ const allow = { allowHttpSite: true };
+ for (const site of ["http://192.168.1.10:3000", "http://10.0.0.2", "http://172.20.1.1:8080", "http://[fd12:3456::1]:3000"]) {
+ expect(siteProblem(site), site).toMatch(/allowHttpSite/);
+ expect(siteProblem(site, allow), site).toBeNull();
+ }
+ for (const site of ["http://studio.example", "http://8.8.8.8", "http://172.32.0.1", "http://192.169.0.1", "http://studio.lan"]) expect(siteProblem(site, allow), site).toMatch(/https/);
+ expect(privateHost("192.168.300.1")).toBe(false);
+ expect(siteProblem("https://studio.example", allow)).toBeNull();
+ });
+});
+
+describe("ffmpeg", () => {
+ it("is worker.json's, else the PATH's when worker.json names none; null or - means pictures only", () => {
+ expect(ffmpegOf({})).toBe("ffmpeg");
+ expect(ffmpegOf({ ffmpeg: "C:\\ffmpeg\\bin\\ffmpeg.exe" })).toBe("C:\\ffmpeg\\bin\\ffmpeg.exe");
+ expect(ffmpegOf({ ffmpeg: null })).toBeNull();
+ expect(ffmpegOf({ ffmpeg: "-" })).toBeNull();
+ expect(ffmpegOf({ ffmpeg: "" })).toBeNull();
+ });
+});
+
+describe("one worker at a time on a worker folder", () => {
+ const lockFile = (dir: string) => path.join(dir, "worker.lock");
+ const exitedPid = () => {
+ const r = spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"], { encoding: "utf8" });
+ return Number(r.stdout);
+ };
+
+ it("a second lock on the same folder is refused while the first is held, and taken once it is let go", async () => {
+ const dir = tempDir("fuobe-worker-lock-");
+ const first = await takeLock(dir);
+ expect(JSON.parse(fs.readFileSync(lockFile(dir), "utf8"))).toMatchObject({ pid: process.pid, id: first.owner.id });
+ await expect(takeLock(dir)).rejects.toBeInstanceOf(WorkerRunning);
+ await expect(takeLock(dir)).rejects.toThrow(/Another worker is running on this worker folder/);
+ first.release();
+ expect(fs.existsSync(lockFile(dir))).toBe(false);
+ const second = await takeLock(dir);
+ // A late release of the first lock never lets go of the second.
+ first.release();
+ expect(JSON.parse(fs.readFileSync(lockFile(dir), "utf8")).id).toBe(second.owner.id);
+ second.release();
+ });
+
+ it("takes over a lock whose worker has stopped, or whose process id now belongs to another program", async () => {
+ const dir = tempDir("fuobe-worker-lock-");
+ // Its process is gone.
+ fs.writeFileSync(lockFile(dir), JSON.stringify({ pid: exitedPid(), id: "gone", script: "/x/bin/fuobe.mjs" }));
+ (await takeLock(dir)).release();
+ // Half written (and not just now).
+ fs.writeFileSync(lockFile(dir), "{");
+ fs.utimesSync(lockFile(dir), new Date(Date.now() - 60_000), new Date(Date.now() - 60_000));
+ (await takeLock(dir)).release();
+ // Another process runs under that id.
+ const other = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
+ try {
+ fs.writeFileSync(lockFile(dir), JSON.stringify({ pid: other.pid, id: "x", script: "/x/bin/fuobe.mjs" }));
+ (await takeLock(dir, { commandLineOf: async () => "notepad.exe C:\\notes.txt" })).release();
+ // A worker runs under that id (by its command line, or the script it named): refused.
+ for (const line of ['"C:\\Program Files\\nodejs\\node.exe" "C:\\fuobe\\bin\\fuobe.mjs" worker run', "node /x/bin/fuobe.mjs worker run", "node /x/bin/fuobe.mjs"]) {
+ fs.writeFileSync(lockFile(dir), JSON.stringify({ pid: other.pid, id: "x", script: "/x/bin/fuobe.mjs" }));
+ await expect(takeLock(dir, { commandLineOf: async () => line }), line).rejects.toBeInstanceOf(WorkerRunning);
+ }
+ // Its command line can't be read (another user's process): it may be a worker, so refused.
+ await expect(takeLock(dir, { commandLineOf: async () => null })).rejects.toBeInstanceOf(WorkerRunning);
+ expect(await workerLives({ pid: other.pid, id: "x", script: "" }, { commandLineOf: async () => "node other.js" })).toBe(false);
+ } finally {
+ other.kill();
+ }
+ });
});
describe("stop signals", () => {
diff --git a/tests/worker-pause-choice.test.ts b/tests/worker-pause-choice.test.ts
index 61e3a36f..ca5e3ce0 100644
--- a/tests/worker-pause-choice.test.ts
+++ b/tests/worker-pause-choice.test.ts
@@ -67,6 +67,28 @@ describe("me first", () => {
const gpu = { readGpu: async () => ({ usedMb: 9700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[4242, 9000], [77, 650]])), readListeners: async () => LISTING };
expect(await worker(["baseline"], { ...a.io, gpu })).toBe(0);
expect(JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8"))).toEqual({ site: "https://studio.example", workDir: "D:\\w", desktopBaselineMb: 700 });
+ expect(a.out.join("")).toContain("Counted: 700 MB, mostly dwm (process 77, 650 MB)");
expect(await worker(["baseline"], { ...a.io, gpu: { ...gpu, readCounters: async () => null } })).toBe(1);
});
+
+ it("baseline leaves out the running worker's own ComfyUI, and saves at most its cap with a warning", async () => {
+ const home = tempDir("fuobe-worker-home-");
+ const workDir = tempDir("fuobe-worker-work-");
+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify({ site: "https://studio.example", workDir }));
+ // The worker runs: its own ComfyUI (pid 5000 on port 31400) holds 18 GB.
+ fs.writeFileSync(path.join(workDir, "comfyui.pid"), JSON.stringify({ pid: 5000, port: 31_400 }));
+ const listing = { listeners: [...LISTING.listeners, { port: 31_400, pid: 5000 }], names: { ...LISTING.names, "5000": "python", "6000": "game" } };
+ const a = io([], home);
+ const gpu = { readGpu: async () => ({ usedMb: 18_650, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[5000, 18_000], [77, 650]])), readListeners: async () => listing };
+ expect(await worker(["baseline"], { ...a.io, gpu })).toBe(0);
+ expect(JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8")).desktopBaselineMb).toBe(650);
+ expect(a.out.join("")).toContain("Not counted: the worker's own ComfyUI (18000 MB)");
+ // A game left open: the cap, and the game named.
+ const b = io([], home);
+ const game = { ...gpu, readGpu: async () => ({ usedMb: 30_650, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[5000, 18_000], [6000, 12_000], [77, 650]])) };
+ expect(await worker(["baseline"], { ...b.io, gpu: game })).toBe(0);
+ expect(JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8")).desktopBaselineMb).toBe(4096);
+ expect(b.out.join("")).toMatch(/game \(process 6000, 12000 MB\)/);
+ expect(b.out.join("")).toMatch(/another GPU program was open/);
+ });
});
diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.ts
index 32910050..ee30ebcb 100644
--- a/tests/worker-program.test.ts
+++ b/tests/worker-program.test.ts
@@ -6,6 +6,7 @@ import { GpuWatch, othersOf, parseApps, parseGpu } from "../bin/lib/worker/gpu.m
import { cleanJob, vetGraph } from "../bin/lib/worker/checks.mjs";
import { comfyArgs, OwnComfy, PortBusy, portFree } from "../bin/lib/worker/comfy.mjs";
import { parseFor, syncedFolder } from "../bin/lib/worker/config.mjs";
+import { worker } from "../bin/lib/worker/index.mjs";
import { localPause } from "../bin/lib/worker/run.mjs";
import { inventoryHash as workerHash } from "../bin/lib/worker/inventory.mjs";
import { tempDir } from "./helpers/temp-dir";
@@ -143,6 +144,24 @@ describe("cleanup (check 13) and setup", () => {
expect(syncedFolder("D:\\FuobeWorker")).toBe(false);
});
+ it("setup again keeps a port pinned by hand and the rest of worker.json, drops the older setups' 8190, and adds no defaults", async () => {
+ const setupWith = async (saved: Record<string, unknown>) => {
+ const home = tempDir("fuobe-worker-setup-home-");
+ const comfyDir = tempDir("fuobe-worker-setup-comfy-");
+ fs.writeFileSync(path.join(comfyDir, "main.py"), "");
+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify(saved));
+ const answers = ["https://studio.example", `fuobe_wkr_${"a".repeat(43)}`, comfyDir, path.join(comfyDir, "models"), path.join(tempDir("fuobe-worker-setup-work-"), "w"), "-", "n"];
+ const io = { env: { FUOBE_WORKER_HOME: home }, home, stdout: { write: () => {} }, stderr: { write: () => {} }, ask: async () => answers.shift() ?? "" };
+ expect(await worker(["setup"], io)).toBe(0);
+ return JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8")) as Record<string, unknown>;
+ };
+ const kept = await setupWith({ port: 41_000, stallMin: 7, yieldFolder: "C:/turns" });
+ expect(kept).toMatchObject({ port: 41_000, stallMin: 7, yieldFolder: "C:/turns", site: "https://studio.example", ffmpeg: null, autoResume: false });
+ for (const key of ["hungMin", "busyVramMb", "localComfyPorts", "allowHttpSite"]) expect(kept).not.toHaveProperty(key);
+ expect((await setupWith({ port: 8190 })).port).toBeNull();
+ expect((await setupWith({})).port).toBeNull();
+ });
+
it("hashes its inventory the way the studio does", async () => {
const { inventoryHash } = await import("@/server/computer/pool");
const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index 551af51e..aa490f6c 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -137,18 +137,25 @@ interface Pc {
comfyDir: string;
countFile: string;
logs: string[];
+ /** When each log line was written. */
+ logAt: number[];
awake: boolean[];
}
function pc(): Pc {
const base = tempDir("fuobe-worker-pc-");
- const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), logs: [], awake: [] };
+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), logs: [], logAt: [], awake: [] };
for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });
return p;
}
/** Start `fuobe worker run` in this process (its ComfyUI a stand-in process of its own). */
-function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[] } = {}) {
+function start(
+ w: W,
+ s: Studio,
+ p: Pc,
+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number } = {},
+) {
const ctrl = new AbortController();
const cfg = {
site: SITE,
@@ -165,6 +172,7 @@ function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; fai
stallMin: o.stallMin ?? 10,
hungMin: o.hungMin ?? 3,
ffmpeg: o.ffmpeg ?? null,
+ ...(o.port && { port: o.port }),
};
const done = runWorker(cfg, {
fetch: router(w, s),
@@ -175,11 +183,15 @@ function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; fai
rules: RULES,
pins: o.pins ?? {},
allowed: ALLOWED,
- readGpu: async () => null,
+ readGpu: o.readGpu ?? (async () => null),
+ ...(o.gpuEveryMs && { gpuEveryMs: o.gpuEveryMs }),
...(o.ffmpeg === undefined || o.ffmpeg === null ? { ffmpegVersion: async () => null } : {}),
awake: { set: (on: boolean) => void (p.awake.at(-1) !== on && p.awake.push(on)) },
sleep: (ms: number) => sleep(Math.min(ms, 50)),
- log: (line: string) => void p.logs.push(line),
+ log: (line: string) => {
+ p.logs.push(line);
+ p.logAt.push(Date.now());
+ },
...(o.rescanMs && { rescanMs: o.rescanMs }),
});
const r = { ctrl, done };
@@ -223,6 +235,42 @@ function raw(port: number, p: string, headers: Record<string, string>): Promise<
}
describe("a worker keeps its jobs going", () => {
+ it("a second worker on the same worker folder refuses to start, and leaves the first one's ComfyUI, folders and job alone", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ start(w, s, p, { steps: 40, stepMs: 150 });
+ const comfy = await until(async () => {
+ const c = comfyOf(p);
+ return c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2 ? c : null;
+ });
+ // Files of the first one's job in its folders now.
+ fs.writeFileSync(path.join(p.workDir, "input", "in-use.png"), FAKE_PNG);
+ fs.writeFileSync(path.join(p.workDir, "temp", "in-use.txt"), "the first worker's");
+ const logs = p.logs.length;
+ // The same worker.json run again (by hand, while the scheduled one runs).
+ const second = start(w, s, p);
+ await expect(second.done).rejects.toThrow(/Another worker is running on this worker folder/);
+ // Nothing of the first one's was touched: its ComfyUI runs, its folders and its job are as they were.
+ expect(comfyOf(p)).toEqual(comfy);
+ expect(() => process.kill(comfy.pid, 0)).not.toThrow();
+ expect(fs.existsSync(path.join(p.workDir, "input", "in-use.png"))).toBe(true);
+ expect(fs.existsSync(path.join(p.workDir, "temp", "in-use.txt"))).toBe(true);
+ expect(p.logs.slice(logs).some((l) => /Stopped a ComfyUI|Starting its own ComfyUI/.test(l))).toBe(false);
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(prompts(p)).toBe(1);
+ expect(fs.existsSync(path.join(p.workDir, "crashes.json")) ? Object.keys(JSON.parse(fs.readFileSync(path.join(p.workDir, "crashes.json"), "utf8"))) : []).toEqual([]);
+ // Once the first one has stopped, a worker on that folder starts as usual.
+ running[0].ctrl.abort();
+ await running[0].done;
+ const third = start(w, s, p);
+ await until(() => p.logs.slice(logs).some((l) => /Starting its own ComfyUI/.test(l)));
+ third.ctrl.abort();
+ expect(await third.done).toBe("aborted");
+ });
+
it("its ComfyUI is killed at 50%: the output arrives (and its guard refuses another Host and a missing key)", async () => {
const w = addWorker();
const s = studio();
@@ -265,13 +313,22 @@ describe("a worker keeps its jobs going", () => {
expect(["input", "output", "temp"].flatMap((d) => fs.readdirSync(path.join(p.workDir, d)))).toEqual([]);
expect(comfyOf(p)).toBeNull();
expect(p.awake.at(-1)).toBe(false);
- s.intercept = null;
+ // The next start sends the kept results before it starts its ComfyUI (which can take minutes on a real PC).
+ let uploadAt = 0;
+ s.intercept = (q, init) => {
+ if (q.includes("/outputs/") && init.method === "PUT") uploadAt ||= Date.now();
+ return undefined;
+ };
+ const before = p.logs.length;
start(w, s, p);
const t = await ended(id);
expect(t.state).toBe("done");
expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
expect(prompts(p)).toBe(1);
expect(new Hold(path.join(p.workDir, "hold")).ids()).toEqual([]);
+ const startedAt = await until(() => p.logs.slice(before).some((l) => /Starting its own ComfyUI/.test(l)) && p.logAt[p.logs.findIndex((l, i) => i >= before && /Starting its own ComfyUI/.test(l))]);
+ expect(uploadAt).toBeGreaterThan(0);
+ expect(uploadAt).toBeLessThanOrEqual(startedAt);
});
it("stopped before the studio heard it finished: the next start, paused here, sends the kept results without its ComfyUI", async () => {
@@ -299,6 +356,45 @@ describe("a worker keeps its jobs going", () => {
expect(tasks.execOf(t)?.ms).toBeTypeOf("number");
});
+ it("stopped after keeping its results, restarted under a pause-now (the shortcut's pause): the output arrives, with one prompt", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ const first = start(w, s, p);
+ s.intercept = (q, init) => {
+ if (!q.endsWith("/report") || JSON.parse(String(init.body)).event !== "finished") return undefined;
+ first.ctrl.abort();
+ return new Response("stopping", { status: 503 });
+ };
+ await first.done;
+ expect(state(id).state).toBe("running");
+ expect(new Hold(path.join(p.workDir, "hold")).ids()).toEqual([id]);
+ s.intercept = null;
+ // Another program now listens on a port the worker.json pins: nothing at all may reach it.
+ const hits: string[] = [];
+ const other = http.createServer((q, res) => {
+ hits.push(`${q.method} ${q.url}`);
+ res.end("{}");
+ });
+ await new Promise<void>((r) => other.listen(0, "127.0.0.1", () => r()));
+ try {
+ // Paused now, as the pause shortcut does: the studio sends a paused worker's jobs back, but not one whose results
+ // it keeps; those go up with no ComfyUI.
+ fs.writeFileSync(path.join(p.home, "control.json"), JSON.stringify({ paused: true, now: true }));
+ start(w, s, p, { port: (other.address() as { port: number }).port });
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
+ expect(prompts(p)).toBe(1);
+ expect(comfyOf(p)).toBeNull();
+ expect(hits).toEqual([]);
+ expect(new Hold(path.join(p.workDir, "hold")).ids()).toEqual([]);
+ } finally {
+ other.close();
+ }
+ });
+
it("its ComfyUI hangs: the job is given back within the stall limit, then runs to the end", async () => {
const w = addWorker();
const s = studio();
@@ -359,11 +455,53 @@ http.createServer((q, s) => {
s.writeHead(200, { "content-type": "application/json" }); s.end(JSON.stringify({ system: {}, devices: [] }));
}).listen(port, "127.0.0.1");`,
);
- start(w, s, p, { command: [process.execPath, hung, "{port}"], hungMin: 0.05 });
+ // A real GPU reading every 200 ms, so the main loop also asks its ComfyUI for its own memory each time: a ComfyUI
+ // that takes the connection and never answers must not hold the loop (and its beats) up.
+ const t0 = Date.now();
+ start(w, s, p, { command: [process.execPath, hung, "{port}"], hungMin: 0.05, readGpu: async () => ({ usedMb: 500, tempC: 40, apps: [] }), gpuEveryMs: 200 });
await until(() => p.logs.some((l) => /stopped answering/.test(l)), 60_000);
+ expect(Date.now() - t0).toBeLessThan(30_000);
+ const beats = s.calls.filter((c) => c.endsWith("/beat")).length;
+ await sleep(12_000);
+ expect(s.calls.filter((c) => c.endsWith("/beat")).length).toBeGreaterThan(beats);
await until(() => p.logs.filter((l) => /Starting its own ComfyUI/.test(l)).length >= 2, 30_000);
});
+ it("its ComfyUI takes a long time to start: the worker goes on beating meanwhile", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const slow = path.join(p.comfyDir, "slow.mjs");
+ // Proves itself at once, but answers "not ready" (503) for 14 seconds, as a ComfyUI that loads many node packs does.
+ fs.writeFileSync(
+ slow,
+ `import http from "node:http"; import crypto from "node:crypto";
+const key = process.env.FUOBE_WORKER_GUARD_KEY; const port = Number(process.argv[2]); const readyAt = Date.now() + 14000;
+http.createServer((q, s) => {
+ if (q.headers.host !== "127.0.0.1:" + port) { s.writeHead(403); return s.end(); }
+ if (q.url.startsWith("/fuobe-worker/hello") && !q.headers["x-fuobe-worker-key"]) {
+ s.writeHead(200, { "content-type": "application/json" });
+ return s.end(JSON.stringify({ proof: crypto.createHmac("sha256", key).update(String(q.headers["x-fuobe-worker-challenge"])).digest("hex"), pid: process.pid }));
+ }
+ if (q.headers["x-fuobe-worker-key"] !== key) { s.writeHead(403); return s.end(); }
+ if (Date.now() < readyAt) { s.writeHead(503); return s.end(); }
+ s.writeHead(200, { "content-type": "application/json" }); s.end(JSON.stringify({ system: {}, devices: [] }));
+}).listen(port, "127.0.0.1");`,
+ );
+ const beatsAt: number[] = [];
+ s.intercept = (q) => {
+ if (q === "/api/gpu/computer/beat") beatsAt.push(Date.now());
+ return undefined;
+ };
+ start(w, s, p, { command: [process.execPath, slow, "{port}"] });
+ const at = (re: RegExp) => until(() => p.logs.some((l) => re.test(l)) && p.logAt[p.logs.findIndex((l) => re.test(l))], 60_000);
+ const startedAt = await at(/Starting its own ComfyUI/);
+ const readyAt = await at(/^Ready$/);
+ expect(readyAt - startedAt).toBeGreaterThan(10_000);
+ // Beats went on while it started (one every 10 s with no job).
+ expect(beatsAt.filter((b) => b > startedAt && b < readyAt).length).toBeGreaterThanOrEqual(1);
+ });
+
it("a ComfyUI that answers without its guard is stopped and not started again for an hour", async () => {
const w = addWorker();
const s = studio();
diff --git a/tests/worker-runner.test.ts b/tests/worker-runner.test.ts
index e6a9f6f4..6d05834e 100644
--- a/tests/worker-runner.test.ts
+++ b/tests/worker-runner.test.ts
@@ -67,7 +67,7 @@ function worker(): W {
}
function beat(w: W) {
- pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
}
let gens = 0;
@@ -119,13 +119,19 @@ const hooks = (o: Partial<WorkerHooks> = {}): WorkerHooks => ({
...o,
});
-function runner(s: ReturnType<typeof studio>, worker?: WorkerHooks) {
+function runner(s: ReturnType<typeof studio>, worker?: WorkerHooks, now?: () => number) {
return new ComputerRunner(
- { api: s.call, local: (url, init) => realFetch(url, init), socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => sleep(Math.min(ms, 30)), ...(worker && { worker }) },
+ { api: s.call, local: (url, init) => realFetch(url, init), socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => sleep(Math.min(ms, 30)), ...(worker && { worker }), ...(now && { now }) },
{ device: "worker", port: fake.port, clientId: "client-worker-01" },
);
}
+/** A clock on which each real millisecond is `x` of the runner's (600: a real second is ten minutes). */
+function fastClock(x: number) {
+ const start = Date.now();
+ return () => start + (Date.now() - start) * x;
+}
+
/** Claim the next job as a worker's runner does, and run it (or `edit` it first). */
async function claimAndRun(r: InstanceType<typeof ComputerRunner>, s: ReturnType<typeof studio>, edit?: (t: ClaimedTask) => ClaimedTask) {
if (!edit) return r.claimAndRun();
@@ -188,7 +194,8 @@ describe("a worker's runner", () => {
const s = studio(w);
fake.opts.failNext = "never";
const t0 = Date.now();
- await runner(s, hooks({ stallMs: 600 })).claimAndRun();
+ // The PC's own stall limit (600 ms here) wins over the claim's.
+ await runner(s, hooks({ stallLocalMs: 600 })).claimAndRun();
const took = Date.now() - t0;
expect(state(id)).toMatchObject({ state: "waiting", requeues: 1, worker_id: null });
expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "stalled" });
@@ -201,17 +208,88 @@ describe("a worker's runner", () => {
expect(state(id).state).toBe("done");
});
+ it("the stall limit comes with the claim (the studio's), over the worker's own default", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.failNext = "never";
+ let given: number | undefined;
+ // The worker's default is an hour; the claim's limit is the one obeyed (2 minutes here: a real 200 ms on this clock).
+ await claimAndRun(runner(s, hooks({ stallMs: 60 * 60_000 }), fastClock(600)), s, (t) => ((given = t.stallMs), { ...t, stallMs: 2 * 60_000 }));
+ expect(given).toBe(pool.STALL_MS);
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "stalled" });
+ });
+
it("a job past its run limit goes back to the line", async () => {
const w = worker();
const id = task();
const s = studio(w);
+ // About 20 minutes of running on the runner's clock, with an 11-minute limit.
fake.opts.steps = 40;
fake.opts.stepMs = 50;
- await claimAndRun(runner(s, hooks()), s, (t) => ({ ...t, runLimitMs: 500 }));
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 11 * 60_000 }));
expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "run-limit" });
});
+ it("a worker with no times for the lane runs a 20-minute first job to the end (the claim's limit is the run ceiling)", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ // About 20 minutes on the runner's clock (a cold model load and a long render), with the limit the studio gives.
+ fake.opts.steps = 40;
+ fake.opts.stepMs = 50;
+ let limit: number | undefined;
+ const clock = fastClock(600);
+ const t0 = clock();
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), clock), s, (t) => ((limit = t.runLimitMs), t));
+ expect(clock() - t0).toBeGreaterThan(19 * 60_000);
+ expect(limit).toBe(pool.RUN_CEILING_MS);
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("an older studio's 5-minute limit for a lane with no times isn't obeyed: the job runs to the end", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.steps = 40;
+ fake.opts.stepMs = 15;
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 5 * 60_000 }));
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("the run limit counts from when its ComfyUI starts the job, not while the job waits in ComfyUI's queue", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ // Another prompt holds its ComfyUI for about 10 minutes first; the job itself then runs about 3, under an 11-minute limit.
+ fake.opts.steps = 20;
+ fake.opts.stepMs = 15;
+ fake.foreign(1_000);
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 11 * 60_000 }));
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("after running out of memory, only the retry's own time is reported", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.failNext = "oom";
+ // The first try (which runs out of memory) takes as long as the retry would; only the retry's time counts.
+ fake.opts.steps = 10;
+ fake.opts.stepMs = 30;
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id).state).toBe("done");
+ const finished = s.reports.find((x) => x.event === "finished")!;
+ const entry = finished.entry as { status?: { messages?: [string, { timestamp?: number }][] } };
+ const stamps = (entry.status?.messages ?? []).map(([, d]) => d.timestamp).filter((x): x is number => typeof x === "number");
+ expect(finished.execMs).toBe(Math.max(...stamps) - Math.min(...stamps));
+ });
+
it("a job its ComfyUI stopped on twice fails in plain words; the worker goes on", async () => {
const w = worker();
const id = task();
@@ -382,4 +460,31 @@ describe("results kept until the studio has them", () => {
expect(() => hold.folder("../x")).toThrow();
expect(path.basename(hold.folder(t.id))).toBe(t.id);
});
+
+ it("lets go of kept results the studio never took after a day, and of a half-made copy that old", async () => {
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const hold = new Hold(holdDir);
+ const t = { id: "CCCCCCCCCCCCCCCC", promptId: "00000000-0000-4000-8000-000000000003" } as ClaimedTask;
+ await hold.keep(t, { kind: "finished", entries: [{ status: { status_str: "success", completed: true }, outputs: {} }] } as HeldResults, async () => new Response(FAKE_PNG));
+ fs.mkdirSync(path.join(holdDir, "DDDDDDDDDDDDDDDD"));
+ const day = 24 * 3_600_000;
+ expect(hold.expire(Date.now(), day)).toEqual([]);
+ expect(hold.ids()).toEqual([t.id]);
+ expect(hold.expire(Date.now() + day + 60_000, day).sort()).toEqual(["CCCCCCCCCCCCCCCC", "DDDDDDDDDDDDDDDD"]);
+ expect(fs.readdirSync(holdDir)).toEqual([]);
+ });
+
+ it("a claim with nothing for it says so with whether it was for kept results only, and the kept results stay", async () => {
+ const w = worker();
+ const s = studio(w);
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const hold = new Hold(holdDir);
+ const kept = { id: "EEEEEEEEEEEEEEEE", promptId: "00000000-0000-4000-8000-000000000004" } as ClaimedTask;
+ await hold.keep(kept, { kind: "finished", entries: [{ status: { status_str: "success", completed: true }, outputs: {} }] } as HeldResults, async () => new Response(FAKE_PNG));
+ const seen: [string | null, boolean][] = [];
+ const r = runner(s, hooks({ hold: hold as never, claimed: (t, o) => void seen.push([t?.id ?? null, o.onlyHeld]) }));
+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);
+ expect(seen).toEqual([[null, true]]);
+ expect(hold.ids()).toEqual([kept.id]);
+ });
});
diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.ts
index ef73d180..b76cd59b 100644
--- a/tests/worker-turns-run.test.ts
+++ b/tests/worker-turns-run.test.ts
@@ -67,7 +67,8 @@ function addWorker(): W {
}
let gens = 0;
-function addTask(): string {
+/** A person's run for the workers, or (`owner`) one of the owner's own, which no turn is asked for. */
+function addTask(o: { owner?: boolean } = {}): string {
const gid = `turns-gen-${++gens}`;
const now = Date.now();
db()
@@ -78,16 +79,17 @@ function addTask(): string {
principal: "owner",
generationId: gid,
graph: { "1": { class_type: "LoadImage", inputs: { image: input } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },
- pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
+ // A person's run (an account's): the studio counts it in the beat's claimableNow.
+ pool: { pools: ["pool"], ...(!o.owner && { account: "turns-account" }), rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
}).id;
}
/**
- * fetch for the worker: the studio's routes for SITE, its own ComfyUI for the rest. With `claimable`, the beat's answer
- * carries claimableNow (the jobs waiting for this worker's pool), as a studio that supports turns sends it.
+ * fetch for the worker: the studio's real routes for SITE (the beat's claimableNow is the studio's own), its own
+ * ComfyUI for the rest. With `older`, the beat's answer has no claimableNow, as from a studio that doesn't say.
*/
-function router(w: W, o: { claimable: boolean }) {
- // The test may switch the count on later (the same object).
+function router(w: W, o: { older: boolean }) {
+ // The test may switch `older` off later (the same object).
const api = apiAs(routes, null);
return async (url: string, init: RequestInit = {}) => {
if (!String(url).startsWith(SITE)) return realFetch(url, init);
@@ -96,10 +98,10 @@ function router(w: W, o: { claimable: boolean }) {
if (p === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: ["small"], workflows: ["wf-test"], missing: [] });
expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);
const res = await api(p, init);
- if (p !== "/api/gpu/computer/beat" || !o.claimable || !res.ok) return res;
- const body = await res.json();
- const n = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE state = 'waiting' AND INSTR(',' || pools || ',', ',pool,') > 0").get() as { n: number }).n;
- return Response.json({ ...body, claimableNow: n });
+ if (p !== "/api/gpu/computer/beat" || !o.older || !res.ok) return res;
+ const body = (await res.json()) as Record<string, unknown>;
+ delete body.claimableNow;
+ return Response.json(body);
};
}
@@ -172,7 +174,7 @@ afterEach(async () => {
}
});
-function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { claimable?: boolean; lockOwners?: string[]; studio?: { claimable: boolean } } = {}) {
+function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: string[]; studio?: { older: boolean } } = {}) {
const ctrl = new AbortController();
const cfg = {
site: SITE,
@@ -189,7 +191,7 @@ function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { claimable?: bo
gpuLockComfyOwners: o.lockOwners ?? [],
};
const done = runWorker(cfg, {
- fetch: router(w, o.studio ?? { claimable: o.claimable ?? true }),
+ fetch: router(w, o.studio ?? { older: false }),
home: p.home,
signal: ctrl.signal,
requirements: { folders: [], files: {}, packs: {}, workflows: {} },
@@ -288,18 +290,34 @@ describe("studio jobs first", () => {
const w = addWorker();
const p = pc();
addTask();
- const studio = { claimable: false };
+ const studio = { older: true };
start(w, p, fakeGpu(p, { workMb: 9000 }), { studio });
await until(() => workerRow(w).local_why?.startsWith("gpu-busy"));
expect(workerRow(w).local_why).toBe("gpu-busy:ComfyUI on port 8188");
expect(site(p)?.siteWaiting ?? 0).toBe(0);
// The studio starts to send the count: the pause ends with no cool-down, and a turn is asked for.
- studio.claimable = true;
+ studio.older = false;
await until(() => workerRow(w).local_why === "waiting-for-yield");
expect(site(p)?.siteWaiting).toBe(1);
expect(p.logs.some((l) => /no longer keeps it paused/.test(l))).toBe(true);
});
+ it("only the owner's own job waits: the studio counts none, so no turn is asked for and local ComfyUI work goes on", async () => {
+ const w = addWorker();
+ const p = pc();
+ const id = addTask({ owner: true });
+ start(w, p, fakeGpu(p, { workMb: 9000 }));
+ // The studio's real beat says 0 (not "unknown"): turns work, local ComfyUI work is no other program, and no
+ // turn begins for the owner's own job.
+ await until(() => comfyAnswers(p));
+ await sleep(2_000);
+ expect(site(p)?.siteWaiting ?? 0).toBe(0);
+ expect(workerRow(w).paused_local).toBe(0);
+ expect(workerRow(w).local_why).toBeNull();
+ expect(task(id).state).toBe("waiting");
+ expect(p.logs.some((l) => /make room|Another program/.test(l))).toBe(false);
+ });
+
it("me first: the pause shortcut during a turn writes siteWaiting 0 and keeps the job in line; a resume asks again", async () => {
const w = addWorker();
const p = pc();
diff --git a/tests/worker-turns.test.ts b/tests/worker-turns.test.ts
index a397171d..a3037b54 100644
--- a/tests/worker-turns.test.ts
+++ b/tests/worker-turns.test.ts
@@ -7,7 +7,7 @@ import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { GpuWatch } from "../bin/lib/worker/gpu.mjs";
-import { measureBaseline, parseCounters, parseListeners, pickGpu, readLock, splitMemory, unknownHolder, workPids } from "../bin/lib/worker/local-work.mjs";
+import { BASELINE_CAP_MB, measureBaseline, parseCounters, parseListeners, pickGpu, readLock, splitMemory, unknownHolder, workPids } from "../bin/lib/worker/local-work.mjs";
import { readYielded, SiteTurns, TURNS, writeSite } from "../bin/lib/worker/turns.mjs";
import { siteOf } from "../bin/lib/worker/run.mjs";
import { tempDir } from "./helpers/temp-dir";
@@ -124,10 +124,29 @@ describe("the port table and the GPU counters", () => {
});
it("measures the desktop's share at setup, without local ComfyUI work", async () => {
- const mb = await measureBaseline({ localComfyPorts: [8188, 8199] }, { readGpu: async () => ({ usedMb: 9700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[4242, 9000], [77, 650]])), readListeners: async () => LISTING });
- expect(mb).toBe(700);
+ const m = await measureBaseline({ localComfyPorts: [8188, 8199] }, { readGpu: async () => ({ usedMb: 9700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[4242, 9000], [77, 650]])), readListeners: async () => LISTING });
+ expect(m).toMatchObject({ mb: 700, measuredMb: 700, capped: false, usedMb: 9700, ownMb: 0, workMb: 9000, top: [{ pid: 77, mb: 650, name: "dwm" }] });
expect(await measureBaseline({}, { readGpu: async () => ({ usedMb: 1, tempC: 1, apps: [] }), readCounters: async () => null })).toBeNull();
});
+
+ it("leaves out the worker's own ComfyUI, by its pid file: its process and the one on its port (a venv's real Python)", async () => {
+ const workDir = tempDir("fuobe-worker-baseline-");
+ // The worker runs: its ComfyUI started as pid 900 (a venv's python.exe), whose own Python (pid 901) listens on 31400
+ // and holds 18 GB of models.
+ fs.writeFileSync(path.join(workDir, "comfyui.pid"), JSON.stringify({ pid: 900, port: 31_400, marker: "comfy_guard.py" }));
+ const listing = { listeners: [...LISTING.listeners, { port: 31_400, pid: 901 }], names: { ...LISTING.names, "901": "python" } };
+ const deps = { readGpu: async () => ({ usedMb: 18_600, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[900, 0], [901, 18_000], [77, 600]])), readListeners: async () => listing };
+ expect(await measureBaseline({ workDir, localComfyPorts: [8188, 8199] }, deps)).toMatchObject({ mb: 600, ownMb: 18_000, capped: false });
+ // Without the pid file (an older worker folder), it would count as the desktop's: capped, and said so.
+ const blind = await measureBaseline({ workDir: tempDir("fuobe-worker-baseline-"), localComfyPorts: [8188, 8199] }, deps);
+ expect(blind).toMatchObject({ mb: BASELINE_CAP_MB, measuredMb: 18_600, capped: true });
+ expect(blind!.top[0]).toEqual({ pid: 901, mb: 18_000, name: "python" });
+ });
+
+ it("saves at most its cap: a game left open is named instead of hiding programs from then on", async () => {
+ const m = await measureBaseline({ localComfyPorts: [8188, 8199] }, { readGpu: async () => ({ usedMb: 12_700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[5555, 12_000], [77, 650]])), readListeners: async () => LISTING });
+ expect(m).toMatchObject({ mb: BASELINE_CAP_MB, measuredMb: 12_700, capped: true, top: [{ pid: 5555, mb: 12_000, name: "game" }, { pid: 77, mb: 650, name: "dwm" }] });
+ });
});
describe("the busy pause after two readings", () => {
@@ -211,6 +230,21 @@ describe("turns", () => {
expect(turns.step(T0 + 30_000, { ...facts, may: false, unsure: true })).toMatchObject({ siteWaiting: 0, ended: "stopped" });
});
+ it("allows one interrupt, named by the time it was allowed, until the helper answers after it", () => {
+ const a = setup({ interruptGapMin: 30 });
+ expect(a.turns.step(T0, { ...facts, serverInterrupt: true })).toMatchObject({ interrupt: true, interruptAt: T0 });
+ // Still the same one interrupt while the helper hasn't answered: a helper stops one job per interruptAt.
+ expect(a.turns.step(T0 + 1000, { ...facts, serverInterrupt: true })).toMatchObject({ interrupt: true, interruptAt: T0, waitForYield: true });
+ // An answer from before it was allowed doesn't count.
+ answer(a.folder, { state: "yielding", at: T0 - 5000 });
+ expect(a.turns.step(T0 + 2000, { ...facts, serverInterrupt: true })).toMatchObject({ interrupt: true, interruptAt: T0 });
+ // The helper is making room, after the interrupt was allowed: it has seen it, and the flag goes.
+ answer(a.folder, { state: "yielding", at: T0 + 2500, startsAt: T0 + 60_000 });
+ expect(a.turns.step(T0 + 3000, { ...facts, serverInterrupt: true })).toMatchObject({ interrupt: false, interruptAt: null, waitForYield: true });
+ // Still inside the gap: no second interrupt in this turn.
+ expect(a.turns.step(T0 + 4000, { ...facts, serverInterrupt: true })).toMatchObject({ interrupt: false, interruptAt: null });
+ });
+
it("asks for an interrupt only when the studio does, at most once per gap, and never when the PC says never", () => {
const a = setup({ interruptGapMin: 30 });
expect(a.turns.step(T0, { ...facts, serverInterrupt: true }).interrupt).toBe(true);
@@ -273,17 +307,19 @@ describe("turns", () => {
expect(t.folderOk()).toBe(false);
});
- it("reads the beat's count, the oldest wait and the interrupt switch; absent means it doesn't say", () => {
- expect(siteOf({ claimableNow: 2, oldestWaitS: 40, worker: { yieldInterrupt: true } })).toEqual({ claimable: 2, oldestWaitS: 40, interrupt: true });
- expect(siteOf({ worker: { claimableNow: 1 } })).toEqual({ claimable: 1, oldestWaitS: null, interrupt: false });
- expect(siteOf({ waiting: 9, worker: {} })).toEqual({ claimable: null, oldestWaitS: null, interrupt: false });
+ it("reads only the beat's claimableNow (a count); absent, or anything else, means the studio doesn't say", () => {
+ expect(siteOf({ claimableNow: 2 })).toEqual({ claimable: 2 });
+ expect(siteOf({ claimableNow: 0 })).toEqual({ claimable: 0 });
+ // Fields the protocol doesn't have are not read.
+ expect(siteOf({ worker: { claimableNow: 1, yieldInterrupt: true }, oldestWaitS: 40 })).toEqual({ claimable: null });
+ expect(siteOf({ waiting: 9, claimableNow: -1, worker: {} })).toEqual({ claimable: null });
expect(siteOf(null).claimable).toBeNull();
});
- it("the oldest wait: the studio's when it says, else how long this worker has seen jobs waiting", () => {
+ it("the oldest wait: how long this worker has seen people's jobs waiting for it", () => {
const { turns } = setup();
expect(turns.step(T0, { ...facts, workHolds: false }).oldestWaitS).toBe(0);
expect(turns.step(T0 + 30_000, { ...facts, workHolds: false }).oldestWaitS).toBe(30);
- expect(turns.step(T0 + 31_000, { ...facts, workHolds: false, oldestWaitS: 95 }).oldestWaitS).toBe(95);
+ expect(turns.step(T0 + 31_000, { ...facts, workHolds: false, claimable: 0 }).oldestWaitS).toBe(0);
});
});
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index 31eebbda..f66edf7f 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -20,7 +20,7 @@ const { principalOf } = await import("@/server/computer/http");
const beatRoute = await import("@/app/api/gpu/computer/beat/route");
const claimRoute = await import("@/app/api/gpu/computer/claim/route");
const reportRoute = await import("@/app/api/gpu/computer/tasks/[id]/report/route");
-const { forWorkers } = await import("@/server/providers/comfyui");
+const { comfyProvider, forWorkers } = await import("@/server/providers/comfyui");
const { hoursAt, parseHours } = await import("@/lib/worker-hours");
const lanesModule = await import("@/lib/lanes");
const { lanesFor, needsOf, laneOf } = lanesModule;
@@ -51,7 +51,7 @@ const row = (w: W) => workers.getWorker(w.id)!;
function beat(w: W, local: { paused?: boolean; why?: string | null } = {}, running: string[] = []) {
return pool.workerBeat(
row(w),
- pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1.0.0", local: { paused: local.paused ?? false, why: local.why ?? null, until: null }, gpu: {}, inventoryHash: null, running: running.map((task) => ({ task })), stopped: [] }),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: local.paused ?? false, why: local.why ?? null, until: null }, gpu: {}, inventoryHash: null, running: running.map((task) => ({ task })), stopped: [] }),
clock,
);
}
@@ -59,7 +59,7 @@ function beat(w: W, local: { paused?: boolean; why?: string | null } = {}, runni
const claim = (w: W, running: string[] = []) => pool.workerClaim(row(w), running, clock);
let gens = 0;
-function task(o: { lane?: string; workflow?: string; minVram?: number; rankAgoMs?: number; estMs?: number; notAfter?: number } = {}) {
+function task(o: { lane?: string; workflow?: string; minVram?: number; rankAgoMs?: number; estMs?: number; notAfter?: number; account?: string } = {}) {
const gid = `gen-${++gens}`;
db()
.prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")
@@ -69,7 +69,7 @@ function task(o: { lane?: string; workflow?: string; minVram?: number; rankAgoMs
principal: "owner",
generationId: gid,
graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
- pool: { pools: ["pool"], rankAt: created, lane: o.lane ?? LANE_A, needs: { workflowId: o.workflow ?? "wf-a", files: [], packs: [], minVramBytes: o.minVram ?? 0 }, estMs: o.estMs, notAfter: o.notAfter },
+ pool: { pools: ["pool"], account: o.account, rankAt: created, lane: o.lane ?? LANE_A, needs: { workflowId: o.workflow ?? "wf-a", files: [], packs: [], minVramBytes: o.minVram ?? 0 }, estMs: o.estMs, notAfter: o.notAfter },
});
db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(created, t.id);
return t.id;
@@ -92,7 +92,7 @@ describe("who may claim (check 1)", () => {
it("a new worker is paused in both places and claims nothing", () => {
const w = pool.addWorker("fresh");
task();
- const a = pool.workerBeat(row({ id: w.id, token: w.token }), pool.cleanBeat({ device: "x", protocol: 1, version: "1", local: { paused: true, why: "here" } }), clock);
+ const a = pool.workerBeat(row({ id: w.id, token: w.token }), pool.cleanBeat({ device: "x", protocol: 2, version: "1", local: { paused: true, why: "here" } }), clock);
expect(a.runner).toBe(false);
expect(a.worker.paused).toBe(true);
expect(pool.workerClaim(row({ id: w.id, token: w.token }), [], clock)).toBeNull();
@@ -111,6 +111,24 @@ describe("who may claim (check 1)", () => {
expect(state(id2).state).toBe("waiting");
});
+ it("an older worker program takes no task, and the owner sees why", () => {
+ const id = task();
+ const w = worker("older-program");
+ const a = pool.workerBeat(
+ row(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "0.9.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }),
+ clock,
+ );
+ expect(a.runner).toBe(false);
+ expect(a.worker.minProtocol).toBe(2);
+ expect(a.claimableNow).toBe(0);
+ expect(claim(w)).toBeNull();
+ expect(pool.workerState(row(w), clock)).toEqual({ state: "paused", words: "Takes no jobs until its worker program is updated" });
+ expect(state(id).state).toBe("waiting");
+ beat(w);
+ expect(claim(w)?.id).toBe(id);
+ });
+
it("paused on the website, or here, or draining: no new task", () => {
task();
const w = worker("p", { pausedServer: true });
@@ -222,6 +240,30 @@ describe("losing a worker (checks 3, 4, 5)", () => {
expect(state(id).tried_json).toBeNull();
});
+ it("a pause now leaves a job whose finished results the worker keeps its own, so it sends them instead of running it again", () => {
+ const id = task();
+ const w = worker("keeps");
+ claim(w);
+ tasks.setTask(id, { state: "running", sent_at: clock });
+ const a = pool.workerBeat(
+ row(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: true, why: "here-now", until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], held: [id] }),
+ clock,
+ );
+ expect(a.worker.pauseNow).toBe(true);
+ expect(a.stops).toEqual([]);
+ expect(state(id)).toMatchObject({ state: "running", worker_id: w.id });
+ // Paused, it may take no new job, but its own job comes back to it, for the kept results.
+ expect(pool.workerClaim(row(w), [], clock)?.id).toBe(id);
+ // The same pause with nothing kept: the job goes back in line.
+ const id2 = task();
+ const w2 = worker("keeps-nothing");
+ claim(w2);
+ tasks.setTask(id2, { state: "running", sent_at: clock });
+ beat(w2, { paused: true, why: "here-now" }, [id2]);
+ expect(state(id2).state).toBe("waiting");
+ });
+
it("a busy GPU on the worker sends its job back the same way", () => {
const id = task();
const w = worker("busy");
@@ -286,14 +328,55 @@ describe("order (checks 8, 9)", () => {
});
});
+describe("people's runs this worker may take now (the beat's claimableNow)", () => {
+ it("counts people's waiting runs it can run here, never the owner's own, and not runs for other lanes, files or VRAM", () => {
+ const w = worker("counts", { lanes: [LANE_A], workflows: ["wf-a"], vram: 12 * GB });
+ expect(beat(w).claimableNow).toBe(0);
+ task(); // the owner's own
+ expect(beat(w).claimableNow).toBe(0);
+ task({ account: "acct-1" });
+ task({ account: "acct-2" });
+ task({ account: "acct-3", lane: LANE_B }); // a lane it isn't allowed
+ task({ account: "acct-4", workflow: "wf-z" }); // a workflow it can't run
+ task({ account: "acct-5", minVram: 20 * GB }); // more VRAM than it has
+ expect(beat(w).claimableNow).toBe(2);
+ // Its own pause doesn't change the count (its PC reads it to know whether people's runs wait for it).
+ expect(beat(w, { paused: true, why: "gpu-busy:ComfyUI on port 8188" }).claimableNow).toBe(2);
+ // Paused on the website, draining or outside its hours: none.
+ pool.patchWorker(w.id, { paused: true });
+ expect(beat(w).claimableNow).toBe(0);
+ pool.patchWorker(w.id, { paused: false, drain: true });
+ expect(beat(w).claimableNow).toBe(0);
+ pool.patchWorker(w.id, { drain: false, hours: everyDay(at(180), at(240)) });
+ expect(beat(w).claimableNow).toBe(0);
+ });
+
+ it("goes down as it claims them", () => {
+ const w = worker("claims");
+ task({ account: "acct-1" });
+ task({ account: "acct-2" });
+ expect(beat(w).claimableNow).toBe(2);
+ expect(claim(w)).not.toBeNull();
+ expect(beat(w, {}, []).claimableNow).toBe(1);
+ });
+});
+
describe("routes", () => {
+ it("the beat's answer carries claimableNow", async () => {
+ clock = Date.now();
+ const w = worker("beat-route");
+ task({ account: "acct-route" });
+ const res = await beatRoute.POST(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "x", protocol: 2, version: "1", local: { paused: false } }) }));
+ expect(((await res.json()) as { claimableNow?: number }).claimableNow).toBe(1);
+ });
+
it("three workers that beat every 5 seconds are not rate-limited (check 14)", async () => {
clock = Date.now();
const ws = [worker("r1"), worker("r2"), worker("r3")];
let ok = 0;
for (let i = 0; i < 12; i++) {
for (const w of ws) {
- const res = await beatRoute.POST(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "x", protocol: 1, version: "1", local: { paused: false } }) }));
+ const res = await beatRoute.POST(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "x", protocol: 2, version: "1", local: { paused: false } }) }));
if (res.status === 200) ok++;
}
}
@@ -310,7 +393,8 @@ describe("routes", () => {
const { task: t } = await c.json();
expect(t.id).toBe(id);
expect(t.lane).toBe(LANE_A);
- expect(t.runLimitMs).toBe(5 * MIN);
+ // No times for the lane on this worker yet: the run ceiling, so a first long job (a cold model load) can finish.
+ expect(t.runLimitMs).toBe(45 * MIN);
const sent = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify({ event: "sent", promptId: t.promptId }) }), {
params: Promise.resolve({ id }),
});
@@ -399,6 +483,25 @@ describe("a worker's own reports: giving a job back, its execution time, the inp
}
});
+ it("a job given back shows its kept place in line, then the usual words once a worker has it again: never a restart", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("words");
+ const poll = async () => (await comfyProvider.poll({ externalId: "11111111-1111-4111-8111-111111111111", meta: { relay: id, workflowId: "none", generationId: state(id).generation_id } } as never)) as { state: string; message?: string };
+ const first = await routed(w, id);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ await first.say({ event: "give-back", why: "stalled" });
+ expect(state(id)).toMatchObject({ state: "waiting", note: "resent" });
+ const waiting = await poll();
+ expect(waiting).toMatchObject({ state: "queued", message: pool.poolWaitWords(state(id)) });
+ expect(waiting.message).not.toMatch(/another GPU|restart/i);
+ await routed(w, id);
+ const again = await poll();
+ expect(state(id).state).toBe("sending");
+ expect(again.state).toBe("queued");
+ expect(again.message).not.toMatch(/restart|sent it again/i);
+ });
+
it("a give-back with an unknown reason is refused, and a person's own computer can't give its job back", async () => {
clock = Date.now();
const id = task();
@@ -430,6 +533,86 @@ describe("a worker's own reports: giving a job back, its execution time, the inp
expect(tasks.execOf(state(id2))).toBeNull();
});
+ it("holds a reported execution time to the time since the job was sent, and to its run ceiling", async () => {
+ clock = Date.now();
+ const w = worker("exec-caps");
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ const finish = async (sentAgoMs: number, execMs: number) => {
+ const id = task();
+ const { t } = await routed(w, id);
+ tasks.report(state(id), { event: "sent", promptId: t.promptId }, () => ({ error: "x" }));
+ tasks.setTask(id, { sent_at: Date.now() - sentAgoMs });
+ tasks.report(state(id), { event: "finished", entry, execMs }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ return tasks.execOf(state(id))!.ms;
+ };
+ // Sent 2 minutes ago, said to have run 10 hours: about 3 minutes (2, and the minute allowed before "sent").
+ const capped = await finish(2 * MIN, 10 * 60 * MIN);
+ expect(capped).toBeGreaterThanOrEqual(3 * MIN - 1_000);
+ expect(capped).toBeLessThanOrEqual(3 * MIN + 1_000);
+ // Sent 3 hours ago, said to have run 2 hours: the run ceiling.
+ expect(await finish(180 * MIN, 120 * MIN)).toBe(pool.RUN_CEILING_MS);
+ // A sound time stays as it was.
+ expect(await finish(30 * MIN, 25 * MIN)).toBe(25 * MIN);
+ });
+
+ it("past its run limit: back in line once, with the whole run ceiling for its next try; past it again, it fails at once", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("run-limit");
+ db().prepare("UPDATE relay_workers SET bench_json = ? WHERE id = ?").run(JSON.stringify({ [LANE_A]: { medianMs: 2 * MIN, p90Ms: 3 * MIN } }), w.id);
+ const first = await routed(w, id);
+ expect(first.t.runLimitMs).toBe(10 * MIN);
+ expect(first.t.stallMs).toBe(pool.STALL_MS);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ expect((await first.say({ event: "give-back", why: "run-limit" })).body.state).toBe("waiting");
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ // The lane's times may come from shorter jobs: this one gets the whole ceiling now.
+ const second = await routed(w, id);
+ expect(second.t.runLimitMs).toBe(pool.RUN_CEILING_MS);
+ await second.say({ event: "sent", promptId: second.t.promptId });
+ const back = await second.say({ event: "give-back", why: "run-limit" });
+ expect(back.body.state).toBe("failed");
+ expect(state(id)).toMatchObject({ state: "failed", error: pool.GAVE_BACK_WORDS, requeues: 2 });
+ // Other reasons still have three tries: a stall after one run-limit goes back in line.
+ const id2 = task();
+ const third = await routed(w, id2);
+ await third.say({ event: "sent", promptId: third.t.promptId });
+ await third.say({ event: "give-back", why: "run-limit" });
+ const fourth = await routed(w, id2);
+ await fourth.say({ event: "sent", promptId: fourth.t.promptId });
+ expect((await fourth.say({ event: "give-back", why: "stalled" })).body.state).toBe("waiting");
+ });
+
+ it("results kept from an earlier try go up as no new attempt, keep their own time, and add no time to the lane", async () => {
+ clock = Date.now();
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ // Made 10 minutes ago; it ran, its worker stopped before the studio heard, and it went back in line.
+ const id = task({ rankAgoMs: 10 * MIN });
+ const w = worker("kept");
+ const first = await routed(w, id);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ expect(state(id).attempts).toBe(1);
+ pool.backInLine(state(id), { blame: true });
+ const again = await routed(w, id);
+ expect((await again.say({ event: "sent", promptId: again.t.promptId, kept: true })).status).toBe(200);
+ expect(state(id).attempts).toBe(1);
+ const done = await again.say({ event: "finished", entry, execMs: 4 * MIN, device: "Test GPU <b>", kept: true });
+ expect(done.status).toBe(200);
+ expect(state(id).state).not.toBe("queued");
+ // Its time ran before this "sent": kept as reported (it is under the time since the task was made). The GPU's name
+ // keeps only plain characters.
+ expect(tasks.execOf(state(id))).toEqual({ ms: 4 * MIN, device: "Test GPU b" });
+ expect(JSON.parse(row(w).bench_json ?? "{}")[LANE_A]).toBeUndefined();
+ // A job that runs here counts toward the lane's times, and its "sent" is an attempt.
+ const id2 = task();
+ const run = await routed(w, id2);
+ await run.say({ event: "sent", promptId: run.t.promptId });
+ expect(state(id2).attempts).toBe(1);
+ tasks.setTask(id2, { sent_at: Date.now() - 5_000 });
+ await run.say({ event: "finished", entry, execMs: 1_000 });
+ expect(JSON.parse(row(w).bench_json ?? "{}")[LANE_A]?.runs).toHaveLength(1);
+ });
+
it("a worker that can't make clips and sound again gets no workflow that reads them", () => {
const index = loadIndex();
const { mediaOf } = lanesModule;
@@ -439,13 +622,39 @@ describe("a worker's own reports: giving a job back, its execution time, the inp
// A worker that has every file and pack.
const files = Object.values(index.files).map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
const nodePacks = Object.keys(index.packs).map((name) => ({ name, commit: null }));
- const all = lanesFor(index, { files, nodePacks }, sha).workflows;
+ const all = lanesFor(index, { files, nodePacks, media: ["image", "video", "audio"] }, sha).workflows;
expect(all).toEqual(expect.arrayContaining([...reads, ...pictures]));
- expect(lanesFor(index, { files, nodePacks, media: ["image", "video", "audio"] }, sha).workflows).toEqual(all);
const onlyPictures = lanesFor(index, { files, nodePacks, media: ["image"] }, sha);
expect(onlyPictures.workflows).toEqual(expect.arrayContaining(pictures));
for (const id of reads) expect(onlyPictures.workflows).not.toContain(id);
expect(onlyPictures.missing.some((m) => m.files.includes("input:video"))).toBe(true);
+ // A worker from before workers said which inputs they take (no `media`) never re-encodes clips: pictures only.
+ expect(lanesFor(index, { files, nodePacks }, sha).workflows).toEqual(onlyPictures.workflows);
+ });
+
+ it("a job's run limit: the run ceiling with no times yet, else 3 × the lane's p90 plus its load, 10 minutes to the ceiling", () => {
+ expect(pool.runLimitMs(undefined)).toBe(pool.RUN_CEILING_MS);
+ expect(pool.runLimitMs(null, "small", 200_000)).toBe(45 * MIN);
+ expect(pool.runLimitMs(0)).toBe(45 * MIN);
+ expect(pool.runLimitMs(30_000)).toBe(10 * MIN);
+ expect(pool.runLimitMs(4 * MIN, "small", 3 * MIN)).toBe(15 * MIN);
+ expect(pool.runLimitMs(20 * MIN, "small", 5 * MIN)).toBe(45 * MIN);
+ // The claim gives the worker's own times for the lane.
+ clock = Date.now();
+ const id = task();
+ const w = worker("timed");
+ db().prepare("UPDATE relay_workers SET bench_json = ? WHERE id = ?").run(JSON.stringify({ [LANE_A]: { medianMs: 3 * MIN, p90Ms: 4 * MIN, loadMs: 3 * MIN } }), w.id);
+ const t = pool.workerClaim(row(w), [], clock)!;
+ expect(t.id).toBe(id);
+ expect(t.runLimitMs).toBe(15 * MIN);
+ });
+
+ it("an older worker's inventory (no `media`) keeps its hash, so the studio doesn't ask for it at every beat", () => {
+ const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };
+ const w = worker("older");
+ pool.saveInventory(row(w), inv);
+ expect(row(w).inventory_hash).toBe(pool.inventoryHash(inv));
+ expect(JSON.parse(row(w).inventory_json ?? "{}").media).toBeUndefined();
});
it("the inventory's hash covers the kinds of input, and the worker hashes it the same way", async () => {