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: give a job back, report its execution time, say which inputs they take

Adarshe01d5c9a014e
diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjs
index 68a73f8c..e5729895 100644
--- a/bin/lib/worker/inventory.mjs
+++ b/bin/lib/worker/inventory.mjs
@@ -109,9 +109,9 @@ export async function modelFiles(modelDirs, index, cacheFile, pins = filePins())
return out;
}
-/** The same hash the studio computes (src/server/computer/pool.ts inventoryHash). */
+/** The same hash the studio computes (src/server/computer/pool.ts inventoryHash), with the kinds of input it takes. */
export function inventoryHash(inv) {
const files = inv.files.map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();
const packs = inv.nodePacks.map((p) => `${p.name}@${p.commit ?? ""}`).sort();
- return crypto.createHash("sha256").update(JSON.stringify({ files, packs })).digest("hex");
+ return crypto.createHash("sha256").update(JSON.stringify({ files, packs, ...(inv.media && { media: [...inv.media].sort() }) })).digest("hex");
}
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 c4a322d7..d02f46b5 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -1,4 +1,4 @@
-import { RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
+import { GIVE_BACK, 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";
@@ -6,7 +6,7 @@ import { leased, report, type TaskRow } from "@/server/computer/tasks";
import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";
import { enter } from "@/server/rate";
-const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "passes", "gone", "comfy-down", "stopped", "failed"]);
+const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "passes", "gone", "give-back", "comfy-down", "stopped", "failed"]);
/** 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 };
@@ -18,6 +18,8 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
const e = b.event;
if (typeof e !== "string" || !EVENTS.has(e)) return null;
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+ // A worker's measured execution time and GPU name, with a finished job.
+ const exec = { ...(num(b.execMs) !== undefined && { execMs: num(b.execMs) }), ...(typeof b.device === "string" && { device: b.device }) };
switch (e) {
case "sent":
return typeof b.promptId === "string" ? { event: e, promptId: b.promptId, number: num(b.number) } : null;
@@ -28,9 +30,11 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
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 "finished":
- return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }) } : null;
+ 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":
- return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never } : null;
+ return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never, ...(b.running !== true && exec) } : null;
+ case "give-back":
+ return typeof b.why === "string" && (GIVE_BACK as readonly string[]).includes(b.why) ? { event: e, why: b.why as never } : null;
case "failed":
return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status) } : null;
case "comfy-down":
diff --git a/src/lib/lanes.ts b/src/lib/lanes.ts
index 7a9cfa82..b1d12ac3 100644
--- a/src/lib/lanes.ts
+++ b/src/lib/lanes.ts
@@ -86,10 +86,30 @@ export function needsOf(index: RequirementIndex, workflowId: string): Needs | nu
return { workflowId, files, packs: Object.keys(wf.packs).sort(), minVramBytes: minVramBytesFor(wf.vramGb) };
}
-/** A worker's verified files and node packs (PUT /api/gpu/computer/inventory). */
+/** The kinds of input file a worker may take. A worker makes every clip and sound again before its ComfyUI reads it. */
+export const MEDIA_KINDS = ["image", "video", "audio"] as const;
+export type MediaKind = (typeof MEDIA_KINDS)[number];
+
+/** The node types that read a clip or a sound file the job sent. */
+export const MEDIA_LOADERS: Record<"video" | "audio", readonly string[]> = {
+ video: ["LoadVideo", "VHS_LoadVideo", "VHS_LoadVideoPath", "VHS_LoadVideoFFmpeg", "VHS_LoadVideoFFmpegPath"],
+ audio: ["LoadAudio", "VHS_LoadAudio", "VHS_LoadAudioUpload"],
+};
+
+/** The kinds of input file a workflow reads besides pictures: "video", "audio", both or none. */
+export function mediaOf(wf: Pick<IndexWorkflow, "core" | "packs">): ("video" | "audio")[] {
+ const classes = new Set([...wf.core, ...Object.values(wf.packs).flat()]);
+ return (["video", "audio"] as const).filter((k) => MEDIA_LOADERS[k].some((c) => classes.has(c)));
+}
+
+/**
+ * A worker's verified files and node packs (PUT /api/gpu/computer/inventory), and the kinds of input it takes (`media`:
+ * a worker without a way to make clips and sound again takes pictures only). No `media`: every kind.
+ */
export interface Inventory {
files: FileNeed[];
nodePacks: { name: string; commit: string | null }[];
+ media?: MediaKind[];
}
const fileKey = (f: Pick<FileNeed, "folder" | "name">) => `${f.folder}/${f.name}`;
@@ -109,6 +129,7 @@ export function lanesFor(
sha: Sha,
): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {
const packs = new Set(inv.nodePacks.map((p) => p.name));
+ const takes = new Set<string>(inv.media ?? MEDIA_KINDS);
const ok = new Map<string, boolean>();
const workflows: string[] = [];
const lacking = new Map<string, Map<string, number>>();
@@ -118,13 +139,15 @@ export function lanesFor(
const n = needsOf(index, id)!;
const missingFiles = n.files.filter((f) => !hasFile(inv, f));
const missingPacks = n.packs.filter((p) => !packs.has(p));
- const fine = !missingFiles.length && !missingPacks.length;
+ const missingMedia = mediaOf(index.workflows[id]).filter((k) => !takes.has(k));
+ const fine = !missingFiles.length && !missingPacks.length && !missingMedia.length;
if (fine) workflows.push(id);
ok.set(lane, (ok.get(lane) ?? true) && fine);
if (!fine) {
const m = lacking.get(lane) ?? new Map<string, number>();
for (const f of missingFiles) m.set(fileKey(f), f.size);
for (const p of missingPacks) m.set(`pack:${p}`, 0);
+ for (const k of missingMedia) m.set(`input:${k}`, 0);
lacking.set(lane, m);
}
}
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 4a6fce4f..0d0a7b2c 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -23,10 +23,21 @@ export interface HistoryEntryLike {
outputs?: Record<string, Record<string, unknown>>;
}
-/** Why the tab gave up on a task by itself (the server says it in plain words). */
-export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified"] as const;
+/**
+ * Why the tab gave up on a task by itself (the server says it in plain words). A worker adds two: its ComfyUI stopped
+ * twice while running the task ("input-crashed"), and a clip or a sound that couldn't be made again ("input-unreadable").
+ */
+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"] as const;
export type TabFailure = (typeof TAB_FAILURES)[number];
+/**
+ * Why a worker gives a task back to the line (another worker, or this one later, runs it): it made no progress for too
+ * long ("stalled"), it ran past its run limit ("run-limit"), or it takes clips or sound and this worker can't make them
+ * again ("media").
+ */
+export const GIVE_BACK = ["stalled", "run-limit", "media"] as const;
+export type GiveBackWhy = (typeof GIVE_BACK)[number];
+
/** What the tab reports about one task. */
export type ReportEvent =
/** ComfyUI took the prompt (`promptId`: the id it answered, the server's own unless an older ComfyUI minted one). */
@@ -37,10 +48,18 @@ export type ReportEvent =
| { event: "queued"; position: number }
/** Running: the sampler's steps, and the node. */
| { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }
- /** Finished: its /history entry (a worker adds the most VRAM it took, for the benchmarks). */
- | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number }
- /** A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. */
- | { event: "passes"; running: boolean; entries: HistoryEntryLike[] }
+ /**
+ * Finished: its /history entry. A worker adds the most VRAM it took (for the benchmarks), how long its ComfyUI spent
+ * executing the job (`execMs`: execution only, no waits, no uploads) and its GPU's name (`device`).
+ */
+ | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string }
+ /**
+ * A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. The
+ * last one (not running) is the job's end: a worker adds `execMs` and `device` as for "finished".
+ */
+ | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string }
+ /** A worker gives the task back to the line (it counts as an attempt). */
+ | { event: "give-back"; why: GiveBackWhy }
/** ComfyUI has no trace of it (restarted): the server sends it again once. */
| { event: "gone" }
/** The tab can't use ComfyUI: it doesn't answer, or (`why: "setting"`) it answers without Fuobe's setting. */
@@ -61,6 +80,7 @@ const ALLOWED: Record<ReportEventName, readonly RelayState[]> = {
finished: ["queued", "running"],
passes: ["queued", "running"],
gone: ["sending", "queued", "running"],
+ "give-back": ["sending", "queued", "running"],
"comfy-down": ["sending", "queued", "running", "collecting"],
stopped: ["sending", "queued", "running", "collecting", "done", "failed", "canceled"],
failed: ["sending", "queued", "running", "collecting"],
@@ -355,6 +375,10 @@ export function tabFailureWords(reason: TabFailure, status?: number): string {
return "The GPU that took this run refused it: it names a file path.";
case "model-unverified":
return "The GPU that took this run refused it: it needs a model file that GPU couldn't verify.";
+ case "input-crashed":
+ return "This run stopped twice at the same point. Try another file or different settings.";
+ case "input-unreadable":
+ return "A clip or a sound in this run couldn't be read. Try another file.";
default:
return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;
}
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index e3db034a..ff82f7f1 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -1,11 +1,11 @@
import "server-only";
import crypto from "node:crypto";
-import { allLanes, laneLabel, lanesFor, needsOf, type Inventory, type Needs } from "@/lib/lanes";
+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 { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
-import { cleanFacts, endTask, getTask, json, noteProgress, setPoolClocks, setTask, takeTask, type TaskRow } from "./tasks";
+import { cleanFacts, endTask, getTask, json, noteProgress, setPoolClocks, setPoolGiveBack, setTask, takeTask, type TaskRow } from "./tasks";
import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
/**
@@ -199,7 +199,9 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; wo
const name = text(x?.name, 128);
return name ? [{ name, commit: text(x?.commit, 64) }] : [];
});
- const inv: Inventory = { files, nodePacks };
+ // The kinds of input it takes (none said: every kind, as before workers said so).
+ const media = Array.isArray(o.media) ? MEDIA_KINDS.filter((k) => (o.media as unknown[]).includes(k)) : undefined;
+ const inv: Inventory = { files, nodePacks, ...(media && { media }) };
const r = lanesFor(loadIndex(), inv, sha);
const invHash = inventoryHash(inv);
db()
@@ -212,7 +214,7 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; wo
export function inventoryHash(inv: Inventory): string {
const files = [...inv.files].map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();
const packs = [...inv.nodePacks].map((p) => `${p.name}@${p.commit ?? ""}`).sort();
- return sha(JSON.stringify({ files, packs }));
+ return sha(JSON.stringify({ files, packs, ...(inv.media && { media: [...inv.media].sort() }) }));
}
// ---------------------------------------------------------------------------
@@ -366,6 +368,16 @@ setPoolClocks((t, now) => {
return getTask(t.principal, t.id) ?? t;
});
+/** The words of a run whose worker gave it back the third time. */
+export const GAVE_BACK_WORDS = "This run couldn't finish. Press Retry.";
+
+/**
+ * A worker gives its task back (it stalled, ran past its run limit, or takes clips or sound the worker can't make
+ * again): it goes back in line with its place kept, and counts as an attempt, so another worker that can run it is
+ * preferred and the third time fails it.
+ */
+setPoolGiveBack((t) => backInLine(t, { blame: true, why: GAVE_BACK_WORDS }));
+
// ---------------------------------------------------------------------------
// Place in line and the wait (4.4)
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 6f256a77..7165a273 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -16,6 +16,7 @@ import {
type BeatAnswer,
type ClaimedTask,
type ComputerFacts,
+ type GiveBackWhy,
type HistoryEntryLike,
type RelayState,
type ReportEvent,
@@ -568,6 +569,9 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
}
const entries = e.event === "finished" ? [e.entry] : e.entries;
if (!Array.isArray(entries) || entries.some((x) => !x || typeof x !== "object")) throw new RelayError(400, "Bad history entry");
+ // A worker's measured execution time and GPU, kept with the task for metering.
+ const exec = execFields(e);
+ const extra = (more: Record<string, unknown> = {}) => ({ ...(exec || Object.keys(more).length ? { extra_json: JSON.stringify({ ...extraOf(t), ...(exec && { exec }), ...more }) } : {}) });
const p = plan(entries, e.event === "passes");
if ("follow" in p) {
if (!t.meta_batch) {
@@ -578,12 +582,12 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
return { ok: true, follow: p.follow };
}
if ("error" in p) {
- endTask(t.id, "failed", { error: p.error });
+ endTask(t.id, "failed", { error: p.error, ...extra() });
return { ok: true };
}
const received: Received[] = p.wanted.map((w) => ({ n: w.n, bytes: 0, total: 0, done: false }));
if (!p.wanted.length) {
- endTask(t.id, "done", { result_json: JSON.stringify(p.outputs), wanted_json: "[]", received_json: "[]" });
+ endTask(t.id, "done", { result_json: JSON.stringify(p.outputs), wanted_json: "[]", received_json: "[]", ...extra() });
return { ok: true, wanted: [] };
}
setTask(t.id, {
@@ -592,10 +596,15 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
result_json: JSON.stringify(p.outputs),
wanted_json: JSON.stringify(p.wanted),
received_json: JSON.stringify(received),
- extra_json: JSON.stringify({ ...extraOf(t), budget: p.budget }),
+ ...extra({ budget: p.budget }),
});
return { ok: true, wanted: p.wanted };
}
+ case "give-back":
+ // Only a worker's task goes back to the line (a person's own computer keeps its jobs).
+ if (!t.pools || !poolGiveBack) throw new RelayError(409, "That doesn't fit this run now");
+ poolGiveBack(t, e.why);
+ return { ok: true };
case "gone":
if (t.attempts < 2 && t.state !== "sending") {
setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null });
@@ -799,6 +808,30 @@ export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {
let poolClocks: ((t: TaskRow, now: number) => TaskRow) | null = null;
export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (poolClocks = fn);
+/** A worker gives its task back to the line (pool.ts sets this too). */
+let poolGiveBack: ((t: TaskRow, why: GiveBackWhy) => void) | null = null;
+export const setPoolGiveBack = (fn: (t: TaskRow, why: GiveBackWhy) => void) => (poolGiveBack = fn);
+
+/** The execution time (ms, at most a week) and GPU name a worker reported with a finished job, as kept. */
+export interface ExecFacts {
+ ms: number;
+ device?: string;
+}
+
+function execFields(e: ReportEvent): ExecFacts | null {
+ if (e.event !== "finished" && e.event !== "passes") return null;
+ const ms = typeof e.execMs === "number" && Number.isFinite(e.execMs) && e.execMs >= 0 ? Math.min(Math.round(e.execMs), 7 * 24 * 3_600_000) : null;
+ if (ms === null) return null;
+ const device = typeof e.device === "string" && e.device.trim() ? e.device.trim().slice(0, FACT_LIMITS.text) : undefined;
+ return { ms, ...(device && { device }) };
+}
+
+/** What a worker measured for a task's run: its ComfyUI's execution time and its GPU, or null (none reported). */
+export const execOf = (t: TaskRow): ExecFacts | null => {
+ const x = json<{ exec?: ExecFacts }>(t.extra_json, {}).exec;
+ return x && typeof x.ms === "number" ? x : null;
+};
+
/** The file of a received output, for the principal whose task it is (anyone else: null). */
export function receivedFile(principal: Principal, taskId: string, n: number): { path: string; contentType?: string } | null {
const t = getTask(principal, taskId);
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index 28f67fd6..31eebbda 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -22,7 +22,8 @@ const claimRoute = await import("@/app/api/gpu/computer/claim/route");
const reportRoute = await import("@/app/api/gpu/computer/tasks/[id]/report/route");
const { forWorkers } = await import("@/server/providers/comfyui");
const { hoursAt, parseHours } = await import("@/lib/worker-hours");
-const { lanesFor, needsOf, laneOf } = await import("@/lib/lanes");
+const lanesModule = await import("@/lib/lanes");
+const { lanesFor, needsOf, laneOf } = lanesModule;
const { loadIndex } = await import("@/server/gpu/index-file");
const LANE_A = "aaaaaaaaaaaa";
@@ -360,3 +361,102 @@ describe("hours and lanes", () => {
expect(laneOf(index, id, sha)).toMatch(/^([0-9a-f]{12}|small)$/);
});
});
+
+describe("a worker's own reports: giving a job back, its execution time, the inputs it takes", () => {
+ const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+ async function routed(w: W, id: string) {
+ const headers = { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" };
+ const c = await claimRoute.POST(new Request("http://localhost:3000/api/gpu/computer/claim", { method: "POST", headers, body: JSON.stringify({ running: [] }) }));
+ const { task: t } = await c.json();
+ expect(t.id).toBe(id);
+ const say = async (body: Record<string, unknown>) => {
+ const r = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify(body) }), { params: Promise.resolve({ id }) });
+ return { status: r.status, body: await r.json() };
+ };
+ return { t, say };
+ }
+
+ it("a job given back goes back in line with its place, counts as an attempt, and the third time fails in plain words", async () => {
+ clock = Date.now();
+ const id = task();
+ const rank = state(id).rank_at;
+ const w = worker("gives-back");
+ for (let i = 1; i <= 3; i++) {
+ const { t, say } = await routed(w, id);
+ expect(t.attempt).toBe(i);
+ expect((await say({ event: "sent", promptId: t.promptId })).status).toBe(200);
+ const back = await say({ event: "give-back", why: i === 1 ? "stalled" : i === 2 ? "run-limit" : "media" });
+ expect(back.status).toBe(200);
+ if (i < 3) {
+ expect(back.body.state).toBe("waiting");
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: i, rank_at: rank, worker_id: null });
+ expect(JSON.parse(state(id).tried_json ?? "[]")).toEqual([w.id]);
+ } else {
+ expect(back.body.state).toBe("failed");
+ expect(state(id).error).toBe(pool.GAVE_BACK_WORDS);
+ }
+ }
+ });
+
+ it("a give-back with an unknown reason is refused, and a person's own computer can't give its job back", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("bad-reason");
+ const { t, say } = await routed(w, id);
+ await say({ event: "sent", promptId: t.promptId });
+ expect((await say({ event: "give-back", why: "bored" })).status).toBe(400);
+ expect(state(id).state).toBe("queued");
+ const own = tasks.createTask({ principal: "owner", generationId: "own-gen", graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } } });
+ db().prepare("UPDATE relay_tasks SET state = 'running' WHERE id = ?").run(own.id);
+ expect(() => tasks.report(state(own.id), { event: "give-back", why: "stalled" }, () => ({ error: "x" }))).toThrow(/doesn't fit/);
+ });
+
+ it("keeps the execution time and the GPU name a worker reports with a finished job", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("exec");
+ const { t } = await routed(w, id);
+ tasks.report(state(id), { event: "sent", promptId: t.promptId }, () => ({ error: "x" }));
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ tasks.report(state(id), { event: "finished", entry, execMs: 12_345.6, device: " Test GPU " }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ expect(state(id).state).toBe("done");
+ expect(tasks.execOf(state(id))).toEqual({ ms: 12_346, device: "Test GPU" });
+ // Nothing reported: nothing kept; a nonsense time is not kept either.
+ const id2 = task();
+ const { t: t2 } = await routed(w, id2);
+ tasks.report(state(id2), { event: "sent", promptId: t2.promptId }, () => ({ error: "x" }));
+ tasks.report(state(id2), { event: "finished", entry, execMs: -5 }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ expect(tasks.execOf(state(id2))).toBeNull();
+ });
+
+ it("a worker that can't make clips and sound again gets no workflow that reads them", () => {
+ const index = loadIndex();
+ const { mediaOf } = lanesModule;
+ const reads = Object.keys(index.workflows).filter((k) => !index.workflows[k].isolated && mediaOf(index.workflows[k]).length);
+ const pictures = Object.keys(index.workflows).filter((k) => !index.workflows[k].isolated && !mediaOf(index.workflows[k]).length);
+ expect(reads.length).toBeGreaterThan(10);
+ // A worker that has every file and pack.
+ const files = Object.values(index.files).map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ const nodePacks = Object.keys(index.packs).map((name) => ({ name, commit: null }));
+ const all = lanesFor(index, { files, nodePacks }, sha).workflows;
+ expect(all).toEqual(expect.arrayContaining([...reads, ...pictures]));
+ expect(lanesFor(index, { files, nodePacks, media: ["image", "video", "audio"] }, sha).workflows).toEqual(all);
+ const onlyPictures = lanesFor(index, { files, nodePacks, media: ["image"] }, sha);
+ expect(onlyPictures.workflows).toEqual(expect.arrayContaining(pictures));
+ for (const id of reads) expect(onlyPictures.workflows).not.toContain(id);
+ expect(onlyPictures.missing.some((m) => m.files.includes("input:video"))).toBe(true);
+ });
+
+ it("the inventory's hash covers the kinds of input, and the worker hashes it the same way", async () => {
+ const { inventoryHash: workerHash } = await import("../bin/lib/worker/inventory.mjs");
+ const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };
+ expect(pool.inventoryHash({ ...inv, media: ["image"] })).not.toBe(pool.inventoryHash(inv));
+ expect(pool.inventoryHash({ ...inv, media: ["video", "image"] })).toBe(pool.inventoryHash({ ...inv, media: ["image", "video"] }));
+ expect(workerHash({ ...inv, media: ["image", "audio"] })).toBe(pool.inventoryHash({ ...inv, media: ["image", "audio"] }));
+ const w = worker("media");
+ const saved = pool.saveInventory(row(w), { ...inv, media: ["image", "teleport"] });
+ expect(saved.lanes).toBeDefined();
+ expect(JSON.parse(row(w).inventory_json ?? "{}").media).toEqual(["image"]);
+ });
+});