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 CPU slot beside the GPU's job, and finishing jobs for it

Adarshf0689dbc1abf
diff --git a/src/app/api/gpu/computer/claim/route.ts b/src/app/api/gpu/computer/claim/route.ts
index 533845e0..10bb89db 100644
--- a/src/app/api/gpu/computer/claim/route.ts
+++ b/src/app/api/gpu/computer/claim/route.ts
@@ -14,14 +14,15 @@ export async function POST(request: Request) {
if (principal instanceof Response) return principal;
const limited = rateOf(callerKey(request, principal), "claim", 60);
if (limited) return limited;
- const body = (await request.json().catch(() => null)) as { device?: unknown; running?: unknown } | null;
+ const body = (await request.json().catch(() => null)) as { device?: unknown; running?: unknown; slot?: unknown } | null;
const running = Array.isArray(body?.running) ? body.running.filter((x): x is string => typeof x === "string").slice(0, 32) : [];
try {
const worker = requestWorker(request);
// Job tickets made for the catalog before this version of the studio are made again first (ticket-refresh.ts).
if (worker?.kind === "pool") await refreshTicketsBeforeClaim();
- // A shared GPU takes the best task it can run from its pool (pool.ts); a person's computer, their own oldest.
- const task = worker?.kind === "pool" ? workerClaim(worker, running) : claim(principal, String(body?.device ?? ""), running);
+ // A shared GPU takes the best task it can run from its pool (pool.ts), for its GPU or for its CPU slot (`slot`:
+ // "cpu"); a person's computer, their own oldest.
+ const task = worker?.kind === "pool" ? workerClaim(worker, running, Date.now(), body?.slot === "cpu" ? "cpu" : "gpu") : claim(principal, String(body?.device ?? ""), running);
if (!task) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });
return Response.json({ task }, { headers: { "Cache-Control": "no-store" } });
} catch (e) {
diff --git a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
index 57eda8ca..b262ba3b 100644
--- a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
@@ -3,6 +3,7 @@ import { connection } from "next/server";
import { RELAY_LIMITS } from "@/lib/relay";
import { gateAsProxy } from "@/server/direct-gate";
import { callerKey, isUtf8File, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { glbFileSelfContained } from "@/server/computer/finish";
import { failTask, getTask, leased, outputFile, outputStatus, receivePart, RelayError, SNIFF_BYTES, wantedOf, type TaskRow } from "@/server/computer/tasks";
import { enter } from "@/server/rate";
@@ -89,9 +90,17 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computer
}
try {
const owner = t.principal === "owner";
- const r = await receivePart(t, n, { offset, total, length }, (file, append) => writeBody(request, file, append, length), (head, w) => outputType(head, w, owner));
+ // An account's 3D model on the workers (its GPU job's model, or a finishing job's web GLB, src/lib/finish-ticket.ts):
+ // a binary glTF only, whose every buffer and picture is inside the file.
+ const glb = !owner && !!t.pools;
+ const r = await receivePart(t, n, { offset, total, length }, (file, append) => writeBody(request, file, append, length), (head, w) => outputType(head, w, owner, { glb }));
// A text result is UTF-8 through to its end.
const w = wantedOf(t).find((x) => x.n === n);
+ if (r.done && glb && w?.kind === "model3d" && !glbFileSelfContained(outputFile(t.id, n))) {
+ fs.rmSync(outputFile(t.id, n), { force: true });
+ failTask(getTask(principal, t.id) ?? t, "Couldn't save a result from your ComfyUI: it isn't a 3D model.");
+ return no(415, "That isn't a 3D model.");
+ }
if (r.done && w?.kind === "text" && !isUtf8File(outputFile(t.id, n))) {
fs.rmSync(outputFile(t.id, n), { force: true });
failTask(getTask(principal, t.id) ?? t, "Couldn't save a result from your ComfyUI: it isn't text.");
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 d2ca0b42..83e30bfc 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -1,7 +1,8 @@
-import { GIVE_BACK, RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
+import { GIVE_BACK, previewOf, RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
import { noteFinished } from "@/server/computer/bench";
+import { planFinish } from "@/server/computer/finish";
import { leased, report, type TaskRow } from "@/server/computer/tasks";
import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";
import { enter } from "@/server/rate";
@@ -10,8 +11,10 @@ const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "pas
/** Reports read at once: one person's, and across the server (each holds its body in memory while it is read). */
const AT_ONCE = { person: 2, all: 16 };
-/** A report over this size counts against a lower limit a minute. */
-const LARGE_BYTES = 64 * 1024;
+/** A report over this size counts against a lower limit a minute (a progress report with a preview stays under it). */
+const LARGE_BYTES = 128 * 1024;
+/** The most a progress report with a worker's live preview may weigh (its preview is kept only up to 64 KB). */
+const RUNNING_BYTES = 256 * 1024;
/** The event as the tab sent it, with only the fields each one has, or null. */
function eventOf(b: Record<string, unknown>): ReportEvent | null {
@@ -29,8 +32,11 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
return { event: e, status: num(b.status) ?? 400, body: b.body };
case "queued":
return { event: e, position: num(b.position) ?? -1 };
- case "running":
- return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }) };
+ case "running": {
+ // A worker's live preview: kept only as a JPEG of at most 64 KB (a larger one is dropped, the report kept).
+ const preview = previewOf(b.preview);
+ return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }), ...(preview && { preview }) };
+ }
case "finished":
return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }), ...exec } : null;
case "passes":
@@ -104,13 +110,17 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
} catch {}
const event = body && typeof body === "object" ? eventOf(body) : null;
if (!event) return no(400, "Not a report");
- if (!LARGE_EVENTS.has(event.event) && raw!.length > RELAY_LIMITS.smallReportBytes) return no(413, "That report is too large");
+ // A progress report is a few KB, unless it carries a worker's live preview.
+ const withPreview = event.event === "running" && typeof body?.preview === "string";
+ if (!LARGE_EVENTS.has(event.event) && raw!.length > (withPreview ? RUNNING_BYTES : RELAY_LIMITS.smallReportBytes)) return no(413, "That report is too large");
// 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 finishing job (src/lib/finish-ticket.ts) names its results by role; any other job, by its workflow's outputs.
+ const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => (t.finish_json ? planFinish(t, entries) : planRelayOutputs(t, entries, passes))));
// 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). The workers' log keeps its measured run (tasks.ts report).
- if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running" && !event.kept) noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
+ // there would be only the upload's; not a CPU slot's work, which uses no GPU). The workers' log keeps its measured
+ // run (tasks.ts report).
+ if (t.pools && !t.slot && (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 4be5cdf1..aaf520e9 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -8,12 +8,14 @@
* a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.
*/
import { isGuard } from "./comfy-guard";
+import { finishProblem, type FinishResult, type FinishStats } from "./finish-ticket";
import { fetchWithin } from "./fetch-within";
import { parseComfyBinary, parseComfyText } from "./comfy-ws";
import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";
import {
DONE_SHOWN_MS,
META_BATCH_HISTORY,
+ PREVIEW_LIMITS,
RELAY_LIMITS,
RELAY_TIMES,
type BeatAnswer,
@@ -80,6 +82,42 @@ export interface RunnerDeps {
onBeat?: (a: BeatAnswer) => void;
/** What only a worker program does (docs/gpu-workers.md). A browser tab has none of it. */
worker?: WorkerHooks;
+ /**
+ * A worker's CPU slot runs finishing jobs (src/lib/finish-ticket.ts) with its own code: the inputs by slot in, the
+ * files it made by role out (with what it measured), or why it refuses the job. A runner without it gives a finishing
+ * job back. A browser tab never gets one.
+ */
+ finish?: (t: ClaimedTask, inputs: Record<string, ArrayBuffer>, o: { signal: AbortSignal; progress: (fraction: number) => void }) => Promise<FinishMade | { refused: "unsafe-model" | "finish-failed" }>;
+}
+
+/** The files a finishing job made, by role, and what it measured. */
+export interface FinishMade {
+ files: { role: string; name: string; data: ArrayBuffer | Uint8Array; contentType: string }[];
+ stats?: FinishStats;
+ turntable?: string;
+}
+
+/**
+ * A worker's live preview for a progress report: the latest preview of its job as base64, when it is a JPEG of at most
+ * PREVIEW_LIMITS.maxBytes and the last one went at least PREVIEW_LIMITS.everyMs ago (else undefined: none is sent).
+ */
+export async function previewForReport(preview: Blob | undefined, lastSentAt: number, now: number, shrink?: (b: Blob) => Promise<Blob | null>): Promise<string | undefined> {
+ if (!preview || preview.size === 0 || now - lastSentAt < PREVIEW_LIMITS.everyMs) return undefined;
+ const isJpeg = async (b: Blob) => {
+ if (b.size === 0 || b.size > PREVIEW_LIMITS.maxBytes || (b.type && b.type !== "image/jpeg")) return null;
+ const bytes = new Uint8Array(await b.arrayBuffer());
+ return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff ? bytes : null;
+ };
+ // A PNG or a big JPEG is made again as a small JPEG first, when the worker can.
+ let bytes = await isJpeg(preview);
+ if (!bytes && shrink) {
+ const small = await shrink(preview).catch(() => null);
+ bytes = small ? await isJpeg(small) : null;
+ }
+ if (!bytes) return undefined;
+ let bin = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return btoa(bin);
}
/** Why a worker refuses a job ticket: another catalog, more than its PC allows, or a ticket it can't use (or a graph where a ticket belongs). */
@@ -149,6 +187,11 @@ export interface WorkerHooks {
* `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>;
+ /**
+ * A live preview its ComfyUI made that isn't a JPEG small enough to send (a PNG, or a big JPEG): made again as a small
+ * JPEG (at most 512 pixels on its long side), or null when it can't. Without it, only a small JPEG is sent.
+ */
+ shrinkPreview?(preview: Blob): Promise<Blob | null>;
}
/** ComfyUI's words for running out of memory (lib/gpu/fix-codes.ts says the same). */
@@ -284,7 +327,7 @@ export class ComputerRunner {
constructor(
private deps: RunnerDeps,
- private o: { device: string; port: number; host?: string; clientId: string; access?: "ask" | "blocked" },
+ private o: { device: string; port: number; host?: string; clientId: string; access?: "ask" | "blocked"; slot?: "cpu" },
) {
this.now = deps.now ?? Date.now;
this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -586,6 +629,8 @@ export class ComputerRunner {
/** The files a composed job ticket's graph makes, by task and name: sent from here, never read from the studio. */
private madeOf = new Map<string, Map<string, { data: ArrayBuffer | Uint8Array; contentType: string }>>();
private stoppedDone = new Set<string>();
+ /** The files a finishing job made, by task and name: uploaded from here, never read from ComfyUI. */
+ private finishMade = new Map<string, Map<string, Blob>>();
/**
* Ask for a job and run it (one at a time). True when there was one. Only while ComfyUI here answers to this site: a
@@ -598,7 +643,8 @@ export class ComputerRunner {
// A worker's kept results go up without its ComfyUI (`onlyHeld`); anything else needs ComfyUI answering.
if (!o.onlyHeld && (await this.look()).comfy !== "ok") return false;
const running = this.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => j.taskId);
- 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 }) });
+ // A worker's CPU slot claims for itself (`slot`): its work never waits for its GPU's job, nor holds it up.
+ 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, ...(this.o.slot && { slot: this.o.slot }) }) });
if (res.status !== 200) {
if (res.status === 401) this.stop("signed-out");
if (res.status === 204) await this.deps.worker?.claimed(null, { onlyHeld: !!o.onlyHeld });
@@ -636,12 +682,15 @@ export class ComputerRunner {
await this.runJob(t);
} finally {
this.madeOf.delete(t.id);
+ this.finishMade.delete(t.id);
const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;
if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase)).catch(() => {});
}
}
private async runJob(t: ClaimedTask): Promise<void> {
+ // A finishing job runs with the worker's own code, never on ComfyUI.
+ if (t.finish !== undefined) return this.runFinish(t);
this.promptOf.set(t.id, t.promptId);
this.job(t, { phase: t.resume === "collecting" ? "saving" : t.resume === "running" ? "running" : t.resume === "queued" ? "queued" : "sending" });
try {
@@ -729,6 +778,132 @@ export class ComputerRunner {
}
}
+ /**
+ * A finishing job (src/lib/finish-ticket.ts) on a worker's CPU slot: its ticket checked, its inputs read (each checked
+ * against its SHA-256, a picture made again first), the worker's own code run on them within the run limit, its files
+ * kept before the studio hears of them, then the files the studio asks for uploaded. Results kept from an earlier try
+ * go up without running it again. No ComfyUI is used.
+ */
+ private async runFinish(t: ClaimedTask): Promise<void> {
+ const worker = this.deps.worker;
+ try {
+ const held = worker ? await worker.hold.get(t).catch(() => null) : null;
+ let wanted = t.wanted;
+ let entries: HistoryEntryLike[] | null = held?.entries ?? null;
+ let phase = t.resume ?? "sending";
+ if (held && phase !== "collecting") {
+ 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;
+ phase = "collecting";
+ }
+ if (phase !== "collecting") {
+ if (!this.deps.finish || !worker) {
+ if (worker) await this.giveBack(t, "update-worker");
+ else await this.report(t, { event: "failed", reason: "bad-ticket" });
+ return this.job(t, { phase: "failed" });
+ }
+ if (finishProblem(t.finish, { inputs: t.inputs })) {
+ await this.report(t, { event: "failed", reason: "bad-ticket" });
+ return this.job(t, { phase: "failed" });
+ }
+ this.job(t, { phase: "sending" });
+ // Its inputs, by slot: from the studio, checked against their SHA-256 (a picture made again first).
+ const inputs: Record<string, ArrayBuffer> = {};
+ for (const i of t.finish!.inputs) {
+ const input = t.inputs.find((x) => x.name === i.name);
+ if (!input) {
+ await this.report(t, { event: "failed", reason: "bad-ticket" });
+ return this.job(t, { phase: "failed" });
+ }
+ const read = async (): Promise<ArrayBuffer | TabFailure> => {
+ const res = await this.deps.api("/api/gpu/computer/tasks/" + t.id + "/inputs/" + input.n, { headers: { "X-Fuobe-Lease": t.lease } });
+ if (res.status === 404 || res.status === 409) throw new Stopped();
+ if (res.status === 429) return "input-changed";
+ if (!res.ok) throw new Error("The studio answered HTTP " + res.status + " for a file");
+ const data = await res.arrayBuffer();
+ return (await this.deps.sha256(data)) === input.sha256 ? data : "input-changed";
+ };
+ const got = await worker.input(t, input, read);
+ if (got === "give-back") {
+ await this.giveBack(t, "media");
+ return this.job(t, { phase: "failed" });
+ }
+ if (typeof got === "string") {
+ await this.report(t, { event: "failed", reason: got });
+ return this.job(t, { phase: "failed" });
+ }
+ inputs[i.slot] = got;
+ }
+ if (phase === "sending") await this.report(t, { event: "sent", promptId: t.promptId });
+ await this.report(t, { event: "running", value: 0, max: 100 });
+ this.job(t, { phase: "running", value: 0, max: 100 });
+ // Its run limit: past it, the job goes back in line (the next try has the whole limit again).
+ const ctrl = new AbortController();
+ const limit = t.runLimitMs && t.runLimitMs > 0 ? t.runLimitMs : 20 * 60_000;
+ const started = this.now();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ ctrl.abort();
+ }, limit);
+ let lastAt = 0;
+ const progress = (fraction: number) => {
+ const value = Math.max(0, Math.min(99, Math.round(fraction * 100)));
+ this.job(t, { phase: "running", value, max: 100 });
+ if (this.now() - lastAt < PROGRESS_EVERY_MS * 4) return;
+ lastAt = this.now();
+ void this.report(t, { event: "running", value, max: 100 }).catch(() => null);
+ };
+ let made: FinishMade | { refused: "unsafe-model" | "finish-failed" };
+ try {
+ made = await this.deps.finish(t, inputs, { signal: ctrl.signal, progress }).catch((): { refused: "finish-failed" } => ({ refused: "finish-failed" }));
+ } finally {
+ clearTimeout(timer);
+ }
+ if (!this.alive) throw new Stopped();
+ if (timedOut) {
+ await this.giveBack(t, "run-limit");
+ return this.job(t, { phase: "failed" });
+ }
+ if ("refused" in made) {
+ await this.report(t, { event: "failed", reason: made.refused });
+ return this.job(t, { phase: "failed" });
+ }
+ const results: FinishResult[] = made.files.map((f) => ({ filename: f.name, subfolder: "", type: "output", role: f.role }));
+ const entry: HistoryEntryLike = {
+ status: { status_str: "success", completed: true },
+ outputs: { finish: { results, ...(made.stats && { stats: [made.stats] }), ...(made.turntable && { turntable: [made.turntable] }) } },
+ };
+ const files = new Map(made.files.map((f) => [f.name, new Blob([toArrayBuffer(f.data)], { type: f.contentType })]));
+ this.finishMade.set(t.id, files);
+ const execMs = this.now() - started;
+ // Kept on its disk first: a stop from here on uploads them instead of running the job again.
+ await worker.hold
+ .keep(t, { kind: "finished", entries: [entry], execMs }, async (f) => {
+ const b = files.get(f.filename);
+ return b ? new Response(b) : null;
+ })
+ .catch(() => {});
+ const a = await this.report(t, { event: "finished", entry, execMs: Math.round(execMs) });
+ if (a.stop) throw new Stopped();
+ if (!a.wanted) return this.job(t, { phase: a.state === "done" ? "done" : "failed" });
+ wanted = a.wanted;
+ entries = [entry];
+ }
+ if (!wanted) return;
+ await this.collect(t, wanted, entries ?? [], t.received ?? []);
+ } catch (e) {
+ if (e instanceof Stopped) {
+ if (e.gone) worker?.hold.drop(t.id);
+ return this.job(t, { phase: "failed" });
+ }
+ throw e;
+ }
+ }
+
/**
* The job's graph, or why it is refused. A ticket is composed by the worker's own composer (a runner without one gives
* it back to a worker that has one, or refuses it in a browser). A graph is taken as it is by a browser tab; a worker
@@ -927,6 +1102,8 @@ export class ComputerRunner {
const worker = this.deps.worker;
let lastSent = 0;
let lastKey = "";
+ let lastPreview: Blob | undefined;
+ let lastPreviewAt = -Infinity;
let following: string | undefined;
// A worker's watchdog: when the job last moved (a step, a node, its place, a pass).
let movedAt = this.now();
@@ -1014,11 +1191,19 @@ export class ComputerRunner {
moved(JSON.stringify([w.s, w.s === "pending" ? w.ahead : null, ev?.value, ev?.max, ev?.node, ev?.nodesDone]));
const report: ReportEvent = w.s === "pending" ? { event: "queued", position: w.ahead } : { event: "running", value: ev?.value, max: ev?.max, node: ev?.node, nodesDone: ev?.nodesDone };
const key = JSON.stringify(report);
- if (key !== lastKey && this.now() - lastSent >= PROGRESS_EVERY_MS) {
- const a = await this.report(t, report);
+ // A worker sends its ComfyUI's latest preview with its progress, when the claim asks for one: a small JPEG, at most
+ // one every 2 s.
+ const shown = worker && t.reportPreview && w.s === "running" ? this.view.jobs.find((j) => j.taskId === t.id)?.preview : undefined;
+ // Each preview is tried once (one that can't be sent is never made again).
+ const due = !!shown && shown !== lastPreview && this.now() - lastPreviewAt >= PREVIEW_LIMITS.everyMs && this.now() - lastSent >= PROGRESS_EVERY_MS;
+ const preview = due ? await previewForReport(shown, lastPreviewAt, this.now(), worker?.shrinkPreview?.bind(worker)) : undefined;
+ if (due) lastPreview = shown;
+ if ((key !== lastKey || preview) && this.now() - lastSent >= PROGRESS_EVERY_MS) {
+ const a = await this.report(t, preview && report.event === "running" ? { ...report, preview } : report);
if (a.stop) throw new Stopped();
lastKey = key;
lastSent = this.now();
+ if (preview) lastPreviewAt = this.now();
}
this.job(t, w.s === "pending" ? { phase: "queued", position: w.ahead } : { phase: "running", value: ev?.value, max: ev?.max });
// The socket says when steps move; without it, a read a second.
@@ -1037,8 +1222,9 @@ export class ComputerRunner {
await this.report(t, { event: "failed", reason: "output-missing" });
return this.job(t, { phase: "failed" });
}
- // A worker's kept copy first (its ComfyUI may have restarted since), else ComfyUI's own file.
- const kept = this.deps.worker ? await this.deps.worker.hold.file(t, w).catch(() => null) : null;
+ // A finishing job's own file, then a worker's kept copy (its ComfyUI may have restarted since), else ComfyUI's own file.
+ const made = this.finishMade.get(t.id)?.get(w.filename);
+ const kept = made ?? (this.deps.worker ? await this.deps.worker.hold.file(t, w).catch(() => null) : null);
const res = kept ? null : await this.deps.local(`${this.base}${readPath(viewPath(w))}`, { credentials: "omit", cache: "no-store" }).catch(() => null);
if (!kept && !res?.ok) {
await this.report(t, { event: "failed", reason: "output-missing" });
diff --git a/src/lib/finish-ticket.ts b/src/lib/finish-ticket.ts
new file mode 100644
index 00000000..810bf063
--- /dev/null
+++ b/src/lib/finish-ticket.ts
@@ -0,0 +1,137 @@
+/**
+ * Finishing jobs (docs/gpu-workers.md, "The CPU slot"): CPU work that follows a run on this install's GPUs and runs on
+ * the worker that has a CPU slot, never on the studio's server. Two kinds:
+ *
+ * - "model3d": an image-to-3D model's finish. The worker checks the GLB (a self-contained binary glTF only: no buffer or
+ * picture that names another file), writes the web GLB, and renders a turntable clip and its poster.
+ * - "path": a camera path drawn through a still and its depth picture (the guide of a camera move), as an MP4.
+ *
+ * A finish ticket names its kind, its typed settings and its input files (slot, name, SHA-256). The worker runs it with
+ * its own code (bin/lib/worker/finish.mjs) and sends back only the files its kind makes (FINISH_FILES). Both sides check
+ * a ticket the same way (finishProblem).
+ *
+ * Pure: the server, the worker program and the tests share it.
+ */
+import { INPUT_NAME } from "./relay";
+
+export const FINISH_VERSION = 1;
+
+export const FINISH_KINDS = ["model3d", "path"] as const;
+export type FinishKind = (typeof FINISH_KINDS)[number];
+
+/** The materials the GLB finish knows (scripts/model3d/finish-glb.mjs --material). */
+export const FINISH_MATERIALS = ["auto", "matte", "metal", "mixed"] as const;
+
+/** One key of a camera path (src/lib/camera-path.ts CameraKey). */
+export interface FinishPathKey {
+ t: number;
+ azimuth: number;
+ elevation: number;
+ distance: number;
+ truck?: number;
+}
+
+export interface FinishTicket {
+ v: typeof FINISH_VERSION;
+ kind: FinishKind;
+ /** model3d: { material, turntable }; path: { keys, frames, fps }. */
+ settings: Record<string, unknown>;
+ /** model3d: one "model" (the raw GLB); path: a "photo" and its "depth" picture. */
+ inputs: { slot: string; name: string; sha256: string }[];
+}
+
+/** The input slots each kind takes, in order. */
+export const FINISH_SLOTS: Record<FinishKind, readonly string[]> = { model3d: ["model"], path: ["photo", "depth"] };
+
+/**
+ * The files each kind may send back, by role: their kind on the server and the most each may weigh. The worker names
+ * its results by these roles; any other file is never asked for.
+ */
+export const FINISH_FILES: Record<FinishKind, Record<string, { kind: "model3d" | "video" | "image"; maxBytes: number }>> = {
+ model3d: {
+ web: { kind: "model3d", maxBytes: 300 * 2 ** 20 },
+ turntable: { kind: "video", maxBytes: 256 * 2 ** 20 },
+ poster: { kind: "image", maxBytes: 16 * 2 ** 20 },
+ },
+ path: { path: { kind: "video", maxBytes: 512 * 2 ** 20 } },
+};
+
+/** A path's frames and frame rate: at most this many, and this fast. */
+export const PATH_LIMITS = { maxFrames: 241, maxFps: 60, maxKeys: 64 };
+
+/** The longest a finish may run on a worker (its CPU slot's run limit for a finish). */
+export const FINISH_RUN_MS = 20 * 60_000;
+
+const SHA = /^[0-9a-f]{64}$/;
+const finite = (v: unknown, lo: number, hi: number) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+
+/**
+ * Why a finish ticket can't be used, or null. `inputs`: the files the task sends (name and SHA-256): every input the
+ * ticket names must be one of them, by name and SHA-256.
+ */
+export function finishProblem(t: unknown, o: { inputs?: { name: string; sha256: string }[] } = {}): string | null {
+ if (!t || typeof t !== "object" || Array.isArray(t)) return "not a finish ticket";
+ const k = t as Record<string, unknown>;
+ if (Object.keys(k).some((x) => !["v", "kind", "settings", "inputs"].includes(x))) return "a finish ticket has an unknown field";
+ if (k.v !== FINISH_VERSION) return "another version of finish ticket";
+ if (!(FINISH_KINDS as readonly string[]).includes(String(k.kind))) return "no such finish";
+ const kind = k.kind as FinishKind;
+ const s = k.settings;
+ if (!s || typeof s !== "object" || Array.isArray(s)) return "settings missing";
+ const set = s as Record<string, unknown>;
+ if (kind === "model3d") {
+ if (Object.keys(set).some((x) => x !== "material" && x !== "turntable")) return "a setting isn't one";
+ if (!(FINISH_MATERIALS as readonly string[]).includes(String(set.material))) return "material isn't one";
+ if (typeof set.turntable !== "boolean") return "turntable isn't a yes or no";
+ } else {
+ if (Object.keys(set).some((x) => !["keys", "frames", "fps"].includes(x))) return "a setting isn't one";
+ if (!Number.isInteger(set.frames) || !finite(set.frames, 2, PATH_LIMITS.maxFrames)) return "frames out of range";
+ if (!Number.isInteger(set.fps) || !finite(set.fps, 1, PATH_LIMITS.maxFps)) return "fps out of range";
+ const keys = set.keys;
+ if (!Array.isArray(keys) || keys.length > PATH_LIMITS.maxKeys) return "keys out of range";
+ for (const key of keys) {
+ if (!key || typeof key !== "object" || Array.isArray(key)) return "a key isn't one";
+ const x = key as Record<string, unknown>;
+ if (Object.keys(x).some((f) => !["t", "azimuth", "elevation", "distance", "truck"].includes(f))) return "a key has an unknown field";
+ if (!finite(x.t, 0, 1) || !finite(x.azimuth, -3600, 3600) || !finite(x.elevation, -90, 90) || !finite(x.distance, 0.05, 20)) return "a key is out of range";
+ if (x.truck !== undefined && !finite(x.truck, -20, 20)) return "a key is out of range";
+ }
+ }
+ const inputs = k.inputs;
+ const slots = FINISH_SLOTS[kind];
+ if (!Array.isArray(inputs) || inputs.length !== slots.length) return "inputs don't fit the finish";
+ for (const [i, raw] of inputs.entries()) {
+ if (!raw || typeof raw !== "object") return "an input isn't one";
+ const x = raw as Record<string, unknown>;
+ if (Object.keys(x).some((f) => !["slot", "name", "sha256"].includes(f))) return "an input has an unknown field";
+ if (x.slot !== slots[i]) return "an input is in the wrong slot";
+ if (typeof x.name !== "string" || !INPUT_NAME.test(x.name)) return "an input's name isn't one";
+ if (typeof x.sha256 !== "string" || !SHA.test(x.sha256)) return "an input has no SHA-256";
+ if (o.inputs && !o.inputs.some((y) => y.name === x.name && y.sha256 === x.sha256)) return "an input isn't one the job sends";
+ }
+ return null;
+}
+
+/** A finished finish job's result file, as the worker names it in its report (role: one of FINISH_FILES for its kind). */
+export interface FinishResult {
+ filename: string;
+ subfolder: string;
+ type: "output";
+ role: string;
+}
+
+/** What a model finish measured (scripts/model3d/finish-glb.mjs's JSON line), as far as each is a number or a word. */
+export interface FinishStats {
+ material?: string;
+ triangles?: number;
+ bytesIn?: number;
+ bytesOut?: number;
+}
+
+/**
+ * The finish's own history entry, as the worker reports it in place of ComfyUI's: its results by role, the model's
+ * stats, and the turntable's state ("done", or "skipped: …" when the worker has no browser or ffmpeg for it).
+ */
+export function finishEntry(results: FinishResult[], extra: { stats?: FinishStats; turntable?: string } = {}) {
+ return { status: { status_str: "success", completed: true }, outputs: { finish: { results, ...(extra.stats && { stats: [extra.stats] }), ...(extra.turntable && { turntable: [extra.turntable] }) } } };
+}
diff --git a/src/lib/image-size.ts b/src/lib/image-size.ts
index 48a1390f..bb45164a 100644
--- a/src/lib/image-size.ts
+++ b/src/lib/image-size.ts
@@ -13,6 +13,54 @@ export function imageSize(data: Uint8Array): { width: number; height: number } |
}
}
+/**
+ * The size a picture shows at: its pixel size, turned when its EXIF orientation (a JPEG's) says it is stored on its
+ * side (orientations 5 to 8). Null as for imageSize.
+ */
+export function orientedImageSize(data: Uint8Array): { width: number; height: number } | null {
+ const size = imageSize(data);
+ if (!size) return null;
+ const o = exifOrientation(data);
+ return o !== null && o >= 5 && o <= 8 ? { width: size.height, height: size.width } : size;
+}
+
+/** A JPEG's EXIF orientation (1 to 8), or null when it has none (or isn't a JPEG). */
+export function exifOrientation(b: Uint8Array): number | null {
+ try {
+ if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return null;
+ let o = 2;
+ while (o + 4 < b.length && b[o] === 0xff) {
+ const marker = b[o + 1];
+ if (marker === 0xda || marker === 0xd9) return null;
+ const len = u16be(b, o + 2);
+ if (len < 2) return null;
+ if (marker === 0xe1 && len >= 16 && ascii(b, o + 4, 4) === "Exif") return tiffOrientation(b, o + 10, Math.min(b.length, o + 2 + len));
+ o += 2 + len;
+ }
+ } catch {}
+ return null;
+}
+
+/** The orientation tag (0x0112) of a TIFF header at `start` (an EXIF block), within `end`. */
+function tiffOrientation(b: Uint8Array, start: number, end: number): number | null {
+ const le = ascii(b, start, 2) === "II";
+ if (!le && ascii(b, start, 2) !== "MM") return null;
+ const u16 = (at: number) => (le ? b[at] | (b[at + 1] << 8) : (b[at] << 8) | b[at + 1]);
+ const u32 = (at: number) => (le ? (b[at] | (b[at + 1] << 8) | (b[at + 2] << 16)) + b[at + 3] * 2 ** 24 : u32be(b, at));
+ const ifd = start + u32(start + 4);
+ if (ifd + 2 > end) return null;
+ const n = u16(ifd);
+ for (let i = 0; i < n; i++) {
+ const at = ifd + 2 + i * 12;
+ if (at + 12 > end) return null;
+ if (u16(at) === 0x0112) {
+ const v = u16(at + 8);
+ return v >= 1 && v <= 8 ? v : null;
+ }
+ }
+ return null;
+}
+
const ascii = (b: Uint8Array, o: number, n: number) => String.fromCharCode(...b.subarray(o, o + n));
const u16be = (b: Uint8Array, o: number) => (b[o] << 8) | b[o + 1];
const u16le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8);
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index a76c1bd2..115d1328 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -7,6 +7,7 @@
* Pure (no I/O): the server's checks and the tab's script share it. None of these words reach the UI.
*/
+import type { FinishTicket } from "./finish-ticket";
import type { Ceiling, JobTicket } from "./job-ticket";
/** Where a task is. */
@@ -28,9 +29,11 @@ export interface HistoryEntryLike {
/**
* Why the tab gave up on a task by itself (the server says it in plain words). A worker adds three: its ComfyUI stopped
* twice while running the task ("input-crashed"), a clip or a sound that couldn't be made again ("input-unreadable"),
- * and a job ticket it refused (src/lib/job-ticket.ts), or a graph where a ticket belongs ("bad-ticket").
+ * and a job ticket it refused (src/lib/job-ticket.ts), or a graph where a ticket belongs ("bad-ticket"). A finishing job
+ * (src/lib/finish-ticket.ts) adds two: a 3D model that isn't a self-contained binary glTF ("unsafe-model"), and a finish
+ * that couldn't be made ("finish-failed").
*/
-export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified", "input-crashed", "input-unreadable", "bad-ticket"] as const;
+export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified", "input-crashed", "input-unreadable", "bad-ticket", "unsafe-model", "finish-failed"] as const;
export type TabFailure = (typeof TAB_FAILURES)[number];
/**
@@ -53,8 +56,11 @@ export type ReportEvent =
| { event: "refused"; status: number; body: unknown }
/** Waiting in ComfyUI's queue: how many prompts are before it. */
| { event: "queued"; position: number }
- /** Running: the sampler's steps, and the node. */
- | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }
+ /**
+ * Running: the sampler's steps, and the node. A worker may add its ComfyUI's latest preview (`preview`: a JPEG as
+ * base64, at most PREVIEW_LIMITS.maxBytes, at most one every PREVIEW_LIMITS.everyMs). A larger one is dropped.
+ */
+ | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number; preview?: string }
/**
* 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), its GPU's name (`device`), and `kept` when the
@@ -156,6 +162,15 @@ export interface ClaimedTask {
/** A worker's task: its class in the line ("owner": the owner's own job), and its workflow. */
class?: "paid" | "free" | "owner";
workflowId?: string;
+ /** A worker's task for its CPU slot (light CPU work, or a finishing job): "cpu". Absent: its GPU's. */
+ slot?: "cpu";
+ /** A finishing job (src/lib/finish-ticket.ts), in place of a graph or a job ticket: the worker runs it with its own code. */
+ finish?: FinishTicket;
+ /**
+ * A worker's task whose run shows a live preview: the worker may send its ComfyUI's latest preview with its progress
+ * (PREVIEW_LIMITS). Absent: it sends none (a run whose results are checked before anyone sees them never has it).
+ */
+ reportPreview?: true;
}
/** The tab's facts about its ComfyUI (never its command line: that holds paths and user names). */
@@ -261,6 +276,34 @@ export interface WorkerBeat {
* going quiet during that sleep goes on with no blame: no attempt counted, and this worker may take it again.
*/
slept?: number;
+ /**
+ * Its CPU slot (docs/gpu-workers.md, "The CPU slot"), when it has one: the finishing jobs it runs. Absent or null: no
+ * CPU slot, and its GPU's slot takes light CPU work as before.
+ */
+ cpuSlot?: CpuSlot | null;
+ /** The tasks its CPU slot works on, with where each is (as `running` for its GPU's). */
+ cpuRunning?: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
+}
+
+/** A worker's CPU slot: it takes light CPU work (catalog workflows marked cpu) and these finishing jobs. */
+export interface CpuSlot {
+ finishes: string[];
+}
+
+/**
+ * A worker's live preview in a progress report: a JPEG, at most this big, at most one this often. A larger one is
+ * dropped (the report itself is kept).
+ */
+export const PREVIEW_LIMITS = { maxBytes: 64 * 1024, everyMs: 2000 };
+
+/** A report's preview as kept: base64 of a JPEG of at most PREVIEW_LIMITS.maxBytes, else undefined. */
+export function previewOf(v: unknown): string | undefined {
+ if (typeof v !== "string" || !v || v.length % 4 !== 0 || v.length > Math.ceil(PREVIEW_LIMITS.maxBytes / 3) * 4) return undefined;
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(v)) return undefined;
+ const pad = v.endsWith("==") ? 2 : v.endsWith("=") ? 1 : 0;
+ if ((v.length / 4) * 3 - pad > PREVIEW_LIMITS.maxBytes) return undefined;
+ // A JPEG starts FF D8 FF ("/9j/" in base64).
+ return v.startsWith("/9j/") ? v : undefined;
}
/** Task timings (DESIGN 5.5): the runner lease, how often the tab beats, when a computer counts as gone. */
@@ -454,6 +497,10 @@ export function tabFailureWords(reason: TabFailure, status?: number): string {
return "A clip or sound in this run couldn't be read.";
case "bad-ticket":
return "This run couldn't be made with these settings.";
+ case "unsafe-model":
+ return "This 3D model couldn't be opened for the web, so it is kept as it is.";
+ case "finish-failed":
+ return "This run couldn't finish.";
default:
return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;
}
diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.ts
new file mode 100644
index 00000000..28e4c4e6
--- /dev/null
+++ b/src/server/computer/finish.ts
@@ -0,0 +1,347 @@
+import "server-only";
+import fs from "node:fs";
+import type { OutputFile } from "@/lib/catalog/types";
+import { normalizeKeys } from "@/lib/camera-path";
+import { FINISH_FILES, FINISH_VERSION, finishProblem, PATH_LIMITS, type FinishKind, type FinishPathKey, type FinishStats, type FinishTicket } from "@/lib/finish-ticket";
+import type { HistoryEntryLike, WantedFile } from "@/lib/relay";
+import { accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom } from "../account-files";
+import { db } from "../db";
+import { accountFinishProblem, MODEL_FINISH_VERSION, modelToFinish, OWN_ORBIT, withTurntable } from "../model3d-finish";
+import { getSetting } from "../settings";
+import { absolutePath, deleteAsset, getAsset, readRef, saveFile, type Asset } from "../storage";
+import { tenantAccount } from "../tenant";
+import { cpuSlotOf, poolWaitMs } from "./pool";
+import { createTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type TaskRow } from "./tasks";
+import type { WorkerRow } from "./workers";
+
+/**
+ * Finishing jobs on the workers (docs/gpu-workers.md, "The CPU slot"): the CPU work that follows an account's run on this
+ * install's GPUs runs on a worker's CPU slot, never on this server. Two kinds (src/lib/finish-ticket.ts):
+ *
+ * - "model3d": an image-to-3D model's finish. The worker checks the GLB is self-contained (a buffer or a picture that
+ * names another file is refused there), writes the web GLB, and renders the turntable and its poster. This server
+ * only stores what comes back, on the model output as its own finish does (src/server/model3d-finish.ts).
+ * - "path": a camera path drawn through a still and its depth picture (the guide of a camera move), as an MP4.
+ *
+ * A finishing job is a task for the workers like any other: in the run's class, at the run's place in line, staged and
+ * collected through the same routes, with its own run limit. Only a worker whose CPU slot says it runs that kind takes
+ * it. The owner's own runs, and runs on an account's own GPU or key, keep this server's finish, as before.
+ */
+
+/** The finishing jobs a worker's CPU slot runs (any pool worker not revoked, paused or not: a run then waits in line). */
+export function workersFinish(kind: FinishKind): boolean {
+ if (getSetting("comfyWhere") !== "workers") return false;
+ const rows = db().prepare("SELECT cpu_slot_json FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND pool = 'pool' AND cpu_slot_json IS NOT NULL").all() as Pick<WorkerRow, "cpu_slot_json">[];
+ return rows.some((w) => !!cpuSlotOf(w)?.finishes.includes(kind));
+}
+
+/** A finishing job's ticket as its task keeps it, or null. */
+const ticketOf = (t: Pick<TaskRow, "finish_json">): FinishTicket | null => (t.finish_json ? json<FinishTicket | null>(t.finish_json, null) : null);
+
+/** The latest finishing job of this kind for a run (and step, for a path), or null. */
+export function finishTask(generationId: string, kind: FinishKind, step = 0): TaskRow | null {
+ const rows = db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? AND finish_json IS NOT NULL ORDER BY created_at DESC").all(generationId) as TaskRow[];
+ return rows.find((t) => ticketOf(t)?.kind === kind && (json<{ step?: number }>(t.extra_json, {}).step ?? 0) === step) ?? null;
+}
+
+/** The run's own task on the workers (its class and its place in line), when it had one. */
+const runTask = (generationId: string) =>
+ db().prepare("SELECT class, rank_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND finish_json IS NULL ORDER BY created_at DESC LIMIT 1").get(generationId) as Pick<TaskRow, "class" | "rank_at"> | undefined;
+
+/**
+ * Queue a finishing job for an account's run: its files staged as the account's, its ticket checked as the worker will
+ * check it, in the run's class and at the run's place in line (a job no worker takes within the wait limit fails, not
+ * charged). Returns the task's id.
+ */
+export function queueFinish(o: {
+ kind: FinishKind;
+ generationId: string;
+ account: string;
+ inputs: { slot: string; data: Buffer; contentType: string; name: string }[];
+ settings: Record<string, unknown>;
+ step?: number;
+}): string {
+ const principal = `acct:${o.account}` as const;
+ const inputs = o.inputs.map((i) => {
+ const name = stageInput(principal, i.data, i.contentType, i.name);
+ return { slot: i.slot, name, sha256: stagedInput(principal, name)!.sha256 };
+ });
+ const ticket: FinishTicket = { v: FINISH_VERSION, kind: o.kind, settings: o.settings, inputs };
+ const problem = finishProblem(ticket, { inputs });
+ // Why, for the server's log only: the run says one plain sentence.
+ if (problem) {
+ console.warn(`[fuobe] A finishing job for ${o.generationId} wasn't queued: ${problem}.`);
+ throw new Error("This run couldn't finish.");
+ }
+ const run = runTask(o.generationId);
+ const now = Date.now();
+ const t = createTask({
+ principal,
+ generationId: o.generationId,
+ graph: {},
+ finish: ticket,
+ workflowId: `finish-${o.kind}`,
+ made: o.kind === "model3d" ? "model3d" : "video",
+ ...(o.step !== undefined && { extra: { step: o.step } }),
+ pool: {
+ pools: ["pool"],
+ account: o.account,
+ class: run?.class === "paid" ? "paid" : "free",
+ rankAt: run?.rank_at ?? now,
+ lane: "small",
+ needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },
+ notAfter: now + poolWaitMs(),
+ slot: "cpu",
+ },
+ });
+ return t.id;
+}
+
+/**
+ * A finishing job's finished entry (its results by role): the files to collect, each within its kind's limit and the
+ * room the account's files and the server's disk have. Call it as the task's account (onComputer).
+ */
+export function planFinish(t: Pick<TaskRow, "id" | "finish_json">, entries: HistoryEntryLike[]): FinishedPlan {
+ const ticket = ticketOf(t);
+ const e = entries[0];
+ if (!ticket || !e) return { error: "This run couldn't finish." };
+ if (e.status?.status_str === "error") return { error: "This run couldn't finish." };
+ const out = (e.outputs?.finish ?? {}) as { results?: unknown; stats?: unknown; turntable?: unknown };
+ const roles = FINISH_FILES[ticket.kind];
+ const seen = new Set<string>();
+ const results = (Array.isArray(out.results) ? out.results : []).flatMap((r) => {
+ const x = (r ?? {}) as Record<string, unknown>;
+ const role = typeof x.role === "string" ? x.role : "";
+ if (!(role in roles) || seen.has(role) || typeof x.filename !== "string" || !/^[\w.-]{1,128}$/.test(x.filename) || x.type !== "output" || (x.subfolder ?? "") !== "") return [];
+ seen.add(role);
+ return [{ role, filename: x.filename }];
+ });
+ if (!results.length) return { error: "This run couldn't finish." };
+ const account = tenantAccount();
+ let budget = Math.max(0, diskFreeBytes() - diskFloorBytes());
+ if (account) {
+ if (!diskHasRoom()) return { error: "There's no room to keep this result right now." };
+ budget = Math.min(budget, accountTotalBytes(account) - accountUsage(account).total);
+ }
+ if (budget <= 0) return { error: "There's no room to keep this result right now." };
+ const wanted: WantedFile[] = results.map((r, n) => ({ n, filename: r.filename, subfolder: "", type: "output", kind: roles[r.role].kind, maxBytes: Math.max(1, Math.min(roles[r.role].maxBytes, budget)) }));
+ const stats = Array.isArray(out.stats) && out.stats[0] && typeof out.stats[0] === "object" ? (out.stats[0] as Record<string, unknown>) : {};
+ const turntable = Array.isArray(out.turntable) && typeof out.turntable[0] === "string" ? out.turntable[0].slice(0, 200) : undefined;
+ const kept: FinishStats = {
+ ...(typeof stats.material === "string" && /^[a-z]{1,16}$/.test(stats.material) && { material: stats.material }),
+ ...(Number.isFinite(stats.triangles) && { triangles: Math.max(0, Math.round(Number(stats.triangles))) }),
+ ...(Number.isFinite(stats.bytesIn) && { bytesIn: Math.max(0, Math.round(Number(stats.bytesIn))) }),
+ ...(Number.isFinite(stats.bytesOut) && { bytesOut: Math.max(0, Math.round(Number(stats.bytesOut))) }),
+ };
+ return { wanted, outputs: [{ files: results.map((r, n) => ({ role: r.role, n })), stats: kept, ...(turntable && { turntable }) }], budget };
+}
+
+/** What a finishing job came to: still going, its files by role (with what it measured), or why it ended without them. */
+export type FinishOutcome =
+ | { state: "waiting" }
+ | { state: "done"; files: Record<string, { path: string; contentType?: string }>; stats: FinishStats; turntable?: string }
+ | { state: "failed"; why: string };
+
+export function finishOutcome(t: TaskRow): FinishOutcome {
+ if (t.state === "failed" || t.state === "canceled") return { state: "failed", why: t.error ?? t.state };
+ if (t.state !== "done") return { state: "waiting" };
+ const r = resultOf<{ files?: { role: string; n: number }[]; stats?: FinishStats; turntable?: string }>(t)[0] ?? {};
+ const files: Record<string, { path: string; contentType?: string }> = {};
+ for (const f of r.files ?? []) {
+ const got = receivedFile(t.principal, t.id, f.n);
+ if (got) files[f.role] = got;
+ }
+ return { state: "done", files, stats: r.stats ?? {}, ...(r.turntable && { turntable: r.turntable }) };
+}
+
+// ---------------------------------------------------------------------------
+// The 3D finish of an account's run on this install's GPUs
+
+/** How often a finish waiting on a worker is looked at. */
+const LOOK_MS = 2000;
+
+declare global {
+ var __fuobeWorkerFinish: Map<string, NodeJS.Timeout> | undefined;
+}
+const watching = () => (globalThis.__fuobeWorkerFinish ??= new Map());
+
+/**
+ * The 3D finish of an account's run on this install's GPUs, on a worker's CPU slot (in place of startModelFinish): the
+ * raw GLB goes to the worker, and the web GLB, the turntable and its poster come back. The run stays running meanwhile;
+ * `done` gets the outputs to store (the raw GLB is kept whatever happens). Once a run: a restart finds the same job.
+ */
+export function startWorkerModelFinish(generationId: string, outputs: OutputFile[], o: { op: string; provider: string; account: string; onMessage?: (m: string) => void; done: (outputs: OutputFile[]) => void }): void {
+ if (watching().has(generationId)) return;
+ const i = modelToFinish(o, outputs);
+ if (i < 0) return o.done(outputs);
+ const mesh = outputs[i];
+ const asset = getAsset(mesh.assetId!);
+ if (!asset) return o.done(outputs);
+ const keep = (finish: Record<string, unknown>) => outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, finish: { version: MODEL_FINISH_VERSION, ...finish } } } : x));
+ let task = finishTask(generationId, "model3d");
+ if (!task || task.state === "canceled") {
+ const problem = accountFinishProblem(o.account, asset.size);
+ if (problem) return o.done(keep({ error: `web GLB: ${problem}` }));
+ try {
+ const id = queueFinish({
+ kind: "model3d",
+ generationId,
+ account: o.account,
+ inputs: [{ slot: "model", data: fs.readFileSync(absolutePath(asset.relPath)), contentType: "model/gltf-binary", name: "model.glb" }],
+ // A job that came with an orbit clip of its splat keeps it as the turntable.
+ settings: { material: "auto", turntable: !outputs.some((x) => x.kind === "video" && x.meta?.role === "orbit") },
+ });
+ task = db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;
+ } catch (e) {
+ return o.done(keep({ error: `web GLB: ${(e as Error).message}` }));
+ }
+ }
+ o.onMessage?.("Finishing the 3D model");
+ const id = task.id;
+ const look = () => {
+ const t = db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow | undefined;
+ const r: FinishOutcome = t ? finishOutcome(t) : { state: "failed", why: "gone" };
+ if (r.state === "waiting") return;
+ clearInterval(watching().get(generationId));
+ watching().delete(generationId);
+ if (r.state === "failed") return o.done(keep({ error: `web GLB: ${r.why === "tab:unsafe-model" ? "the model isn't a self-contained GLB, so it is kept as it is" : "the finish didn't come back, so the model is kept as it is"}` }));
+ o.done(storeModelFinish(generationId, outputs, i, r));
+ };
+ const timer = setInterval(look, LOOK_MS);
+ timer.unref?.();
+ watching().set(generationId, timer);
+ look();
+}
+
+/** Stop looking at a run's finish on a worker (the run was canceled or deleted; its task stops with the run). */
+export function stopWorkerFinish(generationId: string): void {
+ clearInterval(watching().get(generationId));
+ watching().delete(generationId);
+}
+
+/**
+ * Is this a binary glTF 2 whose every buffer and picture is inside the file (no URI, or a data: URI)? This server
+ * checks the worker's web GLB again before it keeps it: it reads only the header and the JSON chunk.
+ */
+export function glbSelfContained(b: Buffer): boolean {
+ if (b.length < 20 || b.readUInt32LE(0) !== 0x46546c67 || b.readUInt32LE(4) !== 2 || b.readUInt32LE(16) !== 0x4e4f534a) return false;
+ const len = b.readUInt32LE(12);
+ if (20 + len > b.length) return false;
+ let j: { buffers?: unknown; images?: unknown };
+ try {
+ j = JSON.parse(b.subarray(20, 20 + len).toString("utf8"));
+ } catch {
+ return false;
+ }
+ if (!j || typeof j !== "object") return false;
+ const list = (v: unknown) => (v === undefined ? [] : Array.isArray(v) ? v : null);
+ const parts = [list(j.buffers), list(j.images)];
+ if (parts.some((x) => x === null)) return false;
+ return parts.flat().every((x) => {
+ const uri = (x as { uri?: unknown } | null)?.uri;
+ return uri === undefined || (typeof uri === "string" && uri.startsWith("data:"));
+ });
+}
+
+/** glbSelfContained for a file, reading only its header and its JSON chunk (at most 64 MB of it). */
+export function glbFileSelfContained(file: string): boolean {
+ let fd: number | null = null;
+ try {
+ fd = fs.openSync(file, "r");
+ const head = Buffer.alloc(20);
+ if (fs.readSync(fd, head, 0, 20, 0) < 20) return false;
+ const len = head.readUInt32LE(12);
+ if (len > 64 * 2 ** 20) return false;
+ const all = Buffer.alloc(20 + len);
+ head.copy(all);
+ if (fs.readSync(fd, all, 20, len, 20) < len) return false;
+ return glbSelfContained(all);
+ } catch {
+ return false;
+ } finally {
+ if (fd !== null) fs.closeSync(fd);
+ }
+}
+
+/** The model output with the worker's finish on it: the web GLB, the turntable clip and its poster, stored as the run's. */
+function storeModelFinish(generationId: string, outputs: OutputFile[], i: number, r: Extract<FinishOutcome, { state: "done" }>): OutputFile[] {
+ const mesh = outputs[i];
+ const saved: Asset[] = [];
+ const save = (role: string, contentType: string, name: string, source: "derived" | "generation") => {
+ const f = r.files[role];
+ if (!f) return null;
+ const data = fs.readFileSync(f.path);
+ if (role === "web" && !glbSelfContained(data)) return null;
+ const a = saveFile({ data, contentType, name, source, generationId });
+ saved.push(a);
+ return a;
+ };
+ try {
+ const web = save("web", "model/gltf-binary", "model-web.glb", "derived");
+ if (!web) return outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, finish: { version: MODEL_FINISH_VERSION, error: "web GLB: the finish didn't come back, so the model is kept as it is" } } } : x));
+ const clip = save("turntable", "video/mp4", "turntable.mp4", "generation");
+ const poster = clip ? save("poster", r.files.poster?.contentType ?? "image/webp", "poster.webp", "derived") : null;
+ const ownOrbit = outputs.some((x) => x.kind === "video" && x.meta?.role === "orbit");
+ const turntable = ownOrbit ? OWN_ORBIT : clip ? "done" : (r.turntable ?? "skipped: no turntable");
+ const finish = { version: MODEL_FINISH_VERSION, ...(r.stats.material && { material: r.stats.material }), ...(r.stats.triangles !== undefined && { triangles: r.stats.triangles }), rawBytes: r.stats.bytesIn ?? getAsset(mesh.assetId!)?.size, webBytes: r.stats.bytesOut ?? web.size, webAsset: web.id, turntable };
+ const next = outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, web: web.url, finish } } : x));
+ if (!clip) return next;
+ return withTurntable(next, mesh.assetId!, { state: "done", video: { url: clip.url, kind: "video", contentType: clip.contentType, assetId: clip.id, meta: { role: "turntable", fps: 24, frames: 96 } }, ...(poster && { poster: poster.url }) });
+ } catch (e) {
+ for (const a of saved) deleteAsset(a.id);
+ console.warn(`[fuobe] 3D finish for ${generationId}: ${(e as Error).message}`);
+ return outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, finish: { version: MODEL_FINISH_VERSION, error: "web GLB: the finish couldn't be kept, so the model is kept as it is" } } } : x));
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The camera path of an account's run on this install's GPUs
+
+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
+
+/** A path's keys for a finish ticket: normalized as the path render does, at most PATH_LIMITS.maxKeys, each in range. */
+export function pathKeys(keys: FinishPathKey[]): FinishPathKey[] {
+ return normalizeKeys(keys)
+ .slice(0, PATH_LIMITS.maxKeys)
+ .map((k) => ({ t: k.t, azimuth: clamp(k.azimuth, -3600, 3600), elevation: k.elevation, distance: k.distance, ...(k.truck !== undefined && Number.isFinite(k.truck) && { truck: clamp(k.truck, -20, 20) }) }));
+}
+
+/**
+ * A camera path through a still and its depth picture, drawn on a worker's CPU slot for a step of an account's run on
+ * this install's GPUs (in place of this server's renderPathVideo). Call it as the run (the step's files are read as its
+ * account). The first call queues the job; later calls say where it is, and once it is done, the URL of the clip, kept
+ * as the run's file. `step`: which of the step's inputs it is.
+ */
+export async function pathOnWorker(generationId: string, step: number, input: { photo: string; depth: string; keys: FinishPathKey[]; frames: number; fps: number }): Promise<{ state: "waiting" } | { state: "done"; url: string } | { state: "failed"; error: string }> {
+ const account = tenantAccount();
+ if (!account) return { state: "failed", error: "This run couldn't finish." };
+ const t = finishTask(generationId, "path", step);
+ if (!t || t.state === "canceled") {
+ const [photo, depth] = await Promise.all([readRef(input.photo), readRef(input.depth)]);
+ const id = queueFinish({
+ kind: "path",
+ generationId,
+ account,
+ step,
+ inputs: [
+ { slot: "photo", data: photo.data, contentType: photo.contentType, name: photo.name || "photo.png" },
+ { slot: "depth", data: depth.data, contentType: depth.contentType, name: depth.name || "depth.png" },
+ ],
+ // The keys as the path render reads them (in time order, from the photo's pose, inside their ranges).
+ settings: { keys: pathKeys(input.keys), frames: input.frames, fps: input.fps },
+ });
+ return id ? { state: "waiting" } : { state: "failed", error: "This run couldn't finish." };
+ }
+ const r = finishOutcome(t);
+ if (r.state === "waiting") return r;
+ if (r.state === "failed") return { state: "failed", error: "This run couldn't finish." };
+ const f = r.files.path;
+ if (!f) return { state: "failed", error: "This run couldn't finish." };
+ // Kept once: a later sweep finds the stored file by the task.
+ const kept = json<{ kept?: string }>(t.extra_json, {}).kept;
+ if (kept) return { state: "done", url: kept };
+ const clip = saveFile({ data: fs.readFileSync(f.path), contentType: "video/mp4", name: "path-render.mp4", source: "derived", generationId });
+ const extra = { ...json<Record<string, unknown>>(t.extra_json, {}), kept: clip.url };
+ db().prepare("UPDATE relay_tasks SET extra_json = ? WHERE id = ?").run(JSON.stringify(extra), t.id);
+ return { state: "done", url: clip.url };
+}
diff --git a/src/server/computer/http.ts b/src/server/computer/http.ts
index 8855649c..c6d49d4c 100644
--- a/src/server/computer/http.ts
+++ b/src/server/computer/http.ts
@@ -108,8 +108,10 @@ const textType = (name: string, owner: boolean) => (/\.srt$/i.test(name) ? "appl
/**
* What a result from someone's ComfyUI is, from its first bytes (as an upload's type is: lib/sniff.ts), and whether it
* is what the server asked for. Never a page or a script: a picture that is really HTML is refused. Throws the words.
+ * A 3D model comes only from the owner's own jobs, or as a binary glTF when `o.glb` (a run on the workers whose 3D
+ * finish runs on a worker: the route checks the whole file's parts once it has arrived).
*/
-export function outputType(head: Buffer, w: WantedFile, owner: boolean): string {
+export function outputType(head: Buffer, w: WantedFile, owner: boolean, o: { glb?: boolean } = {}): string {
const s = head.length >= 4 ? sniffMedia(head, undefined, { gif: true }) : null;
switch (w.kind) {
case "image":
@@ -131,7 +133,7 @@ export function outputType(head: Buffer, w: WantedFile, owner: boolean): string
if (!head.includes(0)) return textType(w.filename, owner);
break;
case "model3d":
- if (owner && head.subarray(0, 4).toString("latin1") === "glTF") return "model/gltf-binary";
+ if ((owner || o.glb) && head.subarray(0, 4).toString("latin1") === "glTF") return "model/gltf-binary";
if (owner && /^ply\r?\n/.test(head.subarray(0, 8).toString("latin1"))) return "model/ply";
break;
}
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 2453acb0..9facc4b1 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -1,8 +1,9 @@
import "server-only";
import crypto from "node:crypto";
+import { FINISH_KINDS, FINISH_RUN_MS, type FinishTicket } from "@/lib/finish-ticket";
import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";
import { allLanes, laneLabel, lanesFor, MEDIA_KINDS, needsOf, type Inventory, type Needs } from "@/lib/lanes";
-import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";
+import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
@@ -25,6 +26,11 @@ import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRo
* every input against its rules, and keeps its ComfyUI behind the guard. An older one is told to update.
*/
export const MIN_PROTOCOL = 2;
+/**
+ * The oldest worker program that takes an account's job ticket: 3 makes every picture again from its pixels before its
+ * 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;
/** 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. */
@@ -63,7 +69,7 @@ export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.c
*/
const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;
/** The columns the line's counts read (never a task's graph or files). */
-const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json";
+const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json, slot, finish_json";
/**
* A task a worker took that is still sending its files to its ComfyUI this long after the claim (or after its ComfyUI lost
* it and it began sending them again on the same claim) goes back in line.
@@ -89,6 +95,43 @@ const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
const MAX_RUNNING = 32;
+// ---------------------------------------------------------------------------
+// The CPU slot (docs/gpu-workers.md): a worker may run one CPU task beside its GPU job
+
+/** A worker's two slots: its GPU's (the jobs that use its GPU) and its CPU slot's (light CPU work, finishing jobs). */
+export type WorkerSlot = "gpu" | "cpu";
+
+/** The device a worker's slot takes its tasks under: its GPU's `wkr-<id>`, its CPU slot's `wkr-<id>-cpu`. */
+export const slotDevice = (w: Pick<WorkerRow, "id">, slot: WorkerSlot = "gpu") => (slot === "cpu" ? `wkr-${w.id}-cpu` : `wkr-${w.id}`);
+
+/** A worker's CPU slot as its last beat said (null: it has none, and its GPU's slot takes light CPU work as before). */
+export function cpuSlotOf(w: Pick<WorkerRow, "cpu_slot_json">): CpuSlot | null {
+ const s = w.cpu_slot_json ? json<CpuSlot | null>(w.cpu_slot_json, null) : null;
+ return s && Array.isArray(s.finishes) ? s : null;
+}
+
+/** A CPU slot as a beat may say it: the finishing jobs it runs, known kinds only. */
+function cleanCpuSlot(v: unknown): CpuSlot | null {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
+ const f = (v as { finishes?: unknown }).finishes;
+ return { finishes: Array.isArray(f) ? FINISH_KINDS.filter((k) => f.includes(k)) : [] };
+}
+
+/** A finishing job's kind (src/lib/finish-ticket.ts), or null for any other task. */
+const finishKind = (t: Pick<TaskRow, "finish_json">): string | null => (t.finish_json ? (json<FinishTicket | null>(t.finish_json, null)?.kind ?? "?") : null);
+
+/**
+ * The slot of this worker that takes a task: a finishing job always its CPU slot; light CPU work (a task marked "cpu")
+ * its CPU slot when it has one, else its GPU's slot, as before; anything else its GPU's.
+ */
+export function slotFor(t: Pick<TaskRow, "slot" | "finish_json">, w: Pick<WorkerRow, "cpu_slot_json">): WorkerSlot {
+ if (t.finish_json) return "cpu";
+ return t.slot === "cpu" && cpuSlotOf(w) ? "cpu" : "gpu";
+}
+
+/** The run limit of a task in a CPU slot: its lane's run ceiling, never more than a finishing job's. */
+const cpuRunLimitMs = (t: Pick<TaskRow, "lane">) => Math.min(FINISH_RUN_MS, runCeilingMs(t.lane));
+
// ---------------------------------------------------------------------------
// What a worker is now
@@ -142,7 +185,7 @@ 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)) return { state: "update-worker", words: "Update the worker: it takes only your own jobs until then" };
+ 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" };
return { state: "idle", words: "Ready" };
}
@@ -195,6 +238,8 @@ export function cleanBeat(b: unknown): WorkerBeat {
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) : [],
...((num(o.slept) ?? 0) > 0 && { slept: Math.min(num(o.slept)!, MAX_SLEPT_MS) }),
+ cpuSlot: cleanCpuSlot(o.cpuSlot),
+ cpuRunning: Array.isArray(o.cpuRunning) ? (o.cpuRunning.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],
};
}
@@ -213,17 +258,20 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
const facts = b.facts ? { ...b.facts, loras: undefined } : undefined;
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 = ? WHERE id = ?`,
- ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, b.catalogVersion ?? null, b.ceiling ? JSON.stringify(b.ceiling) : null, w.id);
+ warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ? WHERE id = ?`,
+ ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, b.catalogVersion ?? null, b.ceiling ? JSON.stringify(b.ceiling) : null, b.cpuSlot ? JSON.stringify(b.cpuSlot) : null, w.id);
// Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.
if (b.slept) forgiveSleep(w, b.slept, now);
- for (const r of b.running) {
+ // The tasks of both its slots stay alive, with their progress.
+ for (const r of [...b.running, ...(b.cpuRunning ?? [])]) {
const t = typeof r?.task === "string" ? (d.prepare("SELECT * FROM relay_tasks WHERE id = ? AND worker_id = ?").get(r.task, w.id) as TaskRow | undefined) : undefined;
if (!t || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
setTask(t.id, { device_seen_at: now });
noteProgress(t.id, r as unknown as Record<string, unknown>, now);
}
for (const id of b.stopped) d.prepare("UPDATE relay_tasks SET stop = 0 WHERE id = ? AND device = ?").run(id, device);
+ // A task its CPU slot held that ended with a stop: the CPU slot heard it in its reports and emptied its ComfyUI then.
+ d.prepare("UPDATE relay_tasks SET stop = 0 WHERE device = ? AND stop = 1 AND state IN ('done','failed','canceled')").run(slotDevice(w, "cpu"));
const stops = (d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE device = ? AND stop = 1").all(device) as { id: string; prompt_id: string; prefix: string | null }[]).map((s) => ({
task: s.id,
promptId: s.prompt_id,
@@ -235,7 +283,10 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
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 ?? []);
+ // Another program on its GPU stops only its GPU's job: its CPU slot's task needs no GPU, and goes on.
+ const gpuOnly = !fresh.stop_now && b.local.why !== "here-now";
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 (gpuOnly && t.device === slotDevice(w, "cpu")) continue;
// 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;
@@ -290,7 +341,8 @@ export function claimableNow(w: WorkerRow, now = Date.now()): number {
const rows = db()
.prepare(`SELECT ${LINE_COLS} 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 ${LINE_ORDER} 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;
+ // Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room.
+ return rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;
}
// ---------------------------------------------------------------------------
@@ -363,28 +415,31 @@ export function inventoryHash(inv: Inventory): string {
const LOOK_AT = 200;
/**
- * A worker asks for work, inside one transaction: first a task it had and lost track of; then, if it holds none and may
- * take work, the best waiting task it can run (its pool, its allowed lanes and their delays, the files and VRAM it
- * needs, the retry rule, and the end of its hours). One task at a time: a worker that holds a task gets nothing new
- * until that one ends or goes back in line, so one worker's token never holds more than one person's job. Sticky
- * lanes: its warm lane goes first until another lane's best task has waited longer than switch_after_ms (and is older).
+ * A worker asks for work for one of its slots (its GPU's, or its CPU slot: `slot`), inside one transaction: first a task
+ * that slot had and lost track of; then, if the slot holds none and the worker may take work, the best waiting task that
+ * slot can run (its pool, its allowed lanes and their delays, the files and VRAM it needs, the retry rule, and the end of
+ * its hours). One task at a time in each slot: a slot that holds a task gets nothing new until that one ends or goes back
+ * in line, so one worker's token never holds more than one person's GPU job and one CPU task. Sticky lanes: its warm
+ * lane goes first until another lane's best task has waited longer than switch_after_ms (and is older).
*/
-export function workerClaim(w: WorkerRow, running: string[], now = Date.now()): ClaimedTask | null {
+export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), slot: WorkerSlot = "gpu"): ClaimedTask | null {
const d = db();
- const device = `wkr-${w.id}`;
+ const device = slotDevice(w, slot);
return d.transaction((): ClaimedTask | null => {
sweepPool(now);
const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+ // A worker with no CPU slot (as its last beat said) has nothing to claim for one.
+ if (slot === "cpu" && !cpuSlotOf(fresh)) return null;
const held = d.prepare(`SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY ${LINE_ORDER}`).all(fresh.id, device) as TaskRow[];
const mine = held.find((t) => !running.includes(t.id));
- if (mine) return claimed(mine, fresh, device, now);
+ if (mine) return claimed(mine, fresh, device, now, slot);
if (held.length || !eligible(fresh, now)) return null;
- const t = pick(fresh, now);
- return t ? claimed(t, fresh, device, now) : null;
+ const t = pick(fresh, now, slot);
+ return t ? claimed(t, fresh, device, now, slot) : null;
}).immediate();
}
-function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {
+function claimed(t: TaskRow, w: WorkerRow, device: string, now: number, slot: WorkerSlot = "gpu"): ClaimedTask {
const needs = json<Needs | null>(t.needs_json, null);
const bench = t.lane ? benchOf(w)[t.lane] : undefined;
if (t.state === "waiting") logWorkerJob("claimed", t, w.id, now);
@@ -396,8 +451,9 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed
const c = takeTask(t, device, now, { worker_id: w.id, ...before, ...(t.state !== "waiting" && t.device === device && t.claimed_at && { claimed_at: t.claimed_at }) });
// 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.
- const limit = runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs);
- const stall = stallLimitMs(t.lane);
+ // A CPU slot's task has the CPU slot's own run limit (a finishing job's at most).
+ const limit = slot === "cpu" ? cpuRunLimitMs(t) : runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs);
+ const stall = Math.min(stallLimitMs(t.lane), limit);
return {
...c,
// A job ticket carries its run and stall limits too.
@@ -433,6 +489,8 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
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'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;
if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return false;
const vram = factsOf(w).vramBytes ?? 0;
@@ -441,12 +499,26 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
return true;
}
+/**
+ * May this slot of this worker run this task: a finishing job only in a CPU slot that says it runs that kind (in the
+ * task's pools, for its worker when it names one); light CPU work in its CPU slot when it has one, else in its GPU's
+ * slot; anything else only in its GPU's slot. Then `fits` as for any task.
+ */
+function fitsSlot(t: TaskRow, w: WorkerRow, now: number, slot: WorkerSlot): boolean {
+ if (slotFor(t, w) !== slot) return false;
+ const kind = finishKind(t);
+ if (kind === null) return fits(t, w, now);
+ if (!(t.pools ?? "").split(",").includes(w.pool) || (t.only_worker && t.only_worker !== w.id) || t.stop) return false;
+ if (refusedBy(t).includes(refusalKey(w))) return false;
+ return !!cpuSlotOf(w)?.finishes.includes(kind);
+}
+
/** The retry rule: a worker that lost or failed this task takes it again only when no other capable worker is about. */
function retryOk(t: TaskRow, w: WorkerRow, now: number): boolean {
const tried = json<string[]>(t.tried_json, []);
if (!tried.includes(w.id)) return true;
const others = db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND id != ? AND seen_at > ?").all(w.id, now - RETRY_WINDOW_MS) as WorkerRow[];
- return !others.some((o) => !tried.includes(o.id) && fits(t, o, now + RETRY_WINDOW_MS));
+ return !others.some((o) => !tried.includes(o.id) && fitsSlot(t, o, now + RETRY_WINDOW_MS, slotFor(t, o)));
}
/** Near the end of its hours, only a task that ends before they do. */
@@ -461,16 +533,17 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
* the best one, in the same class, while the best one has waited less than the pick allowance (the install's setting,
* capped by this worker's switch_after_ms; 0: strict order).
*/
-function pick(w: WorkerRow, now: number): TaskRow | null {
+function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): TaskRow | null {
const settings = queueSettings(now);
+ // A CPU slot looks only at the tasks marked for one.
const rows = db()
- .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ORDER BY ${LINE_ORDER} LIMIT ?`)
+ .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slot === "cpu" ? "AND slot = 'cpu' " : ""}ORDER BY ${LINE_ORDER} LIMIT ?`)
.all(`,${w.pool},`, LOOK_AT) as TaskRow[];
- const ok = lineOrder(rows, settings.fairShare).filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
+ const ok = lineOrder(rows, settings.fairShare).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
if (!ok.length) return null;
const best = ok[0];
const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
- if (allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return best;
+ if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return best;
const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === classRank(best));
return warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best;
}
@@ -720,20 +793,23 @@ function estFor(t: Pick<TaskRow, "lane" | "est_ms">, workers: WorkerRow[], typic
export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaSeconds: number | null } {
const d = db();
const all = poolWorkers().filter((w) => sharePool({ pools: w.pool }, t));
- const workers = all.filter((w) => eligible(w, now) && fits({ ...t, created_at: 0 }, w, now));
+ // Each worker serves a task in one of its slots (slotFor): a slot's own line is the tasks that slot would take.
+ const serves = (x: TaskRow, w: WorkerRow) => fitsSlot({ ...x, created_at: 0 }, w, now, slotFor(t, w));
+ const workers = all.filter((w) => eligible(w, now) && serves(t, w));
const before = lineBefore(t, now);
- // Ahead of it: a task the same workers would serve first (with none able to run it now, any that could run it at all).
- const able = workers.length ? workers : all.filter((w) => fits({ ...t, created_at: 0 }, w, now));
- const ahead = before.filter((x) => sharePool(x, t) && (!able.length || able.some((w) => fits({ ...x, created_at: 0 }, w, now))));
+ // Ahead of it: a task the same slots of the same workers would serve first (with none able to run it now, any that
+ // could run it at all).
+ const able = workers.length ? workers : all.filter((w) => serves(t, w));
+ const ahead = before.filter((x) => sharePool(x, t) && (!able.length || able.some((w) => serves(x, w))));
if (!workers.length) return { place: ahead.length + 1, etaSeconds: null };
const typical = memo(typicalPoolMs);
const own = estFor(t, workers, typical);
const warm = workers.some((w) => w.warm_lane === t.lane);
const load = warm ? 0 : Math.max(0, ...workers.map((w) => (t.lane && benchOf(w)[t.lane]?.loadMs) || 0));
const sum = ahead.reduce((s, x) => s + estFor(x, workers, typical), 0);
- // The jobs these workers hold now: what is left of each.
- const ids = new Set(workers.map((w) => w.id));
- const running = (d.prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state IN ('sending','queued','running','collecting') AND worker_id IS NOT NULL`).all() as TaskRow[]).filter((x) => ids.has(x.worker_id!));
+ // The jobs these workers' slots hold now: what is left of each.
+ const devices = new Set(workers.map((w) => slotDevice(w, slotFor(t, w))));
+ const running = (d.prepare(`SELECT ${LINE_COLS}, device FROM relay_tasks WHERE pools IS NOT NULL AND state IN ('sending','queued','running','collecting') AND worker_id IS NOT NULL`).all() as TaskRow[]).filter((x) => !!x.device && devices.has(x.device));
const left = running.reduce((s, x) => s + Math.max(0, estFor(x, workers, typical) - (now - (x.claimed_at ?? now))), 0);
return { place: ahead.length + 1, etaSeconds: Math.round(((sum + left) / workers.length + load + own) / 1000) };
}
@@ -839,9 +915,9 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
const lane = workflowId ? poolLane(workflowId) : null;
const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;
// A new run of a person's, in the free class (a paid run's head start is the billing service's to price, not to quote).
- const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null } as unknown as TaskRow;
+ const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;
const p = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };
- const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fits({ ...probe, created_at: 0 }, w, now))).length;
+ const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fitsSlot({ ...probe, created_at: 0 }, w, now, slotFor(probe, w)))).length;
return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null };
}
@@ -862,6 +938,8 @@ export function poolFields(
const lane = poolLane(workflowId);
return {
pools: ["pool"],
+ // Light CPU work (the requirements index marks the workflow cpu) goes to a worker's CPU slot when it has one.
+ ...(cpuWorkflow(workflowId) && { slot: "cpu" as const }),
account: o.account,
class: o.class ?? (o.account ? ("free" as const) : ("owner" as const)),
// A head start is only inside a class, and never more than a day.
@@ -873,6 +951,14 @@ export function poolFields(
};
}
+/**
+ * Is a workflow light CPU work: the requirements index marks it `cpu` (no model file, no graphics memory, no card its
+ * nodes need: a join, a trim, adding sound, a Ken Burns move, a filter).
+ */
+export function cpuWorkflow(workflowId: string): boolean {
+ return (loadIndex().workflows as Record<string, { cpu?: boolean } | undefined>)[workflowId]?.cpu === true;
+}
+
/** The queue block for GET /api/generations/<id>: the task's place in its lane and the estimated wait. Null when no pool task waits. */
export function queueOfGeneration(generationId: string, now = Date.now()): { place: number; etaSeconds: number | null } | null {
const t = db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state = 'waiting' LIMIT 1").get(generationId) as TaskRow | undefined;
@@ -915,6 +1001,8 @@ export interface WorkerView {
/** What its PC may ever run (null: no ceiling of its own), and the allowed lanes inside it. */
ceiling: Ceiling | null;
lanesInside: string[];
+ /** Its CPU slot (light CPU work and the finishing jobs it runs), as its last beat said; null: none. */
+ cpuSlot: CpuSlot | null;
/** The catalog version its build composes job tickets for, and whether it is this studio's (else: update the worker). */
catalogVersion: string | null;
catalogCurrent: boolean;
@@ -951,6 +1039,7 @@ export function workerView(w: WorkerRow, now = Date.now()): WorkerView {
lanes: capableOf(w).lanes,
ceiling: ceilingOf(w),
lanesInside: lanesInside(Object.keys(allowOf(w)), ceilingOf(w)),
+ cpuSlot: cpuSlotOf(w),
catalogVersion: w.catalog_version ?? null,
catalogCurrent: catalogCurrent(w),
facts: factsOf(w),
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 0ef489c7..d0564d73 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -22,7 +22,9 @@ import {
type ReportEvent,
type TaskInput,
type WantedFile,
+ previewOf,
} from "@/lib/relay";
+import type { FinishTicket } from "@/lib/finish-ticket";
import type { JobTicket } from "@/lib/job-ticket";
import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";
import { runCeilingMs } from "../queue-settings";
@@ -63,11 +65,19 @@ export interface Progress {
node?: string;
nodesDone?: number;
position?: number;
+ /** A worker's latest live preview (a JPEG as base64, src/lib/relay.ts PREVIEW_LIMITS), and when it came. */
+ preview?: string;
+ previewAt?: number;
at: number;
}
const progressMap = () => (globalThis.__fuobeRelayProgress ??= new Map());
export const taskProgress = (id: string): Progress | undefined => progressMap().get(id);
+/** A task's latest live preview from its worker: a JPEG (at most 64 KB) and when it came, or null. */
+export function taskPreview(id: string): { jpeg: Buffer; at: number } | null {
+ const p = progressMap().get(id);
+ return p?.preview ? { jpeg: Buffer.from(p.preview, "base64"), at: p.previewAt ?? p.at } : null;
+}
/** The relay's tables are made with the database (db.ts RELAY_TABLES). */
const rdb = () => db();
@@ -82,6 +92,10 @@ export interface TaskRow {
graph_json: string | null;
/** An account's task for workers: its job ticket (src/lib/job-ticket.ts), in place of a graph (graph_json is NULL). */
ticket_json?: string | null;
+ /** A finishing job for a worker's CPU slot (src/lib/finish-ticket.ts), in place of a graph (graph_json is NULL). */
+ finish_json?: string | null;
+ /** The worker slot that takes it: "cpu" (light CPU work, a finishing job), or NULL (its GPU's). */
+ slot?: string | null;
prompt_id: string;
prefix: string | null;
meta_batch: number;
@@ -315,6 +329,8 @@ export interface NewTask {
* inputs the ticket names.
*/
ticket?: JobTicket;
+ /** A finishing job (src/lib/finish-ticket.ts): no graph and no ticket; the worker's CPU slot runs it with its own code. */
+ finish?: FinishTicket;
prefix?: string;
metaBatch?: boolean;
preview?: boolean;
@@ -325,8 +341,10 @@ export interface NewTask {
loras?: { file: string; url?: string }[];
/** How many results its workflow says one job makes (an owner's job keeps no more than that, and at least 16). */
outputs?: number;
+ /** More to keep with it (a finishing job's step). */
+ extra?: Record<string, unknown>;
/** For workers (pool.ts): the pools that may take it, and what they need to. */
- pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string };
+ pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string; slot?: "cpu" };
}
/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */
@@ -335,24 +353,24 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
const promptId = crypto.randomUUID();
const now = Date.now();
const d = rdb();
- const named = t.ticket ? new Set(t.ticket.inputs.map((i) => i.name)) : graphStrings(t.graph);
+ const named = t.finish ? new Set(t.finish.inputs.map((i) => i.name)) : t.ticket ? new Set(t.ticket.inputs.map((i) => i.name)) : graphStrings(t.graph);
d.transaction(() => {
const pool = t.pool;
d.prepare(
`INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,
- account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json)
- VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json, finish_json, slot)
+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
id,
t.principal,
t.generationId,
- t.ticket ? null : JSON.stringify(t.graph),
+ t.ticket || t.finish ? null : JSON.stringify(t.graph),
promptId,
t.prefix ?? null,
t.metaBatch ? 1 : 0,
t.preview ? 1 : 0,
t.workflowId ?? null,
- JSON.stringify({ made: t.made, loras: t.loras ?? [], ...(t.outputs && { outputs: t.outputs }) }),
+ JSON.stringify({ ...t.extra, made: t.made, loras: t.loras ?? [], ...(t.outputs && { outputs: t.outputs }) }),
now,
now,
pool?.account ?? null,
@@ -365,6 +383,8 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
pool?.onlyWorker ?? null,
pool ? (pool.class ?? (pool.account ? "free" : "owner")) : null,
t.ticket ? JSON.stringify(t.ticket) : null,
+ t.finish ? JSON.stringify(t.finish) : null,
+ pool?.slot ?? null,
);
const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];
let n = 0;
@@ -501,7 +521,16 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beat
return { runner: free, heldElsewhere: !free && elsewhere, waiting, stops };
}
-export function noteProgress(id: string, r: Record<string, unknown>, now: number) {
+/**
+ * Does a worker's task show live previews: a task on the workers whose run asked for previews, that isn't a finishing
+ * job, and whose results aren't checked before anyone sees them.
+ */
+export function showsPreview(t: Pick<TaskRow, "pools" | "preview" | "finish_json" | "extra_json">): boolean {
+ return !!t.pools && !!t.preview && !t.finish_json && !json<{ checkOutputs?: boolean }>(t.extra_json, {}).checkOutputs;
+}
+
+/** Keep a task's live progress. A preview is kept only from a progress report (`o.preview`), never from a beat. */
+export function noteProgress(id: string, r: Record<string, unknown>, now: number, o: { preview?: boolean } = {}) {
const p: Progress = { at: now };
for (const k of ["value", "max", "nodesDone", "position"] as const) {
const v = nonNeg(r[k]);
@@ -509,6 +538,9 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
}
const node = str(r.node, 64);
if (node) p.node = node;
+ // A worker's live preview: a JPEG of at most 64 KB (previewOf); a larger one, or anything else, is dropped.
+ const preview = o.preview ? previewOf(r.preview) : undefined;
+ if (preview) Object.assign(p, { preview, previewAt: now });
progressMap().set(id, { ...progressMap().get(id), ...p });
}
@@ -556,14 +588,19 @@ export function takeTask(t: TaskRow, device: string, now: number, fields: Partia
const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
// An account's task for workers hands out its job ticket, never a graph (src/lib/job-ticket.ts).
const ticket = t.ticket_json ? json<JobTicket | null>(t.ticket_json, null) : null;
+ // A finishing job hands out its finish ticket (src/lib/finish-ticket.ts): no graph and no job ticket.
+ const finish = t.finish_json ? json<FinishTicket | null>(t.finish_json, null) : null;
return {
id: t.id,
generationId: t.generation_id,
lease,
- ...(ticket ? { ticket } : { graph: json(t.graph_json, {}) }),
+ ...(finish ? { finish } : ticket ? { ticket } : { graph: json(t.graph_json, {}) }),
+ ...(t.slot === "cpu" && { slot: "cpu" as const }),
...(t.pools && { class: (t.class === "paid" || t.class === "owner" ? t.class : t.class === "free" || t.account ? "free" : "owner") as "paid" | "free" | "owner", ...(t.workflow_id && { workflowId: t.workflow_id }) }),
promptId: t.prompt_id,
preview: !!t.preview,
+ // A worker sends live previews only of a run that shows them: never of one whose results are checked first.
+ ...(showsPreview(t) && { reportPreview: true as const }),
...(t.prefix && { prefix: t.prefix }),
...(t.meta_batch && { metaBatch: true }),
inputs,
@@ -691,7 +728,8 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
return { ok: true };
case "running":
setTask(t.id, { ...seen, state: "running", ...(!t.started_at && { started_at: now }), note: null });
- noteProgress(t.id, { ...e, position: undefined }, now);
+ // A live preview only from the attempt that holds the lease, for a run that shows them.
+ noteProgress(t.id, { ...e, position: undefined }, now, { preview: showsPreview(t) });
return { ok: true };
case "finished":
case "passes": {
@@ -923,7 +961,7 @@ export function sweepRelay(now = Date.now()): { inputs: number; tasks: number }
.all(now - RELAY_TIMES.keepMs) as { id: string; finished_at: number | null }[];
for (const t of ended) {
fs.rmSync(taskDir(t.id), { recursive: true, force: true });
- d.prepare("UPDATE relay_tasks SET graph_json = NULL, ticket_json = NULL WHERE id = ?").run(t.id);
+ d.prepare("UPDATE relay_tasks SET graph_json = NULL, ticket_json = NULL, finish_json = NULL WHERE id = ?").run(t.id);
}
const old = d.prepare("DELETE FROM relay_tasks WHERE state IN ('done','failed','canceled') AND finished_at < ?").run(now - RELAY_TIMES.keepMs);
return { inputs: stale.length, tasks: old.changes };
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index 58d5016d..ae589f4a 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -73,6 +73,8 @@ export interface WorkerRow {
catalog_version?: string | null;
/** What its PC may ever run (worker.json `ceiling`), as its last beat said. NULL: no ceiling of its own. */
ceiling_json?: string | null;
+ /** Its CPU slot (src/lib/relay.ts CpuSlot), as its last beat said. NULL: none. */
+ cpu_slot_json?: 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 894f5f11..25fd8e1a 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1021,6 +1021,11 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_tasks", "ticket_json", "TEXT"],
["relay_workers", "catalog_version", "TEXT"],
["relay_workers", "ceiling_json", "TEXT"],
+ // The CPU slot (docs/gpu-workers.md): a task for a worker's CPU slot ("cpu"; NULL: its GPU's), a finishing job's
+ // ticket (src/lib/finish-ticket.ts), and the CPU slot a worker's last beat said it has (NULL: none).
+ ["relay_tasks", "slot", "TEXT"],
+ ["relay_tasks", "finish_json", "TEXT"],
+ ["relay_workers", "cpu_slot_json", "TEXT"],
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 9d36264d..47485e37 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -98,6 +98,8 @@ import { renderPathVideo } from "./path-render";
import { songFormat, songToolProblem } from "@/lib/lyrics";
import { hostedUntested } from "@/lib/catalog/hosted-untested";
import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
+import { pathOnWorker, startWorkerModelFinish, stopWorkerFinish, workersFinish } from "./computer/finish";
+import { PATH_FPS, PATH_FRAMES } from "@/lib/camera-path";
import { cropPicture, isCropWindow } from "./crop-picture";
import { convertMask, decodePng, encodePng } from "./png";
import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";
@@ -541,7 +543,7 @@ export const ASSET_FREE: Record<string, string> = {
"assist_connectors.tools_json": "the tool names a connector is limited to",
"relay_runners.facts_json": "what a person's computer said about its ComfyUI: its GPU, memory, version and LoRA names",
"relay_tasks.graph_json": "the graph a person's computer runs: file names on that computer's ComfyUI, never a Fuobe file",
- "relay_tasks.extra_json": "the run's LoRA names and where they download from, as its generation's request has them (which keeps them)",
+ "relay_tasks.extra_json": "the run's LoRA names and where they download from, as its generation's request has them (which keeps them); a finished camera path's clip, which the next step's request keeps too",
"relay_tasks.wanted_json": "the results asked of a person's computer: file names on its ComfyUI",
"relay_tasks.received_json": "how much of each result has arrived",
"relay_tasks.result_json": "the finished entry a person's ComfyUI reported: its own file names",
@@ -549,6 +551,7 @@ export const ASSET_FREE: Record<string, string> = {
"relay_tasks.needs_json": "what a job for the workers needs: workflow, model file names and sizes, node packs, VRAM",
"relay_tasks.tried_json": "the ids of the workers that lost or failed this job",
"relay_tasks.ticket_json": "an account's job ticket for the workers: settings, and the names and SHA-256 of the job's own staged inputs",
+ "relay_tasks.finish_json": "a finishing job's ticket for a worker's CPU slot: settings, and the names and SHA-256 of the job's own staged inputs",
"relay_workers.facts_json": "what a worker said about its ComfyUI: its GPU, memory and version",
"relay_workers.inventory_json": "a worker's model files and node packs: names, sizes and hashes on that PC",
"relay_workers.lanes_json": "the lanes a worker can run: hashes of model file names",
@@ -557,6 +560,7 @@ export const ASSET_FREE: Record<string, string> = {
"relay_workers.allow_json": "the lanes the owner lets a worker run, with their delays",
"relay_workers.seen_json": "the countries and network hashes a worker's token was used from",
"relay_workers.ceiling_json": "the most a worker's PC may run: lanes, workflow ids and sizes",
+ "relay_workers.cpu_slot_json": "the kinds of finishing job a worker's CPU slot runs",
"relay_pairings.facts_json": "what a paired ComfyUI said about itself: its name, GPU and version",
};
@@ -603,6 +607,7 @@ export function assetInUse(assetId: string, exceptGeneration = ""): boolean {
export function deleteGeneration(id: string): void {
// A 3D job's finish or turntable render stops with it.
stopModelFinish(id);
+ stopWorkerFinish(id);
const assets = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(id) as { id: string }[];
db().transaction(() => {
db().prepare("DELETE FROM generations WHERE id = ?").run(id);
@@ -1092,9 +1097,10 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =
const catalogModel = getModel(original.modelId);
const found = catalogModel && offeredFor(catalogModel, original.engine);
const shotModel = found && dualEngine(found) ? onEngine(found, engineFor(found, original.engine)) : found;
- // An account's 3D model is finished on this server under its own limits (model3d-finish.ts); on this install's GPUs it isn't offered yet.
- // Any Angle's 3D view is the exception: a splat and its turntable, nothing to finish here.
- if (original.account && original.place === "pool" && shotModel?.kind === "model3d" && shotModel.id !== ANY_ANGLE.buildModel) throw new Error(OWN_GPU_TOOL_MESSAGE);
+ // An account's 3D model is finished on this server under its own limits (model3d-finish.ts). On this install's GPUs it
+ // is finished on a worker's CPU slot (computer/finish.ts): offered only while a worker runs that finish. Any Angle's 3D
+ // view is the exception: a splat and its turntable, nothing to finish.
+ if (original.account && original.place === "pool" && shotModel?.kind === "model3d" && shotModel.id !== ANY_ANGLE.buildModel && !workersFinish("model3d")) throw new Error(OWN_GPU_TOOL_MESSAGE);
if (!opts.dependsOn && shotModel?.options.multiShot?.mode === "concat" && (original.params?.shots?.filter((x) => x.prompt.trim()).length ?? 0) > 1) {
return createShotFilm(original, shotModel);
}
@@ -1616,17 +1622,30 @@ async function advanceDependents(): Promise<void> {
comfyWaits().delete(r.id);
// A camera path drawn through the still's depth on this server (Uni3C's guide where no browser drew one); a demo
// depth step hands on a demo render. Only once ComfyUI answers: a sweep that waits for it renders nothing.
+ let pathWaits = false;
for (let i = 0; i < slots.length; i++) {
if (slots[i].render !== "path") continue;
// The still, once the other slots are in (it can come from an earlier step too: a Canvas node's picture).
const photo = withChainInputs({ ...request, chain: slots }, values as string[]).inputs?.images?.[0];
const keys = request.params?.cameraPath ?? [];
if (deps[i]!.provider === "mock" || !photo) values[i] = placeholderFor(slots[i]);
- else {
+ else if (account && stored.place === "pool" && workersFinish("path")) {
+ // A run on this install's GPUs: the path is drawn on a worker's CPU slot (computer/finish.ts), never here. The
+ // step waits for it, sweep by sweep.
+ const depth = values[i]!;
+ const got = await asRun(() => pathOnWorker(r.id, i, { photo, depth, keys, frames: PATH_FRAMES, fps: PATH_FPS }));
+ if (got.state === "failed") throw new Error(got.error);
+ if (got.state === "waiting") {
+ pathWaits = true;
+ continue;
+ }
+ values[i] = got.url;
+ } else {
update(r.id, { message: "Rendering the camera path" });
values[i] = await asRun(() => renderPathVideo({ photo, depth: values[i]!, keys }, r.id));
}
}
+ if (pathWaits) continue;
if (model?.routes.some((x) => x.provider === "llm")) await probeLocal();
// Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
@@ -2669,10 +2688,12 @@ function resumeFinish(r: Row): void {
const outputs = JSON.parse(r.outputs_json || "[]") as OutputFile[];
// An account's model: one account finish at a time, and no turntable on the server (its browser records one).
const account = accountOf(r);
- startModelFinish(r.id, outputs, {
+ // An account's run on this install's GPUs is finished on a worker's CPU slot, never here (computer/finish.ts).
+ const onWorker = !!account && (JSON.parse(r.request_json) as GenerationRequest).place === "pool" && workersFinish("model3d");
+ (onWorker ? startWorkerModelFinish : startModelFinish)(r.id, outputs, {
op: r.op,
provider: r.provider,
- account,
+ account: account!,
onMessage: (message) => update(r.id, { message }),
done: (finished) => {
const now = db().prepare("SELECT status, external_meta_json FROM generations WHERE id = ?").get(r.id) as Pick<Row, "status" | "external_meta_json"> | undefined;
@@ -2992,6 +3013,7 @@ export async function cancelGeneration(id: string): Promise<void> {
// awaits, so it can't mark the job done in between.
if ((JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>).finishing) {
stopModelFinish(id);
+ stopWorkerFinish(id);
update(id, { status: "canceled", completed_at: Date.now(), message: null });
return;
}
@@ -3013,6 +3035,7 @@ export async function cancelGeneration(id: string): Promise<void> {
else if ("run" in own) await own.run(cancel);
}
stopModelFinish(id);
+ stopWorkerFinish(id);
update(id, { status: "canceled", completed_at: Date.now(), message: null });
// Steps waiting only to feed this one are dropped too (nothing was spent on them).
dropUnused(depIds(r.depends_on));
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 82505666..ce32e804 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -24,7 +24,7 @@ import { CONTEXT_LOOP_IDS, runName } from "@/lib/openjutsu-graphs";
import { reuseOf, reviewOfRun } from "@/lib/catalog/remove-object";
import { H3_REMOVAL_WORKFLOW } from "@/lib/catalog/character-swap";
import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";
-import { imageSize } from "@/lib/image-size";
+import { imageSize, orientedImageSize } from "@/lib/image-size";
import { probeMedia, type MediaInfo } from "@/lib/media-probe";
import { ocrText, parseOcrFrame, parseOcrLines, type OcrFrame } from "@/lib/ocr";
import { getSetting, isCandidate, savedSetting } from "../settings";
@@ -209,10 +209,19 @@ const poolMedia = () => new Set((process.env.FUOBE_POOL_MEDIA_INPUTS ?? "image")
/** May a job for workers send them files of this kind ("image", "video", "audio")? */
export const workersTake = (kind: "image" | "video" | "audio"): boolean => poolMedia().has(kind);
-export async function forWorkers(data: Buffer, contentType: string, name: string): Promise<{ data: Buffer; contentType: string; name: string }> {
+/**
+ * A file for a job on the workers: refused when they don't take its kind. A picture is made again from its pixels here
+ * (no EXIF, no GPS), unless `o.onWorker`: then the worker makes it again itself before its ComfyUI reads it, and this
+ * server only checks that it is a picture it can size.
+ */
+export async function forWorkers(data: Buffer, contentType: string, name: string, o: { onWorker?: boolean } = {}): Promise<{ data: Buffer; contentType: string; name: string }> {
const kind = contentType.split("/")[0];
if (!poolMedia().has(kind)) throw new ProviderError(kind === "video" ? "The shared GPUs don't take clips yet." : kind === "audio" ? "The shared GPUs don't take sound yet." : "The shared GPUs don't take this kind of file.");
if (kind !== "image") return { data, contentType, name };
+ if (o.onWorker) {
+ if (!imageSize(data)) throw new ProviderError("The shared GPUs don't take this kind of file.");
+ return { data, contentType, name };
+ }
const sharp = (await import("sharp")).default;
const png = await sharp(data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 }).rotate().png().toBuffer();
return { data: png, contentType: "image/png", name: name.replace(/\.[^.]*$/, "") + ".png" };
@@ -1001,8 +1010,9 @@ function rememberSent(uploaded: string, data: Buffer, contentType: string, name:
const info = probeMedia(data) ?? webmInfo(data) ?? aviInfo(data);
if (info) rememberMedia(uploaded, info);
} else if (/^image\//.test(contentType)) {
- // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape.
- const size = imageSize(data);
+ // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape (as it shows, turned by its
+ // EXIF orientation: a worker makes the picture again upright).
+ const size = orientedImageSize(data);
if (size) rememberMedia(uploaded, { container: "image", ...size, hasVideo: false, hasAudio: false });
}
}
@@ -1310,7 +1320,10 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
const computer = computerScope();
if (computer) {
if (worker === "isolated") throw new ProviderError(ISOLATED_ON_COMPUTER);
- const sent = onWorkers(computer) ? await forWorkers(data, contentType, name) : { data, contentType, name };
+ // An account's run on the workers sends its pictures as they came: the worker makes each one again from its pixels
+ // before its ComfyUI reads it (bin/lib/worker/picture.mjs), so this server never decodes them. The owner's own jobs
+ // are made again here, as before.
+ const sent = onWorkers(computer) ? await forWorkers(data, contentType, name, { onWorker: computer !== "owner" }) : { data, contentType, name };
const staged = stageInput(computer, sent.data, sent.contentType, sent.name);
rememberSent(staged, sent.data, sent.contentType, sent.name);
return staged;
@@ -1659,6 +1672,8 @@ export const comfyProvider: ProviderAdapter = {
prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,
metaBatch,
preview: true,
+ // A run whose results are checked before anyone sees them sends no live previews from the workers.
+ ...(forPool && runStamp()?.checkOutputs && { extra: { checkOutputs: true } }),
workflowId: manifest.id,
made: model?.kind,
loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),
diff --git a/tests/cpu-slot.test.ts b/tests/cpu-slot.test.ts
new file mode 100644
index 00000000..e99ee9e0
--- /dev/null
+++ b/tests/cpu-slot.test.ts
@@ -0,0 +1,362 @@
+/**
+ * The CPU slot on the workers' line (src/server/computer/pool.ts) and the finishing jobs (src/server/computer/finish.ts,
+ * src/lib/finish-ticket.ts): a worker may hold one GPU job and one CPU task at once, each claimed for its own slot; light
+ * CPU work goes to a CPU slot when the worker has one, and to its GPU's slot as before when it hasn't; a finishing job
+ * goes only to a CPU slot that runs its kind; the line counts each slot apart; another program on the GPU stops only
+ * the GPU's job. Then the live previews a worker sends with its progress: a JPEG of at most 64 KB is kept, anything
+ * else is dropped. Never a real ComfyUI, never a GPU.
+ */
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-cpu-slot-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const finish = await import("@/server/computer/finish");
+const { onComputer } = await import("@/server/providers/comfyui");
+const { allLanes } = await import("@/lib/lanes");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { finishProblem, FINISH_RUN_MS } = await import("@/lib/finish-ticket");
+const { previewOf, PREVIEW_LIMITS } = await import("@/lib/relay");
+const { previewForReport } = await import("@/lib/computer-runner");
+const { exifOrientation, orientedImageSize } = await import("@/lib/image-size");
+
+const ROOT = path.resolve(__dirname, "..");
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+/** A workflow the requirements index marks as light CPU work, and one that uses the GPU. */
+const CPU_WORKFLOW = "video-trim";
+const GPU_WORKFLOW = "bg-remove-rmbg";
+
+let routes: ComputerRoutes;
+let accountId = "";
+beforeAll(async () => {
+ routes = await loadRoutes();
+ setSetting("comfyWhere", "workers");
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+});
+beforeEach(() => {
+ resetRates();
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+type W = { id: string; token: string };
+type TaskRow = import("@/server/computer/tasks").TaskRow;
+const row = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;
+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;
+
+/** A worker the owner added and resumed, all day, allowed every lane, able to run every workflow. */
+function addWorker(): W {
+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ const workflows = (JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string }[] }).workflows.map((x) => x.id);
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ return w;
+}
+
+/** A worker's beat as the program sends it, with its CPU slot (null: none) and what each slot runs. */
+const beat = (w: W, o: { cpuSlot?: { finishes: string[] } | null; local?: { paused: boolean; why: string | null }; running?: string[]; cpuRunning?: string[] } = {}) =>
+ pool.workerBeat(
+ workerRow(w),
+ pool.cleanBeat({
+ device: `wkr-${w.id}`,
+ protocol: 3,
+ version: "1",
+ local: { ...(o.local ?? { paused: false, why: null }), until: null },
+ gpu: {},
+ inventoryHash: null,
+ running: (o.running ?? []).map((task) => ({ task })),
+ stopped: [],
+ ...(o.cpuSlot !== undefined && { cpuSlot: o.cpuSlot }),
+ cpuRunning: (o.cpuRunning ?? []).map((task) => ({ task })),
+ }),
+ );
+/** A slot's claim; `running`: the tasks the worker says it works on (any other it holds comes back to it). */
+const claim = (w: W, slot: "gpu" | "cpu" = "gpu", running: string[] = []) => pool.workerClaim(workerRow(w), running, Date.now(), slot);
+
+let gens = 0;
+function generation(account: string | null, op = "edit") {
+ const gid = `cpu-slot-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-selftest-image', 'open', 'comfyui', ?, 'image', 'running', ?, '[]', ?, ?)")
+ .run(gid, op, JSON.stringify(account ? { account, place: "pool" } : {}), now, now);
+ return gid;
+}
+
+/** The owner's own job of this workflow on the workers (a whole graph, in the owner's class), each a second after the last in line. */
+let ranks = 0;
+function ownerTask(workflowId: string, o: { preview?: boolean; checkOutputs?: boolean } = {}) {
+ const gid = generation(null);
+ const graph = { "1": { class_type: "LoadImage", inputs: { image: "x.png" } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/cpu-slot" } } };
+ const id = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId, ...(o.preview && { preview: true }), ...(o.checkOutputs && { extra: { checkOutputs: true } }), pool: pool.poolFields(workflowId, { class: "owner" }) }).id;
+ db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(Date.now() - 3_600_000 + ++ranks * 1000, id);
+ return id;
+}
+
+/** An account's run of this workflow on the workers. */
+function accountTask(workflowId: string) {
+ const gid = generation(accountId);
+ const graph = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/cpu-slot" } } };
+ return tasks.createTask({ principal: `acct:${accountId}`, generationId: gid, graph, workflowId, pool: pool.poolFields(workflowId, { account: accountId }) }).id;
+}
+
+/** An account's 3D finish, queued as the studio queues it after the run's GPU job. */
+function modelFinish(glb = Buffer.from("glTF fake model bytes")) {
+ const gid = generation(accountId, "image-to-3d");
+ return finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: glb, contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });
+}
+
+describe("the CPU slot on the line", () => {
+ it("light CPU work is marked for a CPU slot; a job that uses the GPU is not", () => {
+ expect(pool.cpuWorkflow(CPU_WORKFLOW)).toBe(true);
+ expect(pool.cpuWorkflow(GPU_WORKFLOW)).toBe(false);
+ expect(row(ownerTask(CPU_WORKFLOW)).slot).toBe("cpu");
+ expect(row(ownerTask(GPU_WORKFLOW)).slot).toBeNull();
+ });
+
+ it("a worker with a CPU slot holds one GPU job and one CPU task at once, each claimed for its own slot", () => {
+ const w = addWorker();
+ beat(w, { cpuSlot: { finishes: [] } });
+ const cpu = ownerTask(CPU_WORKFLOW);
+ const gpu = ownerTask(GPU_WORKFLOW);
+ // The GPU's slot leaves the CPU task (older in line) to the CPU slot.
+ expect(claim(w)?.id).toBe(gpu);
+ const c = claim(w, "cpu");
+ expect(c?.id).toBe(cpu);
+ expect(c?.slot).toBe("cpu");
+ expect(c?.runLimitMs).toBeLessThanOrEqual(FINISH_RUN_MS);
+ // One at a time in each slot.
+ expect(claim(w, "gpu", [gpu])).toBeNull();
+ expect(claim(w, "cpu", [cpu])).toBeNull();
+ expect(row(gpu).device).toBe(`wkr-${w.id}`);
+ expect(row(cpu).device).toBe(`wkr-${w.id}-cpu`);
+ // Both stay alive by the worker's beats.
+ beat(w, { cpuSlot: { finishes: [] }, running: [gpu], cpuRunning: [cpu] });
+ expect(row(cpu).device_seen_at).toBeGreaterThan(0);
+ });
+
+ it("a worker with no CPU slot takes light CPU work in its GPU's slot, as before, and claims nothing for a CPU slot", () => {
+ const w = addWorker();
+ beat(w);
+ const cpu = ownerTask(CPU_WORKFLOW);
+ ownerTask(GPU_WORKFLOW);
+ expect(claim(w, "cpu")).toBeNull();
+ expect(claim(w)?.id).toBe(cpu);
+ });
+
+ it("a finishing job goes only to a CPU slot that runs its kind, and carries its ticket in place of a graph", () => {
+ const plain = addWorker();
+ beat(plain, { cpuSlot: { finishes: [] } });
+ expect(finish.workersFinish("model3d")).toBe(false);
+ const id = modelFinish();
+ expect(claim(plain)).toBeNull();
+ expect(claim(plain, "cpu")).toBeNull();
+ const w = addWorker();
+ beat(w, { cpuSlot: { finishes: ["model3d", "path", "something-else"] } });
+ expect(JSON.parse(workerRow(w).cpu_slot_json!)).toEqual({ finishes: ["model3d", "path"] });
+ expect(finish.workersFinish("model3d")).toBe(true);
+ expect(claim(w)).toBeNull();
+ const c = claim(w, "cpu")!;
+ expect(c.id).toBe(id);
+ expect(c.graph).toBeUndefined();
+ expect(c.ticket).toBeUndefined();
+ expect(c.finish).toMatchObject({ kind: "model3d", settings: { material: "auto", turntable: true }, inputs: [{ slot: "model" }] });
+ expect(finishProblem(c.finish, { inputs: c.inputs })).toBeNull();
+ });
+
+ it("the line counts each slot apart: CPU tasks never stand ahead of a GPU job on a worker with a CPU slot", () => {
+ const w = addWorker();
+ beat(w, { cpuSlot: { finishes: [] } });
+ ownerTask(CPU_WORKFLOW);
+ const cpu2 = ownerTask(CPU_WORKFLOW);
+ const gpu = ownerTask(GPU_WORKFLOW);
+ expect(pool.placeInLine(row(gpu)).place).toBe(1);
+ expect(pool.placeInLine(row(cpu2)).place).toBe(2);
+ // With no CPU slot, the same worker serves them all in one line, as before.
+ beat(w, { cpuSlot: null });
+ expect(pool.placeInLine(row(gpu)).place).toBe(3);
+ });
+
+ it("another program on the GPU stops only the GPU's job; the CPU slot's task goes on", () => {
+ const w = addWorker();
+ beat(w, { cpuSlot: { finishes: [] } });
+ const cpu = ownerTask(CPU_WORKFLOW);
+ const gpu = ownerTask(GPU_WORKFLOW);
+ claim(w);
+ claim(w, "cpu");
+ beat(w, { cpuSlot: { finishes: [] }, local: { paused: true, why: "gpu-busy:game.exe" }, running: [gpu], cpuRunning: [cpu] });
+ expect(row(gpu).state).toBe("waiting");
+ expect(row(cpu).state).toBe("sending");
+ // A stop-now by hand stops both.
+ beat(w, { cpuSlot: { finishes: [] }, local: { paused: true, why: "here-now" }, cpuRunning: [cpu] });
+ expect(row(cpu).state).toBe("waiting");
+ });
+
+ it("people's tasks a worker may claim now count only its GPU's work", () => {
+ const w = addWorker();
+ accountTask(CPU_WORKFLOW);
+ beat(w);
+ expect(pool.claimableNow(workerRow(w))).toBe(1);
+ beat(w, { cpuSlot: { finishes: [] } });
+ expect(pool.claimableNow(workerRow(w))).toBe(0);
+ });
+});
+
+describe("finishing jobs", () => {
+ it("a finish ticket is checked the same way on both sides", () => {
+ const name = "fuobe_abcdefgh1234.png";
+ const good = { v: 1, kind: "path", settings: { keys: [{ t: 0, azimuth: 0, elevation: 0, distance: 1 }, { t: 1, azimuth: 30, elevation: 5, distance: 0.8, truck: 0.1 }], frames: 81, fps: 16 }, inputs: [{ slot: "photo", name, sha256: "a".repeat(64) }, { slot: "depth", name: "fuobe_abcdefgh5678.png", sha256: "b".repeat(64) }] };
+ expect(finishProblem(good)).toBeNull();
+ expect(finishProblem({ ...good, inputs: [...good.inputs].reverse() })).not.toBeNull();
+ expect(finishProblem({ ...good, settings: { ...good.settings, frames: 100_000 } })).not.toBeNull();
+ expect(finishProblem({ ...good, settings: { ...good.settings, keys: [{ t: 0, azimuth: 0, elevation: 0, distance: 1, path: "../x" }] } })).not.toBeNull();
+ expect(finishProblem({ ...good, inputs: [{ ...good.inputs[0], name: "../../secret.png" }, good.inputs[1]] })).not.toBeNull();
+ expect(finishProblem({ ...good, extra: 1 })).not.toBeNull();
+ // Its inputs must be the files the job sends.
+ expect(finishProblem(good, { inputs: [{ name, sha256: "a".repeat(64) }] })).not.toBeNull();
+ expect(finishProblem({ v: 1, kind: "model3d", settings: { material: "chrome", turntable: true }, inputs: [{ slot: "model", name, sha256: "a".repeat(64) }] })).not.toBeNull();
+ });
+
+ it("a path's keys go in the ticket as the path render reads them, each inside its range", () => {
+ const keys = finish.pathKeys([
+ { t: 1, azimuth: 99_999, elevation: 200, distance: 50, truck: 500 },
+ { t: 0.5, azimuth: 30, elevation: 5, distance: 0.01 },
+ ]);
+ expect(keys[0]).toEqual({ t: 0, azimuth: 0, elevation: 0, distance: 1 });
+ expect(keys.map((k) => k.t)).toEqual([0, 0.5, 1]);
+ expect(keys[2]).toEqual({ t: 1, azimuth: 3600, elevation: 90, distance: 4, truck: 20 });
+ const name = "fuobe_abcdefgh1234.png";
+ const ticket = { v: 1, kind: "path", settings: { keys, frames: 81, fps: 16 }, inputs: [{ slot: "photo", name, sha256: "a".repeat(64) }, { slot: "depth", name, sha256: "b".repeat(64) }] };
+ expect(finishProblem(ticket)).toBeNull();
+ });
+
+ it("only the files its kind makes are asked for, each within its limit", () => {
+ const id = modelFinish();
+ const t = row(id);
+ const entry = {
+ status: { status_str: "success" },
+ outputs: {
+ finish: {
+ results: [
+ { filename: "web.glb", subfolder: "", type: "output", role: "web" },
+ { filename: "turntable.mp4", subfolder: "", type: "output", role: "turntable" },
+ { filename: "secret.txt", subfolder: "", type: "output", role: "notes" },
+ { filename: "../x.glb", subfolder: "", type: "output", role: "poster" },
+ { filename: "again.glb", subfolder: "", type: "output", role: "web" },
+ ],
+ stats: [{ material: "matte", triangles: 1200, bytesIn: 900, bytesOut: 300 }],
+ },
+ },
+ };
+ const plan = onComputer(t.principal, () => finish.planFinish(t, [entry]));
+ expect("wanted" in plan && plan.wanted.map((w) => [w.filename, w.kind])).toEqual([
+ ["web.glb", "model3d"],
+ ["turntable.mp4", "video"],
+ ]);
+ expect("outputs" in plan && plan.outputs[0]).toMatchObject({ files: [{ role: "web", n: 0 }, { role: "turntable", n: 1 }], stats: { material: "matte", triangles: 1200 } });
+ expect(onComputer(t.principal, () => finish.planFinish(t, [{ status: { status_str: "success" }, outputs: {} }]))).toHaveProperty("error");
+ });
+});
+
+describe("live previews from a worker", () => {
+ const jpeg = (bytes: number) => {
+ const b = Buffer.alloc(bytes, 7);
+ b[0] = 0xff;
+ b[1] = 0xd8;
+ b[2] = 0xff;
+ return b;
+ };
+
+ it("a worker sends a JPEG of at most 64 KB, at most one every 2 s", async () => {
+ const small = new Blob([jpeg(20_000)], { type: "image/jpeg" });
+ expect(await previewForReport(small, -Infinity, 10_000)).toBe(jpeg(20_000).toString("base64"));
+ expect(await previewForReport(small, 9_000, 10_000)).toBeUndefined();
+ expect(await previewForReport(new Blob([jpeg(PREVIEW_LIMITS.maxBytes + 1)], { type: "image/jpeg" }), -Infinity, 10_000)).toBeUndefined();
+ expect(await previewForReport(new Blob([Buffer.from("89504e470d0a1a0a", "hex")], { type: "image/png" }), -Infinity, 10_000)).toBeUndefined();
+ });
+
+ it("the studio keeps a preview up to 64 KB and drops a larger one, keeping the progress", async () => {
+ expect(previewOf(jpeg(PREVIEW_LIMITS.maxBytes).toString("base64"))).toBeDefined();
+ expect(previewOf(jpeg(PREVIEW_LIMITS.maxBytes + 1).toString("base64"))).toBeUndefined();
+ expect(previewOf(Buffer.from("89504e470d0a1a0a", "hex").toString("base64"))).toBeUndefined();
+ expect(previewOf("not base64!")).toBeUndefined();
+ // Through the report route, as a worker sends it.
+ const w = addWorker();
+ beat(w);
+ const id = ownerTask(GPU_WORKFLOW, { preview: true });
+ const c = claim(w)!;
+ expect(c.reportPreview).toBe(true);
+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });
+ const report = (body: Record<string, unknown>) => api(`/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fuobe-Lease": c.lease }, body: JSON.stringify(body) });
+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);
+ const big = jpeg(70 * 1024).toString("base64");
+ expect((await report({ event: "running", value: 2, max: 8, preview: big })).status).toBe(200);
+ expect(tasks.taskProgress(id)).toMatchObject({ value: 2, max: 8 });
+ expect(tasks.taskPreview(id)).toBeNull();
+ const ok = jpeg(30 * 1024);
+ expect((await report({ event: "running", value: 3, max: 8, preview: ok.toString("base64") })).status).toBe(200);
+ expect(tasks.taskPreview(id)?.jpeg.equals(ok)).toBe(true);
+ expect(tasks.taskProgress(id)).toMatchObject({ value: 3, max: 8 });
+ // A beat never brings a preview.
+ beat(w, { running: [id] });
+ expect(tasks.taskPreview(id)?.jpeg.equals(ok)).toBe(true);
+ // A progress report with no preview stays a few KB.
+ expect((await report({ event: "running", value: 4, max: 8, node: "x".repeat(20 * 1024) })).status).toBe(413);
+ });
+});
+
+describe("which runs show live previews", () => {
+ it("a run whose results are checked first, a finishing job and a run with no previews never ask the worker for one", () => {
+ const w = addWorker();
+ beat(w, { cpuSlot: { finishes: ["model3d"] } });
+ const checked = ownerTask(GPU_WORKFLOW, { preview: true, checkOutputs: true });
+ const first = claim(w)!;
+ expect(first.id).toBe(checked);
+ expect(first.reportPreview).toBeUndefined();
+ expect(tasks.showsPreview(row(checked))).toBe(false);
+ tasks.endTask(checked, "canceled");
+ const plain = ownerTask(GPU_WORKFLOW);
+ expect(claim(w)?.reportPreview).toBeUndefined();
+ tasks.endTask(plain, "canceled");
+ const fin = modelFinish();
+ const c = claim(w, "cpu")!;
+ expect(c.id).toBe(fin);
+ expect(c.reportPreview).toBeUndefined();
+ });
+});
+
+describe("pictures as they show", () => {
+ it("a JPEG stored on its side is sized upright, as the worker makes it again", async () => {
+ const sharp = (await import("sharp")).default;
+ const sideways = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } })
+ .jpeg()
+ .withMetadata({ orientation: 6 })
+ .withExif({ IFD0: { Artist: "someone" } })
+ .toBuffer();
+ expect(exifOrientation(sideways)).toBe(6);
+ expect(orientedImageSize(sideways)).toEqual({ width: 20, height: 40 });
+ const plain = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } }).jpeg().toBuffer();
+ expect(exifOrientation(plain)).toBeNull();
+ expect(orientedImageSize(plain)).toEqual({ width: 40, height: 20 });
+ });
+});
diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.ts
index 10451474..f1844187 100644
--- a/tests/pool-account-runs.test.ts
+++ b/tests/pool-account-runs.test.ts
@@ -140,7 +140,7 @@ function workerRunner(token: string) {
origin: "http://localhost:3000",
sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),
compose: (t) => composeOnWorker(t),
- beatExtra: () => ({ protocol: 2, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),
+ beatExtra: () => ({ protocol: 3, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),
},
{ device: "worker", port: comfy.port, clientId: "worker-test" },
);
@@ -191,7 +191,7 @@ function accountTask(o: { lane?: string; account?: string; rankAt?: number; notA
type WorkerRow = import("@/server/computer/workers").WorkerRow;
const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
const beatAs = (w: { id: string }, now = Date.now()) =>
- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);
+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);
const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);
describe("with hosted runs off, nothing changes", () => {
@@ -387,7 +387,7 @@ describe("the line", () => {
// The worker pauses at once (another program on the GPU): the job goes back in line at no cost.
pool.workerBeat(
db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,
- pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: true, why: "gpu-busy:game.exe", until: null }, gpu: {}, running: [{ task: first.id }], stopped: [] }),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: true, why: "gpu-busy:game.exe", until: null }, gpu: {}, running: [{ task: first.id }], stopped: [] }),
);
const back = rowOf(first.id);
expect(back.state).toBe("waiting");
@@ -426,7 +426,7 @@ describe("the line", () => {
// The worker pauses at once (its owner pressed the pause): the run goes back in line.
pool.workerBeat(
db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,
- pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: true, why: "here-now", until: null }, gpu: {}, running: [{ task: t.id }], stopped: [] }),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: true, why: "here-now", until: null }, gpu: {}, running: [{ task: t.id }], stopped: [] }),
);
const back = await until(() => {
const g = getGeneration(id);
@@ -710,23 +710,24 @@ describe("graphs and results for the workers", () => {
});
describe("nothing of a run on the workers goes to a ComfyUI address", () => {
- it("an account's picture is made again from its pixels (no EXIF) and kept for its task", async () => {
+ it("an account's picture is kept for its task as it came (the worker makes it again from its pixels), and never decoded here", async () => {
const sharp = (await import("sharp")).default;
const jpeg = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#c33" } })
.jpeg()
.withExif({ IFD0: { Copyright: "private note", Artist: "someone" } })
.toBuffer();
expect((await sharp(jpeg).metadata()).exif).toBeDefined();
- const { comfyProvider } = await import("@/server/providers/comfyui");
+ const { comfyProvider, mediaInfoFor } = await import("@/server/providers/comfyui");
const staged = await hosted.runOnPool(accountId, () => comfyProvider.prepareFile!(jpeg, "image/jpeg", "me.jpg"));
const row = db().prepare("SELECT principal, content_type FROM relay_inputs WHERE name = ?").get(staged) as { principal: string; content_type: string };
- expect(row).toEqual({ principal: `acct:${accountId}`, content_type: "image/png" });
+ expect(row).toEqual({ principal: `acct:${accountId}`, content_type: "image/jpeg" });
const fs = await import("node:fs");
const path = await import("node:path");
- const kept = fs.readFileSync(path.join(dir, "relay", "in", staged));
- const meta = await sharp(kept).metadata();
- expect(meta.format).toBe("png");
- expect(meta.exif).toBeUndefined();
+ expect(fs.readFileSync(path.join(dir, "relay", "in", staged)).equals(jpeg)).toBe(true);
+ // Its size as it shows (turned by its orientation), as the worker's upright copy has it.
+ expect(hosted.runOnPool(accountId, () => mediaInfoFor(staged))).toMatchObject({ width: 8, height: 8 });
+ // Something that isn't a picture is never kept as one.
+ await expect(hosted.runOnPool(accountId, () => comfyProvider.prepareFile!(Buffer.from("not a picture"), "image/jpeg", "x.jpg"))).rejects.toThrow();
expect(serverComfyCalls()).toEqual([]);
});
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
index 50723463..fc03d0d6 100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@ -161,7 +161,7 @@ const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks
const workerRow = () => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(worker.id) as import("@/server/computer/workers").WorkerRow;
/** The stand-in worker takes the next task in line, as the worker program does. */
function workerTakes() {
- pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }));
+ pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }));
return pool.workerClaim(workerRow(), [], Date.now());
}
const started = (generationId: string) => !!(db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").get(generationId) as { started_at: number | null } | undefined)?.started_at;
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index aedc40d0..348d8b76 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -107,7 +107,7 @@ function standInWorker(name = "stand-in") {
type WorkerRow = import("@/server/computer/workers").WorkerRow;
const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
const beatAs = (w: { id: string }, now = Date.now()) =>
- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);
+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);
const claimAs = (w: { id: string }, now = Date.now()) => pool.workerClaim(workerRow(w), [], now);
const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.ts
index 7616990b..39e9f71c 100644
--- a/tests/worker-tickets.test.ts
+++ b/tests/worker-tickets.test.ts
@@ -101,7 +101,7 @@ function addWorker(): W {
const beat = (w: W, o: { catalogVersion?: string | null; ceiling?: unknown } = {}) =>
pool.workerBeat(
workerRow(w),
- pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: o.catalogVersion === undefined ? VERSION : o.catalogVersion, ...(o.ceiling !== undefined && { ceiling: o.ceiling }) }),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: o.catalogVersion === undefined ? VERSION : o.catalogVersion, ...(o.ceiling !== undefined && { ceiling: o.ceiling }) }),
);
const claim = (w: W) => pool.workerClaim(workerRow(w), []);