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: a job ticket carries its graph's fingerprint, so a worker on an older version runs every run whose graph is the same

Adarshd0cefb852385
diff --git a/bin/fuobe.mjs b/bin/fuobe.mjs
index 01d96000..e4609ac9 100755
--- a/bin/fuobe.mjs
+++ b/bin/fuobe.mjs
@@ -66,6 +66,8 @@ process.exitCode = await main(process.argv.slice(2), {
onInterrupt: (fn) => onSignals(fn),
/** Ctrl+C, and a stop from the system (SIGTERM): a long-running command ends its own way, cleaning up as it goes. */
onStop: (fn) => onSignals(fn, STOP_SIGNALS),
+ /** `fuobe worker run` runs the worker as a child process, which starts again at once on new code. */
+ superviseWorker: true,
ask,
readStdin,
});
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index 5fa6387b..0b7aa878 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -6,9 +6,10 @@ import path from "node:path";
/**
* 2: it says which inputs it takes, makes every clip and sound again, and keeps its ComfyUI behind the guard. 3: it makes
- * every picture of a job ticket again from its pixels too, and may have a CPU slot.
+ * every picture of a job ticket again from its pixels too, and may have a CPU slot. 4: it runs a job ticket made for
+ * another catalog when its own composer makes the same graph from it (the ticket's graphSha), and gives it back otherwise.
*/
-export const PROTOCOL = 3;
+export const PROTOCOL = 4;
/**
* The protocol this worker says it speaks: PROTOCOL, or 2 when it can't make pictures again (no sharp in its checkout).
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjs
index 5bea10c7..b829cb19 100644
--- a/bin/lib/worker/index.mjs
+++ b/bin/lib/worker/index.mjs
@@ -34,6 +34,8 @@ export async function worker(args, io) {
case "setup":
return setup(home, io, say);
case "run": {
+ // From the command line: the worker runs as a child that starts again at once on new code (supervise.mjs).
+ if (io.superviseWorker && !io.env?.FUOBE_WORKER_CHILD) return (await import("./supervise.mjs")).superviseWorker(rest, io);
const cfg = loadConfig(home, io.env);
if (!cfg.site || !cfg.token || !cfg.workDir) {
io.stderr.write("This worker isn't set up yet. Run: fuobe worker setup\n");
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 29638f37..2fd844e4 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -44,7 +44,7 @@ import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";
import { readLocalWork, SiteTurns, writeMode, writeSite } from "./turns.mjs";
-import { CodeWatch, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";
+import { CodeWatch, headOf, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "../../..");
@@ -333,6 +333,25 @@ async function work(saved, deps, owner) {
let updateFoundAt = null;
// When its last GPU or CPU job ended while it waits to restart on new code (a text job in hand may still end).
let textDrainAt = null;
+ // An update asked for now (status.json `update`, which the updater on the PC reads): by the owner ("owner", the beat
+ // answer's updateNow) or by a job whose graph changed in the studio's newer catalog ("graph"). Its restart keeps the
+ // rules above: after the job in hand, never cutting a person's job off.
+ let updateWanted = null;
+ let ownerAskSeen = null;
+ const wantUpdate = (why) => {
+ if (updateWanted?.why === why && now() - updateWanted.at < 60_000) return;
+ updateWanted = { at: now(), why };
+ // New code may already be there: look at once.
+ codeWatch.checkedAt = -Infinity;
+ };
+ // The commit its code came from (the studio shows it, "Back on <commit>").
+ const startedCommit = (() => {
+ try {
+ return headOf(ROOT);
+ } catch {
+ return null;
+ }
+ })();
// 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();
@@ -551,6 +570,13 @@ async function work(saved, deps, owner) {
const facts = composer.workerFactsFrom(await readPcAnswers(ownFetch, base));
const r = await composer.composeTicket({ ticket: t.ticket, generationId: t.generationId, inputs: t.inputs }, { catalog: workerCatalog(catalogDir), catalogVersion, ceiling, laneOf, facts });
if (r.ok) return { graph: r.graph, made: r.made };
+ // A ticket for the studio's newer catalog whose graph this build makes otherwise: back in line at no cost, and the
+ // update is asked for at once (the updater reads it in status.json).
+ if (r.graphChanged) {
+ wantUpdate("graph");
+ log(`Job ${t.id} goes back in line: its graph changed in the studio's newer catalog. Asking for the update now.`);
+ return { refused: r.reason };
+ }
// Why, for the PC's owner (never a setting's value: those are someone's prompt).
log(`Refused job ${t.id}: ${r.reason === "update-worker" ? "its ticket is for another catalog (update the worker)" : r.reason === "outside-ceiling" ? "it is more than this PC runs (its ceiling in worker.json)" : "its ticket isn't one it can use"}.`);
return { refused: r.reason };
@@ -659,6 +685,7 @@ async function work(saved, deps, owner) {
// Without its picture tool, it takes no job ticket: the studio sends it the owner's own jobs only.
protocol: protocolOf(pictureTool),
version: VERSION,
+ ...(startedCommit && { commit: startedCommit }),
// It saves the next token a beat answer gives it (never one for a token from the environment).
canRotateToken: canRotate,
local: pause,
@@ -691,7 +718,14 @@ async function work(saved, deps, owner) {
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\").");
// A studio whose catalog is another than this build's: its people's runs wait for an updated worker. Said once.
const theirs = a?.worker?.catalogVersion;
- if (typeof theirs === "string" && theirs !== catalogVersion && theirs !== studioCatalog) log("The studio's catalog is another than this worker's: it takes only the owner's own jobs until it is updated (docs/gpu-workers.md, \"Install and update\").");
+ if (typeof theirs === "string" && theirs !== catalogVersion && theirs !== studioCatalog) log("The studio's catalog is another than this worker's: it runs people's jobs whose graphs are the same in both, and waits for its update (docs/gpu-workers.md, \"Install and update\").");
+ // The owner asked for an update now (once for each ask).
+ const ask = Number(a?.worker?.updateNow);
+ if (Number.isFinite(ask) && ask > 0 && ask !== ownerAskSeen) {
+ ownerAskSeen = ask;
+ wantUpdate("owner");
+ log("The owner asked for an update now: it looks for new code at once and restarts after the job in hand.");
+ }
if (typeof theirs === "string") studioCatalog = theirs;
answer = a;
takeToken(a?.worker?.token);
@@ -1171,7 +1205,7 @@ async function work(saved, deps, owner) {
lastState = s;
log(s);
}
- writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null });
+ writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null, ...(updateWanted && !updating && { update: { asked: updateWanted.at, why: updateWanted.why } }) });
const before = now();
await sleep(1000);
// A second that took over a minute: the PC slept (the whole process stopped). The next beat says so.
diff --git a/bin/lib/worker/supervise.mjs b/bin/lib/worker/supervise.mjs
new file mode 100644
index 00000000..221a6d12
--- /dev/null
+++ b/bin/lib/worker/supervise.mjs
@@ -0,0 +1,80 @@
+// `fuobe worker run` as started by hand or by a start file (docs/gpu-workers.md, "Install and update"): it runs the
+// worker as a child process and, when the child ends for new code on disk (UPDATE_EXIT), starts it again on that code
+// after a few seconds, so a planned update never waits out a start file's pause for crashes. Any other end is passed
+// on as it came (0 by hand, 3 signed out, 1 a crash...), and the start file decides what follows. It reads no settings,
+// opens nothing and holds no lock: the child does all of that. When this file itself changed on disk, it ends with
+// UPDATE_EXIT too, so whatever started it starts it again on the new one.
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { UPDATE_EXIT } from "./update.mjs";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+/** The child's environment says it is the child (it runs the worker itself). */
+export const CHILD_ENV = "FUOBE_WORKER_CHILD";
+
+/** The pause before the worker starts again on new code (ms). */
+export const RESTART_PAUSE_MS = 3000;
+
+/** The files this supervisor runs from: when one changes, it hands over to whatever started it. */
+const OWN_FILES = [fileURLToPath(import.meta.url), path.resolve(here, "../../fuobe.mjs")];
+
+const fileHash = (files) => {
+ const h = crypto.createHash("sha256");
+ for (const f of files) {
+ try {
+ h.update(fs.readFileSync(f));
+ } catch {
+ h.update("-");
+ }
+ }
+ return h.digest("hex");
+};
+
+const clock = () => `[${new Date().toISOString().slice(11, 19)}]`;
+
+/**
+ * Run the worker in a child process and start it again on new code. `args`: the arguments after `worker run`. Returns
+ * the exit code to end with. `deps` (tests): spawn, script, execPath, sleep, onStop, ownFiles, pauseMs.
+ */
+export async function superviseWorker(args, io, deps = {}) {
+ const spawn = deps.spawn ?? (await import("node:child_process")).spawn;
+ const script = deps.script ?? path.resolve(here, "../../fuobe.mjs");
+ const execPath = deps.execPath ?? process.execPath;
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ const pauseMs = deps.pauseMs ?? RESTART_PAUSE_MS;
+ const ownFiles = deps.ownFiles ?? OWN_FILES;
+ const say = (line) => io.stdout.write(`${clock()} ${line}\n`);
+ const started = fileHash(ownFiles);
+ // Ctrl+C or a stop from the system reaches the child too (it stops its ComfyUI and ends): no new start after it.
+ let stopping = false;
+ const off = (deps.onStop ?? io.onStop)?.(() => {
+ stopping = true;
+ });
+ try {
+ for (;;) {
+ const code = await new Promise((resolve) => {
+ let child;
+ try {
+ child = spawn(execPath, [script, "worker", "run", ...args], { stdio: "inherit", env: { ...io.env, [CHILD_ENV]: "1" }, windowsHide: true });
+ } catch {
+ return resolve(1);
+ }
+ child.on("error", () => resolve(1));
+ child.on("exit", (c) => resolve(typeof c === "number" ? c : 1));
+ });
+ if (code !== UPDATE_EXIT || stopping) return code;
+ if (fileHash(ownFiles) !== started) {
+ say("The worker's starter changed with the new code: it hands over to the start file.");
+ return UPDATE_EXIT;
+ }
+ say(`The worker starts again on its new code in ${Math.round(pauseMs / 1000)} s.`);
+ await sleep(pauseMs);
+ if (stopping) return 0;
+ }
+ } finally {
+ off?.();
+ }
+}
diff --git a/docs/admin-api.md b/docs/admin-api.md
index 3626b93c..57d34fa2 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -44,7 +44,8 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `outputs:moderate` | `POST /api/admin/outputs/hide`, `/unhide` and `/remove` |
| `reports:read` | `GET /api/admin/reports` (reporters' emails only with `accounts:read`) |
| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/events` |
-| `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke |
+| `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke; and `POST /api/admin/workers/{id}/update` |
+| `workers:update` | `POST /api/admin/workers/{id}/update` only: ask a worker to update its program now |
| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those |
| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings`, `GET /api/admin/queue/overrides` |
| `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget (`pausedBudgetS`: how long a run that has started may spend back in line) |
@@ -126,6 +127,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `PATCH /api/admin/site/uploads` | any of the five, each `true` or `false` | `{ switches }`; 400 with the reason for an unknown switch or a value that isn't a boolean. A switch that is off leaves that kind of file as it is: the tool says why it can't take it, and the server's checks apply. Browsers pick it up when they next load a page |
| `GET /api/admin/workers` | | `{ workers, lanes }`. Each worker adds `asked: { at, words }` or null, `jobs` (each job it holds: `{ taskId, generationId, slot, lane, laneLabel, stage, state, claimedAt, startedAt, progress, progressAt, typicalMs, etaS, owners, feature?, modelName? }`) and `lastEvent: { at, kind, event, words }` or null |
| `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once |
+| `POST /api/admin/workers/{id}/update` | none | `{ worker }`: its next beat answer asks it to update now. It looks for new code at once and restarts on it after the job in hand (a person's job is never cut off). Each worker in `GET /api/admin/workers` has `update`: `state` (`current`, `updating` while behind the site's version for under 3 minutes, `behind` after), `since`, `behindMs`, `site`, `worker`, `commit` (first 12 hex), `peopleHeld`, `peopleWaiting`, `askedAt`, `words` and `needsOwner` |
| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |
| `GET /api/admin/workers/jobs` | `before`, `limit` (1 to 200, 50), `worker`, `generation` | `{ items, next }`: the workers' log, newest first. Each item: `{ id, at, event, workerId, workerName, taskId, generationId, principal, lane, execMs, device }` ([gpu-workers.md](gpu-workers.md)) |
| `GET /api/admin/workers/events` | `worker`, `kinds` (a comma list of `state`, `job`, `stage`, `looking`, `admin`, `version`, `log`; all when not given), `before`, `after`, `generation`, `limit` (1 to 500, 100) | `{ items, next, latest }`: the workers' timeline, newest first. Each item: `{ id, at, workerId, workerName, kind, event, words, taskId, generationId, lane, laneLabel, state, detail }`. `next` pages back (as `before`); `latest` is the newest row id (as `after`, for new rows only) ([gpu-workers.md](gpu-workers.md)) |
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index e2ff4194..775be09c 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -177,10 +177,20 @@ job waits for it: while the beat's `claimableNow` says that people's jobs wait t
them on the code it runs, and its log says "New worker code is installed: restarting once no person's job waits for it
(at most 30 min)." The owner's own jobs never hold the restart back. After 30 minutes it restarts anyway. Then it takes
no new job, finishes the job that it has, writes "New worker code is installed: restarting after this job." in its log,
-and ends with exit code 75. Kept results that are not sent yet stay for its next start. Whatever starts the worker can start it
-again at once on exit code 75. An update that is only half done (a new checkout whose build has not run yet) does not
-end the worker: it works on until the parts match, and checks the stamp once a minute meanwhile. A program that
-installs updates writes `update-ready.json` last, after it has checked the new build.
+and ends with exit code 75. Kept results that are not sent yet stay for its next start. `fuobe worker run` runs the
+worker as a child process: when the child ends with exit code 75, it starts it again on the new code after 3 seconds,
+so a start file's longer pause after a crash never applies to an update. Any other end is passed on as it came. When
+the starter itself (`bin/fuobe.mjs` or `bin/lib/worker/supervise.mjs`) changed with the new code, it ends with exit
+code 75 too, and whatever started it starts it again. An update that is only half done (a new checkout whose build has
+not run yet) does not end the worker: it works on until the parts match, and checks the stamp once a minute meanwhile.
+A program that installs updates writes `update-ready.json` last, after it has checked the new build.
+
+**Update now.** The owner can ask a worker to update now: **Update now** in Settings → Workers, or
+`POST /api/admin/workers/{id}/update` (docs/admin-api.md). The next beat answers carry `worker.updateNow` (when it was
+asked) until the worker runs new code, or for 15 minutes. The worker then looks at its code on disk at once, and writes
+`update: { asked, why }` into `status.json` in its home folder, so a program that installs updates can look for new
+code at once. It writes the same when a job ticket's graph changed in the studio's newer catalog (`why: "graph"`). The
+restart keeps the rules above: after the job in hand, and never while it cuts off a person's job.
### The worker's own ComfyUI
@@ -553,9 +563,20 @@ graphs, and so do a person's own computer's jobs (Fuobe Connect and the browser)
pages quote, the cloud models and the record of real renders are left out, so an update that changes only what people
read or see keeps the version, and the workers keep taking accounts' runs. The worker's build writes it
(`dist/catalog-version.json`), and the studio computes the same from its own files (or reads `FUOBE_CATALOG_VERSION`).
- Each beat says the worker's version. A ticket goes only to a worker with the same version.
- A worker built from another catalog takes the owner's own jobs, and its state in Settings → Workers reads **Update
- the worker** while accounts' runs may come to the install's GPUs. Update it (see "Install and update").
+ Each beat says the worker's version.
+- **The graph's fingerprint.** The studio puts `graphSha` on each ticket: the SHA-256 of the graph its own composer
+ makes from the ticket with no facts of any PC, in a canonical form (each node's class and inputs, keys sorted at every
+ depth, a node's `_meta` left out, and the SHA-256 of each file the composer makes; `graphFingerprint` in
+ `src/lib/ticket-compose.ts`). A worker built for the same catalog runs a ticket as before. A worker built for
+ another catalog (protocol 4 and later) composes the ticket the same way with its own build and compares: the same
+ fingerprint, and it runs the job for anyone, composed with its own PC's facts as always; any other graph, or a ticket
+ its build can't read, and it gives the job back with `update-worker`. The job goes back in line untouched (no
+ attempt counted, no failure, no charge, its place and wait kept), the worker asks for its update at once, and the
+ studio offers that job to it no more until it reports another catalog. A ticket with no fingerprint, and a worker
+ program older than protocol 4, keep the old rule: a ticket goes only to a worker with the same version.
+ While a worker is behind the studio's version for less than 3 minutes, Settings → Workers reads **Updating to the new
+ version · back in about a minute**. After that it says how long, with **Update now**. A worker program older than
+ protocol 4 takes only the owner's own jobs while it is behind.
- **The PC is the ceiling.** `ceiling` in `worker.json` (setup asks for it) is the most the PC ever runs:
`{ "lanes": [...], "workflows": [...], "maxMegapixels": 4, "maxSeconds": 10, "maxOutputs": 4 }`. Leave out a field
for no limit of its own. Each beat says the ceiling. The lanes that the owner allows in Settings → Workers only
diff --git a/src/app/api/admin/workers/[id]/update/route.ts b/src/app/api/admin/workers/[id]/update/route.ts
new file mode 100644
index 00000000..5cffa618
--- /dev/null
+++ b/src/app/api/admin/workers/[id]/update/route.ts
@@ -0,0 +1,19 @@
+import { adminAccess, audit } from "@/server/admin-tokens";
+import { askWorkerUpdate } from "@/server/computer/pool";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Update a worker now (owner only, or an admin token with workers:update or workers:write). Its next beat answer says
+ * so: the worker looks for new code at once and restarts on it after the job in hand, never cutting off a person's job.
+ * Answers with the worker as Settings → Workers shows it.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/admin/workers/[id]/update">) {
+ const access = adminAccess(request, ["workers:update", "workers:write"], "Only the studio's owner manages workers");
+ if (access instanceof Response) return access;
+ const { id } = await ctx.params;
+ const view = askWorkerUpdate(id, access.actor.kind === "token" ? access.actor.name : "owner");
+ audit(access.actor, "worker.update", id, {}, view ? 200 : 404);
+ if (!view) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
+ return Response.json({ worker: view }, { headers: NO_STORE });
+}
diff --git a/src/lib/job-ticket.ts b/src/lib/job-ticket.ts
index 6fd92e9c..6f8236d8 100644
--- a/src/lib/job-ticket.ts
+++ b/src/lib/job-ticket.ts
@@ -72,6 +72,11 @@ export interface JobTicket {
size: TicketSize;
/** The route puts the run's one LoRA in the graph's own LoRA slot (comfy-compose.ts ComposeContext.loraSlot). */
loraSlot?: boolean;
+ /**
+ * The SHA-256 of the graph this ticket composes to (graphFingerprint, src/lib/ticket-compose.ts), set by the studio. A
+ * worker built from another catalog runs the ticket when its own composer makes the same graph from it.
+ */
+ graphSha?: string;
/** Set at the claim: how long the job may run, and go without progress. */
runLimitMs?: number;
stallMs?: number;
@@ -309,14 +314,20 @@ const OUTPUT_KINDS = ["image", "video", "audio", "text", "model3d", "frame", "fi
* whether the catalog has a workflow; `o.inputs`: the files the task sends (each input must be one of them, with the
* same SHA-256; a made file's copy is never read, so only its name counts).
*/
-export function ticketProblem(t: unknown, o: { catalogVersion?: string; known?: (id: string) => boolean; inputs?: { name: string; sha256: string }[] } = {}): TicketRefusal | null {
+export function ticketProblem(
+ t: unknown,
+ o: { catalogVersion?: string; known?: (id: string) => boolean; inputs?: { name: string; sha256: string }[]; otherCatalog?: boolean } = {},
+): TicketRefusal | null {
const bad = (detail: string): TicketRefusal => ({ reason: "bad-ticket", detail });
if (!t || typeof t !== "object" || Array.isArray(t)) return bad("not a ticket");
const k = t as Partial<JobTicket> & Record<string, unknown>;
- for (const key of Object.keys(k)) if (!["v", "workflowId", "catalogVersion", "op", "settings", "inputs", "outputs", "size", "loraSlot", "runLimitMs", "stallMs"].includes(key)) return bad(`${key} isn't part of a ticket`);
+ for (const key of Object.keys(k)) if (!["v", "workflowId", "catalogVersion", "op", "settings", "inputs", "outputs", "size", "loraSlot", "graphSha", "runLimitMs", "stallMs"].includes(key)) return bad(`${key} isn't part of a ticket`);
if (k.v !== TICKET_VERSION) return { reason: "update-worker", detail: "another ticket version" };
if (typeof k.catalogVersion !== "string" || !SHA.test(k.catalogVersion)) return bad("no catalog version");
- if (o.catalogVersion !== undefined && k.catalogVersion !== o.catalogVersion) return { reason: "update-worker", detail: "another catalog version" };
+ if (k.graphSha !== undefined && (typeof k.graphSha !== "string" || !SHA.test(k.graphSha))) return bad("graphSha isn't a SHA-256");
+ // Another catalog: only a reader that checks the composed graph itself (o.otherCatalog: composeTicket) goes on, and
+ // only with the ticket's graph SHA-256 to check it against.
+ if (o.catalogVersion !== undefined && k.catalogVersion !== o.catalogVersion && !(o.otherCatalog && k.graphSha)) return { reason: "update-worker", detail: "another catalog version" };
if (typeof k.workflowId !== "string" || !WORKFLOW_ID.test(k.workflowId)) return bad("not a workflow id");
if (o.known && !o.known(k.workflowId)) return bad("an unknown workflow");
if (typeof k.op !== "string" || !OP.test(k.op)) return bad("not an operation");
diff --git a/src/lib/lanes.ts b/src/lib/lanes.ts
index 970db743..329a16e1 100644
--- a/src/lib/lanes.ts
+++ b/src/lib/lanes.ts
@@ -29,6 +29,11 @@ export interface Needs {
size?: { megapixels: number; seconds: number; outputs: number };
/** A job ticket's catalog version (src/lib/job-ticket.ts): only a worker built for that catalog takes the task. */
catalogVersion?: string;
+ /**
+ * The ticket carries its graph's fingerprint (graphSha): a worker built for another catalog that checks the graph itself
+ * may take the task too.
+ */
+ graphSha?: boolean;
/**
* The files the run adds beyond its workflow's own (a look's, a motion's or a recipe's LoRAs: src/lib/runtime-files.ts):
* only a worker that verified each one takes the task.
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index bc6f30c9..57b301e7 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -244,6 +244,11 @@ export interface WorkerAnswer {
lanesInside?: string[];
/** The owner's mode it follows now (absent: an older studio, which has people first). */
queue?: WorkerQueueMode;
+ /**
+ * The owner asked it to update now (when they asked): it looks for new code at once, and restarts on it after the job
+ * in hand. Sent until it comes back on the studio's version, or for a quarter of an hour.
+ */
+ updateNow?: number;
}
/** What a worker says in its beat, on top of a browser's. */
@@ -251,6 +256,8 @@ export interface WorkerBeat {
device: string;
protocol: number;
version: string;
+ /** The commit its code came from (absent: an older worker, or a copy that isn't a git checkout). */
+ commit?: string;
/** It saves the next token a beat answer gives it (`worker.token`) and uses it from its next call on. */
canRotateToken?: boolean;
ready: boolean;
diff --git a/src/lib/ticket-compose.ts b/src/lib/ticket-compose.ts
index ff8119f6..07144e0f 100644
--- a/src/lib/ticket-compose.ts
+++ b/src/lib/ticket-compose.ts
@@ -148,7 +148,51 @@ export function workerFactsFrom(a: { stats?: unknown; dbs?: unknown; reuse?: unk
export type TicketOutcome =
| { ok: true; graph: ComfyWorkflow; workflowId: string; size: ComposedSize; made: { name: string; data: Buffer; contentType: string }[] }
- | { ok: false; reason: "update-worker" | "bad-ticket" | "outside-ceiling"; detail: string };
+ | { ok: false; reason: "update-worker" | "bad-ticket" | "outside-ceiling"; detail: string; graphChanged?: true };
+
+/** A value in canonical form: object keys sorted, at every depth. */
+function canonical(v: unknown): unknown {
+ if (Array.isArray(v)) return v.map(canonical);
+ if (v && typeof v === "object") {
+ const out: Record<string, unknown> = {};
+ for (const k of Object.keys(v as Record<string, unknown>).sort()) {
+ const x = (v as Record<string, unknown>)[k];
+ if (x !== undefined) out[k] = canonical(x);
+ }
+ return out;
+ }
+ return v;
+}
+
+/**
+ * A composed graph's fingerprint (a job ticket's `graphSha`): the SHA-256 of "fuobe-graph-1\n" and the canonical JSON of
+ * { graph, made }. `graph`: each node's class and inputs (a node's `_meta`, its title only, is left out); keys sorted at
+ * every depth. `made`: the SHA-256 of each file the composer makes, in order. Two composers that make the same graph and
+ * the same files from a ticket give the same fingerprint, whatever else differs between their builds.
+ */
+export function graphFingerprint(graph: ComfyWorkflow, made: { data: Uint8Array }[] = []): string {
+ const nodes: Record<string, unknown> = {};
+ for (const [id, node] of Object.entries(graph)) {
+ const { _meta: _title, ...rest } = node as unknown as Record<string, unknown>;
+ void _title;
+ nodes[id] = rest;
+ }
+ const body = JSON.stringify(canonical({ graph: nodes, made: made.map((m) => crypto.createHash("sha256").update(m.data).digest("hex")) }));
+ return crypto.createHash("sha256").update(`fuobe-graph-1\n${body}`).digest("hex");
+}
+
+/**
+ * The fingerprint the studio puts on a ticket (`graphSha`): the graph its own composer makes from the ticket with its own
+ * catalog and no facts of any PC, as a worker checks it (composeTicket). Null when the ticket doesn't compose.
+ */
+export async function ticketGraphSha(job: { ticket: JobTicket; generationId: string; inputs: { name: string; sha256: string }[] }, env: { catalog: ComposeCatalog; catalogVersion: string }): Promise<string | null> {
+ const { graphSha: _old, runLimitMs: _run, stallMs: _stall, ...ticket } = job.ticket;
+ void _old;
+ void _run;
+ void _stall;
+ const r = await composeOne({ ...job, ticket: { ...ticket, catalogVersion: env.catalogVersion } }, { catalog: env.catalog, catalogVersion: env.catalogVersion }, false).catch(() => null);
+ return r?.ok ? graphFingerprint(r.graph, r.made) : null;
+}
/** A run's id as the studio makes them. */
const GENERATION_ID = /^[\w-]{1,64}$/;
@@ -165,12 +209,29 @@ export const catalogKnows = (catalog: ComposeCatalog, id: string) => catalog.has
* the files the graph makes may come out other than the ticket's (the composer that makes them changed), so they are
* given back as they came out, for the studio to stage in place of the old ones, never checked against them.
*/
-export async function composeTicket(
- job: { ticket: unknown; generationId: string; inputs: { name: string; sha256: string }[] },
- env: { catalog: ComposeCatalog; catalogVersion: string; ceiling?: Ceiling | null; laneOf?: (workflowId: string) => string | null; facts?: WorkerFacts; remake?: boolean },
-): Promise<TicketOutcome> {
+export async function composeTicket(job: TicketJob, env: ComposeEnv): Promise<TicketOutcome> {
+ const t = job.ticket as Partial<JobTicket> | null;
+ const other = !env.remake && !!t && typeof t === "object" && t.catalogVersion !== env.catalogVersion && typeof t.graphSha === "string" && /^[0-9a-f]{64}$/.test(t.graphSha);
+ if (!other) return composeOne(job, env, false);
+ // A ticket made for another catalog: first the graph as the studio made it (no facts of this PC, no ceiling), checked
+ // against its fingerprint. Anything but the same graph (another graph, a ticket this build can't read or compose) is
+ // the catalog's change, never the ticket's fault: the job goes back in line for an updated worker.
+ const changed = (detail: string): TicketOutcome => ({ ok: false, reason: "update-worker", detail, graphChanged: true });
+ if (!GENERATION_ID.test(String(job.generationId))) return { ok: false, reason: "bad-ticket", detail: "not a run id" };
+ const plain = await composeOne(job, { catalog: env.catalog, catalogVersion: env.catalogVersion }, true).catch(() => null);
+ if (!plain?.ok) return changed("the ticket doesn't compose with this build");
+ if (graphFingerprint(plain.graph, plain.made) !== t!.graphSha) return changed("the graph changed in the studio's catalog");
+ // The same graph: the job runs here, composed as always with this PC's facts and inside its ceiling.
+ const r = await composeOne(job, env, true);
+ return r.ok || r.reason === "outside-ceiling" ? r : changed("the ticket doesn't compose with this build");
+}
+
+type TicketJob = { ticket: unknown; generationId: string; inputs: { name: string; sha256: string }[] };
+type ComposeEnv = { catalog: ComposeCatalog; catalogVersion: string; ceiling?: Ceiling | null; laneOf?: (workflowId: string) => string | null; facts?: WorkerFacts; remake?: boolean };
+
+async function composeOne(job: TicketJob, env: ComposeEnv, otherCatalog: boolean): Promise<TicketOutcome> {
if (!GENERATION_ID.test(String(job.generationId))) return { ok: false, reason: "bad-ticket", detail: "not a run id" };
- const refused = ticketProblem(job.ticket, { catalogVersion: env.catalogVersion, known: (id) => catalogKnows(env.catalog, id), inputs: job.inputs });
+ const refused = ticketProblem(job.ticket, { catalogVersion: env.catalogVersion, known: (id) => catalogKnows(env.catalog, id), inputs: job.inputs, otherCatalog });
if (refused) return { ok: false, ...refused };
const t = job.ticket as JobTicket;
const lane = (id: string) => env.laneOf?.(id) ?? null;
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index da49f822..2c1871db 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -30,6 +30,7 @@ export const SCOPES = [
"reports:read",
"workers:read",
"workers:write",
+ "workers:update",
"workers:tokens",
"queue:read",
"queue:write",
@@ -54,6 +55,7 @@ export const SCOPE_LABELS: Record<Scope, string> = {
"reports:read": "See reports (reporters' emails need See accounts)",
"workers:read": "See workers",
"workers:write": "Pause, resume, change and revoke workers",
+ "workers:update": "Ask a worker to update its program now",
"workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)",
"queue:read": "See the queue and its settings",
"queue:write": "Change the queue's settings: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget",
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 8b497463..a61fae25 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -6,6 +6,8 @@ import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling
import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, packKey, partLanes, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";
import { POOL_WORDS, RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";
import { runtimeFileKeys } from "@/lib/runtime-files";
+import { APPS, MODELS } from "@/lib/catalog";
+import { laneName, type LaneName } from "@/lib/lane-names";
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
@@ -38,6 +40,19 @@ export const MIN_PROTOCOL = 2;
* ComfyUI reads it (the studio sends an account's pictures as they came), and has a CPU slot when worker.json asks.
*/
export const TICKET_PROTOCOL = 3;
+/**
+ * The oldest worker program that checks a job ticket's graph itself (its graphSha, src/lib/ticket-compose.ts): it runs a
+ * ticket made for another catalog when its own composer makes the same graph from it, and gives the job back at no cost
+ * otherwise. So a new version of the studio holds back only the people's runs whose graph it changed, and only until
+ * the worker is updated.
+ */
+export const GRAPH_PROTOCOL = 4;
+/** A worker behind the studio's version for less than this is updating; past it, the owner is shown "Update now". */
+export const BEHIND_NOTICE_MS = 3 * 60_000;
+/** The owner's "Update now" goes with each beat answer until the worker is on new code, or this long at most. */
+export const UPDATE_ASK_MS = 15 * 60_000;
+/** A worker behind the studio's version for a short while, on its own way to the new one. */
+export const UPDATING_WORDS = "Updating to the new version · back in about a minute";
/** A worker's own pause while a model folder of its isn't there yet: it keeps its last list of files. */
export const MODELS_NOT_READY = "models-not-ready";
/** A task avoids workers that lost or failed it, unless no other worker that can run it beat this recently. */
@@ -174,9 +189,13 @@ export const catalogCurrent = (w: Pick<WorkerRow, "catalog_version">): boolean =
/**
* Takes an account's job ticket: a worker program new enough (TICKET_PROTOCOL: it makes every picture again from its
- * pixels) built for this studio's catalog.
+ * pixels) built for this studio's catalog, or one that checks a ticket's graph itself (GRAPH_PROTOCOL) built for any.
*/
-export const ticketReady = (w: Pick<WorkerRow, "protocol" | "catalog_version">): boolean => (w.protocol ?? 0) >= TICKET_PROTOCOL && catalogCurrent(w);
+export const ticketReady = (w: Pick<WorkerRow, "protocol" | "catalog_version">): boolean =>
+ (w.protocol ?? 0) >= TICKET_PROTOCOL && (catalogCurrent(w) || ((w.protocol ?? 0) >= GRAPH_PROTOCOL && !!w.catalog_version));
+
+/** How long a worker has been behind the studio's catalog, as its beats said (0: it isn't). */
+export const behindFor = (w: Pick<WorkerRow, "behind_since">, now = Date.now()): number => (w.behind_since ? Math.max(0, now - w.behind_since) : 0);
export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "models-not-ready" | "waiting-for-yield" | "update-worker" | "offline";
@@ -208,7 +227,16 @@ export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerStat
return { state: "waiting-for-yield", words: `Waiting for local ComfyUI work to make room${w.local_until ? ` (starts about ${clock(w.local_until, tz)})` : ""}` };
}
// Built from another catalog while people's runs may come here: it takes the owner's own jobs, and theirs once updated.
- if (hostedRunsOn() && ((catalogVersion() && !catalogCurrent(w)) || (w.protocol ?? 0) < TICKET_PROTOCOL)) return { state: "update-worker", words: "Update the worker: it takes only your own jobs until then" };
+ if (hostedRunsOn() && (w.protocol ?? 0) < TICKET_PROTOCOL) return { state: "update-worker", words: "Update the worker: it takes only your own jobs until then" };
+ // Behind the studio's catalog. One that checks a ticket's graph takes people's runs meanwhile (all but those whose
+ // graph changed); an older one takes only the owner's own jobs. A short while behind, it is on its way to the new
+ // version by itself; past BEHIND_NOTICE_MS the owner sees how long, and "Update now".
+ if (hostedRunsOn() && catalogVersion() && !catalogCurrent(w)) {
+ const graphs = (w.protocol ?? 0) >= GRAPH_PROTOCOL;
+ const behind = behindFor(w, now);
+ if (behind < BEHIND_NOTICE_MS) return { state: graphs ? "idle" : "update-worker", words: UPDATING_WORDS };
+ return { state: "update-worker", words: `Behind the site's version for ${Math.round(behind / 60_000)} min: ${graphs ? "people's runs whose graph changed wait for its update" : "it takes only your own jobs until then"}` };
+ }
return { state: "idle", words: "Ready" };
}
@@ -244,6 +272,7 @@ export function cleanBeat(b: unknown): WorkerBeat {
device: String(o.device ?? ""),
protocol: num(o.protocol) ?? 0,
version: text(o.version, 40) ?? "",
+ ...(typeof o.commit === "string" && /^[0-9a-f]{40,64}$/.test(o.commit) && { commit: o.commit }),
...(o.canRotateToken === true && { canRotateToken: true }),
ready: o.ready !== false,
why: text(o.why, 64),
@@ -319,8 +348,19 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
// The owner's controls that ran their course end first (a mode or a hold past its time).
sweepControls(now);
// Its saved state and version before this beat: a timeline row only when either changes.
- const before = d.prepare("SELECT state, version FROM relay_workers WHERE id = ?").get(w.id) as Pick<WorkerRow, "state" | "version"> | undefined;
+ const before = d.prepare("SELECT state, version, commit_sha, behind_since, update_asked_at, update_asked_commit FROM relay_workers WHERE id = ?").get(w.id) as
+ | Pick<WorkerRow, "state" | "version" | "commit_sha" | "behind_since" | "update_asked_at" | "update_asked_commit">
+ | undefined;
const facts = b.facts ? { ...b.facts, loras: undefined } : undefined;
+ // Behind the studio's catalog since when (kept while it stays behind), and the owner's "Update now" until it is on
+ // new code (another commit, or the studio's catalog again) or UPDATE_ASK_MS went by.
+ const site = catalogVersion();
+ const behind = !!site && b.catalogVersion !== site;
+ const behindSince = behind ? (before?.behind_since ?? now) : null;
+ const asked = before?.update_asked_at ?? null;
+ const onNewCode = !!b.commit && !!before?.update_asked_commit && b.commit !== before.update_asked_commit;
+ const askDone = !!asked && (now - asked > UPDATE_ASK_MS || onNewCode || (!!before?.behind_since && !behind));
+ d.prepare("UPDATE relay_workers SET commit_sha = ?, behind_since = ?, update_asked_at = ? WHERE id = ?").run(b.commit ?? null, behindSince, askDone ? null : asked, w.id);
d.prepare(
`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,
warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ?, local_work_json = ? WHERE id = ?`,
@@ -397,6 +437,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
// Best-effort from here: the timeline never fails a beat.
const rows: NewWorkerEvent[] = [];
if (before?.version && b.version && before.version !== b.version) rows.push({ kind: "version", event: "updated", workerId: w.id, words: `Worker program updated to ${b.version}`, detail: { from: before.version, to: b.version } });
+ else if (before?.commit_sha && b.commit && before.commit_sha !== b.commit) rows.push({ kind: "version", event: "updated", workerId: w.id, words: `Worker program updated to ${b.commit.slice(0, 12)}`, detail: { from: before.commit_sha, to: b.commit } });
// Its PC's clock may run ahead of the studio's: never later than now.
for (const l of b.log ?? []) rows.push({ kind: "log", event: l.level, workerId: w.id, words: l.line, at: Math.min(l.at, now) });
logWorkerEvents(rows, now);
@@ -432,6 +473,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
...(fresh.expires_at && { tokenExpiresAt: fresh.expires_at }),
// The owner's mode it follows now: who goes first, and what local work on its PC does.
queue: { mode: mode.mode, localWork: LOCAL_WORK[mode.mode], until: mode.until },
+ // The owner asked it to update now.
+ ...(fresh.update_asked_at && { updateNow: fresh.update_asked_at }),
},
};
}).immediate();
@@ -745,7 +788,10 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
const cap = capableOf(w);
const needs = json<Needs | null>(t.needs_json, null);
if (ceilingProblem(ceilingOf(w), { workflowId: needs?.workflowId, lane, size: needs?.size })) return false;
- if (needs?.catalogVersion && needs.catalogVersion !== w.catalog_version) return false;
+ // A ticket made for another catalog than the worker's goes only to a worker that checks the graph itself
+ // (GRAPH_PROTOCOL), with the ticket's graph fingerprint to check. One that found the graph changed gave the job back
+ // (refusedBy, below) and isn't offered it again until it is updated.
+ if (needs?.catalogVersion && needs.catalogVersion !== w.catalog_version && !(needs.graphSha && !!w.catalog_version && (w.protocol ?? 0) >= GRAPH_PROTOCOL)) return false;
// A ticket's pictures come as they were sent: only a worker that makes them again from their pixels takes it.
if (needs?.catalogVersion && (w.protocol ?? 0) < TICKET_PROTOCOL) return false;
if (refusedBy(t).includes(refusalKey(w))) return false;
@@ -1055,7 +1101,7 @@ setPoolGiveBack((t, why) => {
const { claimedBefore, claimFor, ...rest } = json<Record<string, unknown>>(t.extra_json, {});
const extra = { ...rest, refusedBy: [...new Set([...refusedBy(t), ...(w ? [refusalKey(w)] : [])])].slice(-64) };
const untouched = typeof claimFor === "number" && claimFor === t.claimed_at && t.state === "sending" && !t.sent_at && !t.started_at;
- const sentBack = why === "update-worker" ? "its ticket is for another catalog than the worker's" : "more than its PC runs";
+ const sentBack = why === "update-worker" ? "its graph is another on the worker's version (it waits for the worker's update)" : "more than its PC runs";
if (!backInLine(t, untouched ? { blame: false, sentBack } : { blame: true, why: GAVE_BACK_WORDS, sentBack })) return;
if (taskById(t.id)?.state !== "waiting") return;
setTask(t.id, { extra_json: JSON.stringify(extra), ...(untouched && { claimed_at: typeof claimedBefore === "number" ? claimedBefore : null }) });
@@ -1214,18 +1260,51 @@ function memo<A, R>(fn: (a: A) => R): (a: A) => R {
// Making tasks for workers
/** The catalog's lanes, worked out once for each requirements index (loadIndex keeps one until its file changes). */
-const lanesByIndex = new WeakMap<ReturnType<typeof loadIndex>, { lanes: ReturnType<typeof allLanes>; byWorkflow: Map<string, string> }>();
-function catalogLanes(): { lanes: ReturnType<typeof allLanes>; byWorkflow: Map<string, string> } {
+const lanesByIndex = new WeakMap<ReturnType<typeof loadIndex>, { lanes: (ReturnType<typeof allLanes>[number] & LaneName)[]; byWorkflow: Map<string, string> }>();
+function catalogLanes(): { lanes: (ReturnType<typeof allLanes>[number] & LaneName)[]; byWorkflow: Map<string, string> } {
const index = loadIndex();
let kept = lanesByIndex.get(index);
if (!kept) {
- const lanes = allLanes(index, sha);
+ // Each lane by name: who uses its workflows, and its model (its largest file).
+ const users = workflowUsers();
+ const lanes = allLanes(index, sha).map((l) => {
+ const files = l.workflows.flatMap((id) => index.workflows[id]?.files ?? []).map((k) => index.files[k]).filter(Boolean);
+ const biggest = files.sort((a, b) => b.sizeBytes - a.sizeBytes)[0];
+ const name = laneName(l.lane, { file: biggest?.file ?? null, apps: l.workflows.flatMap((id) => users.get(id) ?? []), fallback: l.label });
+ return { ...l, ...name, label: l.lane === "small" ? l.label : name.label };
+ });
kept = { lanes, byWorkflow: new Map(lanes.flatMap((l) => l.workflows.map((id) => [id, l.lane] as const))) };
lanesByIndex.set(index, kept);
}
return kept;
}
+/**
+ * Who runs each workflow, by name: the catalog's models whose route on ComfyUI is the workflow (a template's variants,
+ * video-concat-{n}, too), then the apps made on those models.
+ */
+function workflowUsers(): Map<string, string[]> {
+ const out = new Map<string, string[]>();
+ const modelsOf = new Map<string, string[]>();
+ const add = (wf: string, name: string) => {
+ const list = out.get(wf) ?? [];
+ if (!list.includes(name)) list.push(name);
+ out.set(wf, list);
+ };
+ for (const m of MODELS) {
+ for (const r of m.routes ?? []) {
+ if (r.provider !== "comfyui" || !r.endpoint) continue;
+ const ids = r.endpoint.includes("{n}") ? [1, 2, 3, 4].map((n) => r.endpoint.replace("{n}", String(n))) : [r.endpoint];
+ for (const id of ids) {
+ add(id, m.name);
+ modelsOf.set(m.id, [...(modelsOf.get(m.id) ?? []), id]);
+ }
+ }
+ }
+ for (const a of APPS) for (const r of [a.open, ...(a.openAlso ?? [])]) for (const id of r ? (modelsOf.get(r.modelId) ?? []) : []) add(id, a.name);
+ return out;
+}
+
/** The lane a workflow's tasks go in (a workflow the catalog doesn't know: the small lane). */
export function poolLane(workflowId: string): string {
return catalogLanes().byWorkflow.get(workflowId) ?? "small";
@@ -1371,14 +1450,14 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
*/
export function poolFields(
workflowId: string,
- o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string; runtime?: FileNeed[] } = {},
+ o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string; graphSha?: boolean; runtime?: FileNeed[] } = {},
now = Date.now(),
) {
const index = loadIndex();
const found = needsOf(index, workflowId);
// How big the job is (a PC's ceiling reads it), and a job ticket's catalog version (only a worker built for it takes it).
// And the files the run adds beyond its workflow's own (a look's LoRAs): only a worker that verified them takes it.
- const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }), ...(o.runtime?.length && { runtime: o.runtime }) };
+ const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }), ...(o.catalogVersion && o.graphSha && { graphSha: true }), ...(o.runtime?.length && { runtime: o.runtime }) };
const needs = found && { ...found, ...extra };
const lane = poolLane(workflowId);
const cls = o.class ?? (o.account ? ("free" as const) : ("owner" as const));
@@ -1561,6 +1640,76 @@ export interface WorkerView {
ownMode: { mode: QueueMode; until: number | null; by: string; at: number } | null;
/** Local work on its PC, as its last beat said while fresh (null: none). */
localWork: LocalWork | null;
+ /** Its program against the studio's version: current, updating by itself, or behind long enough for the owner to act. */
+ update: WorkerUpdate;
+}
+
+/** A worker's program against the studio's version (WorkerView.update). Versions and commits as their first 12 hex. */
+export interface WorkerUpdate {
+ /** "updating": behind for less than BEHIND_NOTICE_MS; "behind": longer (the owner may press Update now). */
+ state: "current" | "updating" | "behind";
+ since: number | null;
+ behindMs: number;
+ site: string | null;
+ worker: string | null;
+ commit: string | null;
+ /** People's runs it gave back because their graph is another on its version, still waiting. */
+ peopleHeld: number;
+ /** People's runs waiting now that it could take. */
+ peopleWaiting: number;
+ /** When the owner asked it to update now (null: not asked, or done). */
+ askedAt: number | null;
+ words: string;
+ /** Tell the owner: behind for BEHIND_NOTICE_MS or more. */
+ needsOwner: boolean;
+}
+
+const short = (v: string | null | undefined) => (v ? v.slice(0, 12) : null);
+
+/** A worker's program against the studio's version, for the owner. A silent worker is offline, never behind. */
+export function updateOf(w: WorkerRow, now = Date.now()): WorkerUpdate {
+ const site = catalogVersion();
+ const live = !!w.seen_at && now - w.seen_at <= RELAY_TIMES.poolSilentMs;
+ const behind = live && !!site && w.catalog_version !== site;
+ const behindMs = behind ? behindFor(w, now) : 0;
+ const state = !behind ? "current" : behindMs < BEHIND_NOTICE_MS ? "updating" : "behind";
+ const key = refusalKey(w);
+ const held = behind
+ ? (db().prepare("SELECT extra_json FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND account IS NOT NULL AND INSTR(extra_json, ?) > 0").all(key) as Pick<TaskRow, "extra_json">[]).filter((t) => refusedBy(t).includes(key)).length
+ : 0;
+ const waiting = live && w.kind === "pool" ? claimableNow(w, now) : 0;
+ const words =
+ state === "current"
+ ? `On the site's version${w.commit_sha ? ` (${short(w.commit_sha)})` : ""}`
+ : state === "updating"
+ ? UPDATING_WORDS
+ : `Behind the site's version for ${Math.round(behindMs / 60_000)} min${held ? `: ${held} ${held === 1 ? "person's run waits" : "people's runs wait"} for it` : ""}`;
+ return {
+ state,
+ since: behind ? (w.behind_since ?? null) : null,
+ behindMs,
+ site: short(site),
+ worker: short(w.catalog_version),
+ commit: short(w.commit_sha),
+ peopleHeld: held,
+ peopleWaiting: waiting,
+ askedAt: w.update_asked_at ?? null,
+ words,
+ needsOwner: state === "behind",
+ };
+}
+
+/**
+ * The owner asks a worker to update now: the next beat answer carries it, and the worker looks for new code at once and
+ * restarts on it after the job in hand (a person's job is never cut off). Until it is on new code, or UPDATE_ASK_MS.
+ */
+export function askWorkerUpdate(id: string, by = "owner", now = Date.now()): WorkerView | null {
+ const d = db();
+ const w = d.prepare("SELECT * FROM relay_workers WHERE id = ? AND kind = 'pool' AND revoked_at IS NULL").get(id) as WorkerRow | undefined;
+ if (!w) return null;
+ d.prepare("UPDATE relay_workers SET update_asked_at = ?, update_asked_by = ?, update_asked_commit = ? WHERE id = ?").run(now, by.slice(0, 64), w.commit_sha ?? null, id);
+ noteAdmin(id, [["update-now", "Update now asked: it looks for new code and restarts after its job"]], by, now);
+ return workerView(d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as WorkerRow, now);
}
/** A task a worker holds now: where it is, and how long it should take. No prompt, no account's details. */
@@ -1687,6 +1836,7 @@ export function workerView(w: WorkerRow, now = Date.now(), typical: (lane: strin
mode: effectiveMode(w, now),
ownMode: workerModeOf(w),
localWork: localWorkOf(w, now),
+ update: updateOf(w, now),
};
}
@@ -1838,7 +1988,7 @@ export function queueView(now = Date.now()) {
}
/** Every lane in this studio's catalog, for the owner to allow per worker. */
-export const lanesCatalog = () => catalogLanes().lanes.map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length }));
+export const lanesCatalog = () => catalogLanes().lanes.map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length, apps: l.apps, model: l.model, file: l.file, workflowIds: l.workflows }));
/**
* The waiting line of a pool as the owner's Queue page shows it (GET /api/admin/queue): in the order its workers serve
diff --git a/src/server/computer/ticket-refresh.ts b/src/server/computer/ticket-refresh.ts
index 6cc115b0..e0a18894 100644
--- a/src/server/computer/ticket-refresh.ts
+++ b/src/server/computer/ticket-refresh.ts
@@ -5,7 +5,7 @@ import { graphLoraNames, runtimeNeeds } from "@/lib/runtime-files";
import { composeTicket, inputKind } from "@/lib/ticket-compose";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
-import { getWorkflow, loadManifest } from "../providers/comfyui";
+import { getWorkflow, loadManifest, withGraphSha } from "../providers/comfyui";
import { catalogVersion } from "./catalog-version";
import { GAVE_BACK_WORDS, poolFields } from "./pool";
import { endTask, inputsOf, json, setTask, swapTaskInput, type TaskRow } from "./tasks";
@@ -83,6 +83,8 @@ export async function refreshTickets(o: { version?: string; startedAt?: number;
const ticket: JobTicket = { ...old, catalogVersion: version };
delete ticket.runLimitMs;
delete ticket.stallMs;
+ // Its graph's fingerprint is made again for the new ticket (fillGraphShas).
+ delete ticket.graphSha;
const inputs = inputsOf(t.id).map((i) => ({ name: i.name, sha256: i.sha256 }));
const r = await composeTicket({ ticket, generationId: t.generation_id, inputs }, { catalog, catalogVersion: version, remake: true }).catch(() => null);
// Written only while the task is as it was read (still waiting, the same ticket).
@@ -122,6 +124,40 @@ export async function refreshTickets(o: { version?: string; startedAt?: number;
return { refreshed, ended };
}
+/** Waiting tickets of this catalog that have no graph fingerprint yet, at most this many per look. */
+const FILL_AT_MOST = 50;
+
+/**
+ * Waiting job tickets of this studio's catalog that carry no graph fingerprint yet (made again after an update, or made
+ * by an older version of the studio) get one (withGraphSha), and their task says so in what it needs, so a worker built
+ * for another catalog that checks the graph itself may take them. Only while the task is as it was read.
+ */
+export async function fillGraphShas(o: { version?: string } = {}): Promise<number> {
+ const version = o.version ?? catalogVersion();
+ if (!version) return 0;
+ const rows = db()
+ .prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND ticket_json IS NOT NULL AND json_extract(ticket_json, '$.catalogVersion') = ? AND json_extract(ticket_json, '$.graphSha') IS NULL AND json_extract(needs_json, '$.graphShaTried') IS NULL LIMIT ?")
+ .all(version, FILL_AT_MOST) as TaskRow[];
+ let filled = 0;
+ for (const t of rows) {
+ const ticket = json<JobTicket | null>(t.ticket_json ?? null, null);
+ if (!ticket) continue;
+ const made = await withGraphSha({ ...ticket }, t.generation_id).catch(() => null);
+ db()
+ .transaction(() => {
+ const now = db().prepare("SELECT state, ticket_json, needs_json FROM relay_tasks WHERE id = ?").get(t.id) as Pick<TaskRow, "state" | "ticket_json" | "needs_json"> | undefined;
+ if (!now || now.state !== "waiting" || now.ticket_json !== t.ticket_json) return;
+ const needs = json<Record<string, unknown>>(now.needs_json ?? null, {});
+ // A ticket that makes no fingerprint isn't tried again (only a worker built for this catalog takes it).
+ if (!made?.graphSha) return void setTask(t.id, { needs_json: JSON.stringify({ ...needs, graphShaTried: true }) });
+ setTask(t.id, { ticket_json: JSON.stringify(made), needs_json: JSON.stringify({ ...needs, graphSha: true }) });
+ filled++;
+ })
+ .immediate();
+ }
+ return filled;
+}
+
declare global {
var __fuobeTicketRefresh: { version: string; at: number; running: Promise<unknown> } | undefined;
}
@@ -138,7 +174,9 @@ export async function refreshTicketsBeforeClaim(now = Date.now()): Promise<void>
await last.running.catch(() => {});
return;
}
- const running = refreshTickets().catch(() => null);
+ const running = refreshTickets()
+ .catch(() => null)
+ .then(() => fillGraphShas().catch(() => 0));
globalThis.__fuobeTicketRefresh = { version, at: now, running };
await running;
}
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index 52d40e6f..f17228b1 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -85,6 +85,14 @@ export interface WorkerRow {
mode_json?: string | null;
/** Local work on its PC (a queue of the owner's own), as its last beat said (src/lib/relay.ts LocalWork). NULL: none. */
local_work_json?: string | null;
+ /** The commit its code came from, as its last beat said. NULL: unknown. */
+ commit_sha?: string | null;
+ /** Since when its beats say a catalog other than the studio's. NULL: it is on the studio's. */
+ behind_since?: number | null;
+ /** The owner's "Update now": when, by whom, and the commit it was on then. NULL: not asked, or done. */
+ update_asked_at?: number | null;
+ update_asked_by?: string | null;
+ update_asked_commit?: string | null;
}
const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
diff --git a/src/server/db.ts b/src/server/db.ts
index b4aefcbb..0fec1954 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1131,6 +1131,13 @@ const RELAY_COLUMNS: [string, string, string][] = [
// The owner's mode for one worker (computer/queue-controls.ts), and local work on its PC as its last beat said.
["relay_workers", "mode_json", "TEXT"],
["relay_workers", "local_work_json", "TEXT"],
+ // A worker's code commit as its last beat said, since when it is behind the studio's catalog, and the owner's "Update
+ // now" (when, by whom, and the commit it was on then) until it is on new code (pool.ts askWorkerUpdate).
+ ["relay_workers", "commit_sha", "TEXT"],
+ ["relay_workers", "behind_since", "INTEGER"],
+ ["relay_workers", "update_asked_at", "INTEGER"],
+ ["relay_workers", "update_asked_by", "TEXT"],
+ ["relay_workers", "update_asked_commit", "TEXT"],
];
declare global {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index c7ba2d4b..c2de3b93 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -97,7 +97,7 @@ import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitW
import { notOnGpusText } from "../runs-here";
import { catalogVersion } from "../computer/catalog-version";
import { ticketProblem, type JobTicket } from "@/lib/job-ticket";
-import { catalogKnows, ticketFor } from "@/lib/ticket-compose";
+import { catalogKnows, ticketFor, ticketGraphSha } from "@/lib/ticket-compose";
import { ownerWaitMs } from "../queue-settings";
import { worldcastBase, worldcastHealth } from "../worldcast";
@@ -305,7 +305,7 @@ export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this mach
* limit (the run was taken in line once; the wait limit applies only before its first start). The run's wait limit is
* the one stamped on it (0: as long as it takes), else the install's own (FUOBE_POOL_WAIT_MIN).
*/
-function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string; runtime?: FileNeed[] }) {
+function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string; graphSha?: boolean; runtime?: FileNeed[] }) {
const stamp = runStamp();
const run = generationId ? runPlaceOf(generationId) : null;
// A run that waited to enter the line (pool-holds.ts) enters where its release says (stamp.rankAt): for the system's
@@ -321,6 +321,7 @@ function accountPoolFields(workflowId: string, account: string, generationId: st
waitMs: run?.started || run?.later ? undefined : (stamp?.waitMs ?? poolWaitMs()),
size: o.size,
catalogVersion: o.catalogVersion,
+ graphSha: o.graphSha,
runtime: o.runtime,
});
}
@@ -1321,6 +1322,19 @@ export function accountTicket(p: PreparedPrompt, principal: Principal, o: { outp
return ticket;
}
+/**
+ * Put its graph's fingerprint on a job ticket (graphSha: src/lib/ticket-compose.ts ticketGraphSha), as this studio's
+ * composer makes it with this catalog. A ticket it can't make one for goes without (only a worker built for this
+ * catalog takes it then). Returns the ticket.
+ */
+export async function withGraphSha(ticket: JobTicket, generationId: string): Promise<JobTicket> {
+ const catalog = { has: (id: string) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow };
+ const sha = await ticketGraphSha({ ticket, generationId, inputs: ticket.inputs.map((i) => ({ name: i.name, sha256: i.sha256 })) }, { catalog, catalogVersion: ticket.catalogVersion }).catch(() => null);
+ if (sha) ticket.graphSha = sha;
+ else delete ticket.graphSha;
+ return ticket;
+}
+
/** What ComfyUI's /prompt answers when it refuses a graph. */
export type PromptRefusalBody = { error?: { type?: string; message?: string; extra_info?: { class_type?: string } }; node_errors?: unknown };
@@ -2026,6 +2040,8 @@ export const comfyProvider: ProviderAdapter = {
const outputs = Math.max(1, manifest.outputs.length) * Math.max(1, Math.round(Number(input.numOutputs) || 1));
// An account's run on the workers: a job ticket, and the worker composes the graph (the owner's own jobs keep theirs).
const ticket = forPool && computer !== "owner" ? accountTicket(prepared, computer, { outputs, kind: model?.kind }) : undefined;
+ // Its graph's fingerprint: a worker built for another catalog runs it when its composer makes the same graph.
+ if (ticket) await withGraphSha(ticket, generationId);
const task = createTask({
principal: computer,
generationId,
@@ -2051,7 +2067,7 @@ export const comfyProvider: ProviderAdapter = {
: // An account's: the lane and files they need, in its class (paid before free), in the order they came
// (with the billing service's head start inside the class), with the wait set for the run.
// A ticket's task goes only to a worker built for its catalog, and inside that PC's ceiling.
- accountPoolFields(manifest.id, computer.slice(5), generationId, { size: prepared.size, catalogVersion: ticket?.catalogVersion, runtime: runtime?.files }),
+ accountPoolFields(manifest.id, computer.slice(5), generationId, { size: prepared.size, catalogVersion: ticket?.catalogVersion, graphSha: !!ticket?.graphSha, runtime: runtime?.files }),
}),
});
// (`workers`: the run keeps its task's clocks, pool.ts, even when a poll of it fails.)
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index 737ceb4b..3a1125b8 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -32,6 +32,7 @@ const routes = {
queueSettings: await import("@/app/api/admin/queue/settings/route"),
workers: await import("@/app/api/admin/workers/route"),
worker: await import("@/app/api/admin/workers/[id]/route"),
+ workerUpdate: await import("@/app/api/admin/workers/[id]/update/route"),
reports: await import("@/app/api/admin/reports/route"),
audit: await import("@/app/api/admin/audit/route"),
files: await import("@/app/api/admin/files/[...path]/route"),
@@ -252,6 +253,7 @@ describe("admin tokens: every admin route asks for its scope", () => {
{ name: "POST workers", scope: "workers:tokens", run: (o) => routes.workers.POST(req("/api/admin/workers", { ...o, method: "POST", body: { name: `w${++n}` } })) },
{ name: "PATCH worker", scope: "workers:write", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { paused: true } }), ctx({ id: "nope" })) },
{ name: "PATCH worker rotate", scope: "workers:tokens", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { rotate: true } }), ctx({ id: "nope" })) },
+ { name: "POST worker update", scope: "workers:update", run: (o) => routes.workerUpdate.POST(req("/api/admin/workers/nope/update", { ...o, method: "POST", body: {} }), ctx({ id: "nope" })) },
{ name: "GET reports", scope: "reports:read", run: (o) => routes.reports.GET(req("/api/admin/reports", o)) },
{ name: "GET audit", scope: "audit:read", run: (o) => routes.audit.GET(req("/api/admin/audit", o)) },
];
@@ -271,7 +273,7 @@ describe("admin tokens: every admin route asks for its scope", () => {
it("refuses a token without the scope (403 scope) and takes one with it", async () => {
for (const c of calls) {
- const other = make(admin.SCOPES.filter((s) => s !== c.scope && !(c.scope === "outputs:hide" && s === "outputs:moderate")));
+ const other = make(admin.SCOPES.filter((s) => s !== c.scope && !(c.scope === "outputs:hide" && s === "outputs:moderate") && !(c.scope === "workers:update" && s === "workers:write")));
const res = await c.run({ token: other.token });
expect(res.status, c.name).toBe(403);
expect(await res.json(), c.name).toMatchObject({ code: "scope", scope: c.scope });
diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.ts
index 90382533..efe59f32 100644
--- a/tests/worker-tickets.test.ts
+++ b/tests/worker-tickets.test.ts
@@ -478,6 +478,11 @@ describe("the line hands out tickets inside each PC's ceiling", () => {
const { noteCatalogProcess, processStart } = await import("@/server/computer/ticket-refresh");
noteCatalogProcess(OTHER, processStart() - 60_000, Date.now() - 60_000);
expect(await refreshTickets()).toEqual({ refreshed: 1, ended: 0 });
+ // Its graph's fingerprint is made again for the new ticket (its graph names the swatch staged now).
+ expect(JSON.parse(row(id).ticket_json!).graphSha).toBeUndefined();
+ const { fillGraphShas } = await import("@/server/computer/ticket-refresh");
+ expect(await fillGraphShas()).toBe(1);
+ expect(JSON.parse(row(id).ticket_json!).graphSha).toMatch(/^[0-9a-f]{64}$/);
const after = row(id);
const next = JSON.parse(after.ticket_json!) as import("@/lib/job-ticket").JobTicket;
const swatch = next.inputs.find((i) => i.slot === made.slot)!;
@@ -495,6 +500,8 @@ describe("the line hands out tickets inside each PC's ceiling", () => {
expect(got.id).toBe(id);
const out = await composer.composeTicket({ ticket: got.ticket, generationId: gid, inputs: tasks.inputsOf(id).map((i) => ({ name: i.name, sha256: i.sha256 })) }, { catalog: { has: () => true, get: (await import("@/server/providers/comfyui")).getWorkflow } as never, catalogVersion: VERSION });
expect(out.ok, out.ok ? "" : out.detail).toBe(true);
+ // The fingerprint the studio made is the one the composer makes.
+ if (out.ok) expect(composer.graphFingerprint(out.graph, out.made)).toBe(JSON.parse(after.ticket_json!).graphSha);
} finally {
db().prepare("DELETE FROM catalog_processes").run();
}
@@ -752,13 +759,72 @@ describe("the worker program composes tickets and keeps to its PC's ceiling", ()
expect(p.logs.some((l) => /more than this PC runs/.test(l))).toBe(true);
});
- it("a ticket for another catalog is given back, and the worker says to update", async () => {
+ /** A worker whose build composes for another catalog (OTHER) than the studio's (VERSION). */
+ const olderWorker = (w: ReturnType<typeof addWorker>, s: ReturnType<typeof studio>, p: Pc) => {
+ const ctrl = new AbortController();
+ const done = runWorker(
+ { site: SITE, token: w.token, comfyDir: p.comfyDir, workDir: p.workDir, modelDirs: [], comfyCommand: [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--steps", "3", "--step-ms", "30", "--worker-guard", "1", "--count-file", p.countFile, "--graph-file", p.graphFile], comfyGuard: true, ffmpeg: null },
+ { fetch: router(w, s), home: p.home, signal: ctrl.signal, requirements: { folders: [], files: {}, packs: {}, workflows: {} }, ComputerRunner, rules: RULES, pins: {}, allowed: ALLOWED, readGpu: async () => null, ffmpegVersion: async () => null, awake: { set: () => {} }, sleep: (ms: number) => sleep(Math.min(ms, 50)), log: (line: string) => void p.logs.push(line), composer, catalogVersion: OTHER, allLanes },
+ );
+ running.push({ ctrl, done });
+ };
+
+ it("a worker built for an older catalog runs a person's ticket whose graph didn't change", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const mine = await accountTask();
+ expect(JSON.parse(row(mine.id).ticket_json!).graphSha).toMatch(/^[0-9a-f]{64}$/);
+ olderWorker(w, s, p);
+ const t = await ended(mine.id);
+ expect(t.state, t.error ?? "").toBe("done");
+ expect(t.requeues).toBe(0);
+ expect(prompts(p)).toBe(1);
+ expect(graphsSent(p)[0]).toEqual(mine.graph);
+ expect(workerRow(w).catalog_version).toBe(OTHER);
+ expect(s.reports).not.toContainEqual(expect.objectContaining({ event: "give-back" }));
+ });
+
+ it("a ticket whose graph changed goes back in line at no cost, is offered to that worker no more, and the worker asks for its update", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const mine = await accountTask();
+ // The studio's graph for it differs from the one this worker's build makes.
+ s.rewrite = (q, body) => {
+ if (q !== "/api/gpu/computer/claim") return body;
+ const { task } = body as { task: { ticket?: Record<string, unknown> } | null };
+ if (task?.ticket) task.ticket.graphSha = "f".repeat(64);
+ return body;
+ };
+ olderWorker(w, s, p);
+ await until(() => s.reports.some((r) => r.event === "give-back"));
+ expect(s.reports).toContainEqual({ event: "give-back", why: "update-worker" });
+ expect(prompts(p)).toBe(0);
+ // Not failed, not counted, its place and wait kept.
+ expect(row(mine.id)).toMatchObject({ state: "waiting", requeues: 0, claimed_at: null, error: null });
+ expect(p.logs.some((l) => /its graph changed/.test(l))).toBe(true);
+ // The update is asked for at once, for the updater on the PC (status.json).
+ await until(() => JSON.parse(fs.readFileSync(path.join(p.home, "status.json"), "utf8")).update?.why === "graph", 30_000);
+ // Not offered again until the worker is on another catalog.
+ expect(claim(w)).toBeNull();
+ expect(row(mine.id).state).toBe("waiting");
+ });
+
+ it("a ticket for another catalog with no graph fingerprint is given back, and the worker says to update", async () => {
const w = addWorker();
const s = studio();
const p = pc();
const mine = await accountTask();
// The studio hears its own version from the worker, but the worker's build composes for another one.
s.send = (q, body) => (q === "/api/gpu/computer/beat" ? { ...body, catalogVersion: VERSION } : body);
+ // A ticket made before graph fingerprints.
+ s.rewrite = (q, body) => {
+ if (q !== "/api/gpu/computer/claim") return body;
+ const { task } = body as { task: { ticket?: Record<string, unknown> } | null };
+ if (task?.ticket) delete task.ticket.graphSha;
+ return body;
+ };
const ctrl = new AbortController();
const done = runWorker(
{ site: SITE, token: w.token, comfyDir: p.comfyDir, workDir: p.workDir, modelDirs: [], comfyCommand: [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--steps", "3", "--step-ms", "30", "--worker-guard", "1", "--count-file", p.countFile], comfyGuard: true, ffmpeg: null },
diff --git a/tests/worker-updates.test.ts b/tests/worker-updates.test.ts
new file mode 100644
index 00000000..a14ee60f
--- /dev/null
+++ b/tests/worker-updates.test.ts
@@ -0,0 +1,287 @@
+import { EventEmitter } from "node:events";
+import fs from "node:fs";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-worker-updates-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+const SITE = "a".repeat(64);
+const OLDER = "b".repeat(64);
+process.env.FUOBE_CATALOG_VERSION = SITE;
+const hostedBefore = process.env.FUOBE_HOSTED_RUNS;
+process.env.FUOBE_HOSTED_RUNS = "1";
+
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const workers = await import("@/server/computer/workers");
+const { laneMatches, laneName, modelTitle } = await import("@/lib/lane-names");
+const { graphFingerprint } = await import("@/lib/ticket-compose");
+const { superviseWorker } = await import("../bin/lib/worker/supervise.mjs");
+const { UPDATE_EXIT } = await import("../bin/lib/worker/update.mjs");
+
+const LANE = "aaaaaaaaaaaa";
+const GB = 2 ** 30;
+const MIN = 60_000;
+let clock = Date.UTC(2026, 10, 2, 3, 0, 0);
+const COMMIT_1 = "1".repeat(40);
+const COMMIT_2 = "2".repeat(40);
+
+type W = { id: string; token: string };
+const row = (w: W) => workers.getWorker(w.id)!;
+
+function beat(w: W, o: { protocol?: number; catalog?: string | null; commit?: string } = {}) {
+ return pool.workerBeat(
+ row(w),
+ pool.cleanBeat({
+ device: `wkr-${w.id}`,
+ protocol: o.protocol ?? 4,
+ version: "0.1.0",
+ ...(o.commit && { commit: o.commit }),
+ ...(o.catalog !== null && { catalogVersion: o.catalog ?? SITE }),
+ local: { paused: false, why: null, until: null },
+ gpu: {},
+ inventoryHash: null,
+ running: [],
+ stopped: [],
+ }),
+ clock,
+ );
+}
+
+function worker(name: string, o: { protocol?: number; catalog?: string; commit?: string } = {}): W {
+ const w = pool.addWorker(name);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { [LANE]: { delayMs: 0 } }, claimAfterMs: 0 });
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: [LANE], workflows: ["wf-a"] }), JSON.stringify({ vramBytes: 24 * GB }), w.id);
+ beat(w, o);
+ return w;
+}
+
+let gens = 0;
+/** A person's job ticket's task, made for the site's catalog, with or without its graph's fingerprint. */
+function personTask(o: { graphSha?: boolean; catalog?: 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', '{}', '[]', ?, ?)")
+ .run(gid, clock, clock);
+ const t = tasks.createTask({
+ principal: "acct:p1",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ ticket: { v: 1, workflowId: "wf-a", catalogVersion: o.catalog ?? SITE, op: "t2i", settings: {}, inputs: [], outputs: { count: 1, kind: "image" }, size: { megapixels: 1, seconds: 0, outputs: 1 }, ...(o.graphSha !== false && { graphSha: "c".repeat(64) }) },
+ pool: { pools: ["pool"], account: "p1", class: "free", rankAt: clock, lane: LANE, needs: { workflowId: "wf-a", files: [], packs: [], minVramBytes: 0, catalogVersion: o.catalog ?? SITE, ...(o.graphSha !== false && { graphSha: true }) } },
+ } as never);
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock, t.id);
+ return t.id;
+}
+const taskRow = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+const claim = (w: W) => pool.workerClaim(row(w), [], clock);
+
+beforeAll(() => setSetting("comfyWhere", "workers"));
+afterAll(() => {
+ if (hostedBefore === undefined) delete process.env.FUOBE_HOSTED_RUNS;
+ else process.env.FUOBE_HOSTED_RUNS = hostedBefore;
+});
+beforeEach(() => {
+ clock += 60 * MIN;
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+describe("a worker behind the site's version", () => {
+ it("an older worker that checks graphs takes people's runs for a new site whose catalog changed elsewhere", () => {
+ const w = worker("graphs", { catalog: OLDER });
+ const id = personTask();
+ expect(claim(w)?.id).toBe(id);
+ expect(pool.ticketReady(row(w))).toBe(true);
+ });
+
+ it("without the ticket's fingerprint, or from a worker program too old to check it, the run waits for an updated worker", () => {
+ const old = worker("protocol-3", { protocol: 3, catalog: OLDER });
+ const plain = worker("graphs", { catalog: OLDER });
+ const bare = personTask({ graphSha: false });
+ expect(claim(plain)).toBeNull();
+ expect(claim(old)).toBeNull();
+ expect(pool.ticketReady(row(old))).toBe(false);
+ expect(taskRow(bare).state).toBe("waiting");
+ // The same worker program on the site's catalog takes it.
+ beat(plain, { catalog: SITE });
+ expect(claim(plain)?.id).toBe(bare);
+ });
+
+ it("a run it gave back over a changed graph is never failed or counted, and isn't offered to it again until it is updated", () => {
+ const w = worker("graphs", { catalog: OLDER });
+ const id = personTask();
+ const got = claim(w)!;
+ expect(got.id).toBe(id);
+ tasks.report(taskRow(id), { event: "give-back", why: "update-worker" } as never, (() => ({})) as never, clock);
+ expect(taskRow(id)).toMatchObject({ state: "waiting", requeues: 0, claimed_at: null, error: null });
+ expect(claim(w)).toBeNull();
+ // It counts as held for the owner while the worker is behind.
+ clock += 4 * MIN;
+ beat(w, { catalog: OLDER });
+ expect(pool.updateOf(row(w), clock)).toMatchObject({ state: "behind", peopleHeld: 1, needsOwner: true });
+ // Updated: offered again.
+ beat(w, { catalog: SITE });
+ expect(claim(w)?.id).toBe(id);
+ });
+
+ it("says it is updating for its first minutes, then how long it has been behind; a worker on the site's version is current", () => {
+ const w = worker("graphs", { catalog: OLDER, commit: COMMIT_1 });
+ expect(pool.workerState(row(w), clock)).toEqual({ state: "idle", words: pool.UPDATING_WORDS });
+ expect(pool.updateOf(row(w), clock)).toMatchObject({ state: "updating", words: pool.UPDATING_WORDS, needsOwner: false, site: SITE.slice(0, 12), worker: OLDER.slice(0, 12), commit: COMMIT_1.slice(0, 12) });
+ clock += 2 * MIN;
+ beat(w, { catalog: OLDER, commit: COMMIT_1 });
+ expect(pool.updateOf(row(w), clock).state).toBe("updating");
+ clock += 2 * MIN;
+ beat(w, { catalog: OLDER, commit: COMMIT_1 });
+ const s = pool.workerState(row(w), clock);
+ expect(s.state).toBe("update-worker");
+ expect(s.words).toMatch(/^Behind the site's version for 4 min: people's runs whose graph changed wait for its update$/);
+ const u = pool.updateOf(row(w), clock);
+ expect(u).toMatchObject({ state: "behind", needsOwner: true, behindMs: 4 * MIN });
+ expect(u.words).toBe("Behind the site's version for 4 min");
+ beat(w, { catalog: SITE, commit: COMMIT_2 });
+ expect(pool.updateOf(row(w), clock)).toMatchObject({ state: "current", since: null, needsOwner: false, words: `On the site's version (${COMMIT_2.slice(0, 12)})` });
+ expect(pool.workerState(row(w), clock).state).toBe("idle");
+ });
+
+ it("an older worker program behind the site's version still takes only the owner's own jobs", () => {
+ const w = worker("protocol-3", { protocol: 3, catalog: OLDER });
+ expect(pool.workerState(row(w), clock)).toEqual({ state: "update-worker", words: pool.UPDATING_WORDS });
+ clock += 5 * MIN;
+ beat(w, { protocol: 3, catalog: OLDER });
+ expect(pool.workerState(row(w), clock).words).toBe("Behind the site's version for 5 min: it takes only your own jobs until then");
+ });
+});
+
+describe("Update now", () => {
+ it("goes with each beat answer until the worker is on new code, and is written in its timeline", () => {
+ const w = worker("graphs", { catalog: OLDER, commit: COMMIT_1 });
+ expect(beat(w, { catalog: OLDER, commit: COMMIT_1 }).worker.updateNow).toBeUndefined();
+ const view = pool.askWorkerUpdate(w.id, "owner", clock)!;
+ expect(view.update.askedAt).toBe(clock);
+ expect(beat(w, { catalog: OLDER, commit: COMMIT_1 }).worker.updateNow).toBe(clock);
+ const asked = clock;
+ clock += 30_000;
+ expect(beat(w, { catalog: OLDER, commit: COMMIT_1 }).worker.updateNow).toBe(asked);
+ // Back on new code: done.
+ clock += 30_000;
+ expect(beat(w, { catalog: SITE, commit: COMMIT_2 }).worker.updateNow).toBeUndefined();
+ expect(row(w).update_asked_at).toBeNull();
+ const events = db().prepare("SELECT kind, event, words FROM worker_events WHERE worker_id = ? ORDER BY id").all(w.id) as { kind: string; event: string; words: string }[];
+ expect(events).toContainEqual(expect.objectContaining({ kind: "admin", event: "update-now" }));
+ expect(events).toContainEqual(expect.objectContaining({ kind: "version", event: "updated", words: `Worker program updated to ${COMMIT_2.slice(0, 12)}` }));
+ });
+
+ it("ends after a quarter of an hour when no new code comes, and asks nothing of a worker that isn't there", () => {
+ const w = worker("graphs", { catalog: SITE, commit: COMMIT_1 });
+ pool.askWorkerUpdate(w.id, "owner", clock);
+ clock += pool.UPDATE_ASK_MS + 1;
+ expect(beat(w, { catalog: SITE, commit: COMMIT_1 }).worker.updateNow).toBeUndefined();
+ expect(pool.askWorkerUpdate("no-such-worker", "owner", clock)).toBeNull();
+ });
+
+ it("the owner's route answers with the worker, and is in the admin log", async () => {
+ const route = await import("@/app/api/admin/workers/[id]/update/route");
+ const w = worker("graphs", { catalog: OLDER, commit: COMMIT_1 });
+ const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
+ const ok = await route.POST(new Request(`http://localhost/api/admin/workers/${w.id}/update`, { method: "POST", body: "{}" }), ctx(w.id));
+ // No owner session here: refused before anything changes.
+ expect([200, 401, 403]).toContain(ok.status);
+ if (ok.status === 200) expect(((await ok.json()) as { worker: { update: { askedAt: number } } }).worker.update.askedAt).toBeGreaterThan(0);
+ else expect(row(w).update_asked_at).toBeNull();
+ });
+});
+
+describe("lane names", () => {
+ it("names a model file as people read it", () => {
+ expect(modelTitle("Wan2_1-I2V-14B-480p_fp8_e4m3fn_scaled_KJ.safetensors")).toBe("Wan 2.1 I2V 480p fp8");
+ expect(modelTitle("diffusion_models/flux1-dev-fp8.safetensors")).toBe("Flux1 dev fp8");
+ });
+
+ it("labels a lane by who uses it and its model, and finds it by app, model, file or id", () => {
+ const l = laneName("ec413688ccde", { file: "diffusion_models/Wan2_1-I2V-14B-480p_fp8_e4m3fn_scaled_KJ.safetensors", apps: ["InfiniteTalk", "InfiniteTalk", "Lipsync", "Talking Photo"], fallback: "old" });
+ expect(l).toEqual({ lane: "ec413688ccde", label: "InfiniteTalk, Lipsync +1 · Wan 2.1 I2V 480p fp8", apps: ["InfiniteTalk", "Lipsync", "Talking Photo"], model: "Wan 2.1 I2V 480p fp8", file: "Wan2_1-I2V-14B-480p_fp8_e4m3fn_scaled_KJ.safetensors" });
+ for (const q of ["infinitetalk", "talking photo", "wan 2.1", "KJ.safetensors", "ec4136", ""]) expect(laneMatches(l, q), q).toBe(true);
+ expect(laneMatches(l, "flux")).toBe(false);
+ expect(laneName("small", { file: null, apps: [], fallback: "Small jobs" }).label).toBe("Small jobs");
+ });
+
+ it("the site's lanes say which apps use them, with the big file", () => {
+ const lanes = pool.lanesCatalog();
+ const talk = lanes.find((l) => l.workflowIds.includes("infinitetalk-native"))!;
+ expect(talk.apps).toContain("InfiniteTalk");
+ expect(talk.label).toMatch(/InfiniteTalk.* · Wan 2\.1 I2V 480p fp8$/);
+ expect(talk.file).toBe("Wan2_1-I2V-14B-480p_fp8_e4m3fn_scaled_KJ.safetensors");
+ expect(lanes.every((l) => typeof l.label === "string" && l.label.length > 0)).toBe(true);
+ });
+});
+
+describe("a graph's fingerprint", () => {
+ it("is the same for the same graph whatever the key order or node titles, and differs for another graph or made file", () => {
+ const a = { "1": { class_type: "LoadImage", inputs: { image: "x.png", upload: "image" }, _meta: { title: "Load" } }, "2": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "p" } } };
+ const b = { "2": { inputs: { filename_prefix: "p", images: ["1", 0] }, class_type: "SaveImage" }, "1": { inputs: { upload: "image", image: "x.png" }, class_type: "LoadImage", _meta: { title: "Another title" } } };
+ expect(graphFingerprint(a as never)).toBe(graphFingerprint(b as never));
+ expect(graphFingerprint(a as never)).toMatch(/^[0-9a-f]{64}$/);
+ const c = { ...a, "2": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "q" } } };
+ expect(graphFingerprint(c as never)).not.toBe(graphFingerprint(a as never));
+ expect(graphFingerprint(a as never, [{ data: Buffer.from("one") }])).not.toBe(graphFingerprint(a as never, [{ data: Buffer.from("two") }]));
+ });
+});
+
+describe("the worker's own restart on new code", () => {
+ /** A stand-in for spawn: each child ends with the next code. */
+ const spawner = (codes: number[]) => {
+ const calls: { args: string[]; env: Record<string, string> }[] = [];
+ const spawn = (_exec: string, args: string[], o: { env: Record<string, string> }) => {
+ calls.push({ args, env: o.env });
+ const child = new EventEmitter();
+ const code = codes.shift() ?? 0;
+ setTimeout(() => child.emit("exit", code), 1);
+ return child;
+ };
+ return { spawn, calls };
+ };
+ const io = () => {
+ const out: string[] = [];
+ return { out, io: { env: { FUOBE_WORKER_HOME: "x" }, stdout: { write: (s: string) => void out.push(s) } } };
+ };
+ const own = () => {
+ const f = path.join(tempDir("fuobe-supervise-"), "starter.mjs");
+ fs.writeFileSync(f, "one");
+ return f;
+ };
+
+ it("starts the worker again a few seconds after it ends for new code, and passes any other end on", async () => {
+ const s = spawner([UPDATE_EXIT, UPDATE_EXIT, 0]);
+ const waits: number[] = [];
+ const { io: i, out } = io();
+ const code = await superviseWorker(["--x"], i, { spawn: s.spawn, script: "fuobe.mjs", execPath: "node", sleep: async (ms: number) => void waits.push(ms), ownFiles: [own()], onStop: () => () => {} });
+ expect(code).toBe(0);
+ expect(s.calls).toHaveLength(3);
+ expect(s.calls[0].args).toEqual(["fuobe.mjs", "worker", "run", "--x"]);
+ expect(s.calls[0].env.FUOBE_WORKER_CHILD).toBe("1");
+ expect(waits).toEqual([3000, 3000]);
+ expect(out.join("")).toMatch(/starts again on its new code in 3 s/);
+ const crash = spawner([1]);
+ expect(await superviseWorker([], io().io, { spawn: crash.spawn, sleep: async () => {}, ownFiles: [own()], onStop: () => () => {} })).toBe(1);
+ });
+
+ it("hands over to whatever started it when its own file changed with the new code", async () => {
+ const file = own();
+ const s = spawner([UPDATE_EXIT, 0]);
+ const spawn = (...a: Parameters<typeof s.spawn>) => {
+ fs.writeFileSync(file, "two");
+ return s.spawn(...a);
+ };
+ expect(await superviseWorker([], io().io, { spawn, sleep: async () => {}, ownFiles: [file], onStop: () => () => {} })).toBe(UPDATE_EXIT);
+ expect(s.calls).toHaveLength(1);
+ });
+});