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.

Queue view: each waiting job says which workers can run it, why the others can't, and their state

Adarshdf6f0d1ba7a0
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 71864608..b908b682 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -3,7 +3,7 @@ import { ENGINE_WORDS } from "@/lib/engine-error";
import crypto from "node:crypto";
import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";
import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";
-import { allLanes, filesBytes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, memoryFit, needsOf, packKey, partLanes, streamFits, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs, type StreamRule } from "@/lib/lanes";
+import { allLanes, filesBytes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, memoryFit, minVramBytesFor, needsOf, packKey, partLanes, streamFits, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs, type StreamRule } from "@/lib/lanes";
import { fileChoices, hasVariants, pickFiles, swapGraphFiles, type FileChoice } from "@/lib/gpu/model-variants";
import type { FileKey } from "@/lib/gpu/types";
import { POOL_WORDS, RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";
@@ -1061,52 +1061,135 @@ function estOn(t: TaskRow, w: WorkerRow): number | null {
return (t.lane && benchOf(w)[t.lane]?.medianMs) || t.est_ms || null;
}
+/**
+ * Why a worker can't run a task (fitWhy, fitSlotWhy), the first reason found: "pool" (not one of the task's pools),
+ * "elsewhere" (sent to another worker), "stopped", "lane-off" (its lane isn't allowed there), "ceiling" (beyond what its
+ * PC may ever run), "version" (its worker program or catalog doesn't take the job's ticket), "refused" (it refused the
+ * job before), "files" (it hasn't the workflow's files), "run-files" (it hasn't the files the run adds), "memory" (too
+ * little GPU memory, streaming from RAM counted), "finish" (no slot of it runs this finishing step), "delay" (its delays
+ * haven't passed yet).
+ */
+export type FitCode = "pool" | "elsewhere" | "stopped" | "lane-off" | "ceiling" | "version" | "refused" | "files" | "run-files" | "memory" | "finish" | "delay";
+
/**
* May this worker run this task: its pool, its lane allowed and capable, its PC's ceiling (the lanes or workflows it
* may ever run, the largest picture, the longest clip, the most results), its build's catalog for a job ticket, its
- * files (the run-time files the run adds too), its VRAM, and the delays.
+ * files (the run-time files the run adds too), its VRAM, and the delays. Null: it may; else the first reason it may not.
*/
-function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
- if (!(t.pools ?? "").split(",").includes(w.pool)) return false;
- if (t.only_worker && t.only_worker !== w.id) return false;
- if (t.stop) return false;
+function fitWhy(t: TaskRow, w: WorkerRow, now: number): FitCode | null {
+ if (!(t.pools ?? "").split(",").includes(w.pool)) return "pool";
+ if (t.only_worker && t.only_worker !== w.id) return "elsewhere";
+ if (t.stop) return "stopped";
const allow = allowOf(w);
const lane = t.lane ?? "";
- if (!(lane in allow)) return false;
+ if (!(lane in allow)) return "lane-off";
const cap = capableOf(w);
const needs = json<Needs | null>(t.needs_json, null);
- if (ceilingProblem(ceilingOf(w), { workflowId: needs?.workflowId, lane, size: needs?.size })) return false;
+ if (ceilingProblem(ceilingOf(w), { workflowId: needs?.workflowId, lane, size: needs?.size })) return "ceiling";
// A ticket made for another catalog than the worker's goes only to a worker that checks the graph itself
// (GRAPH_PROTOCOL), with the ticket's graph fingerprint to check. One that found the graph changed gave the job back
// (refusedBy, below) and isn't offered it again until it is updated.
- if (needs?.catalogVersion && needs.catalogVersion !== w.catalog_version && !(needs.graphSha && !!w.catalog_version && (w.protocol ?? 0) >= GRAPH_PROTOCOL)) return false;
+ if (needs?.catalogVersion && needs.catalogVersion !== w.catalog_version && !(needs.graphSha && !!w.catalog_version && (w.protocol ?? 0) >= GRAPH_PROTOCOL)) return "version";
// 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;
+ if (needs?.catalogVersion && (w.protocol ?? 0) < TICKET_PROTOCOL) return "version";
+ if (refusedBy(t).includes(refusalKey(w))) return "refused";
+ if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return "files";
// The files the run adds beyond its workflow's own (a look's LoRAs): only a worker that verified each one.
- if (needs?.runtime?.length && !hasFiles(inventoryOf(w), needs.runtime)) return false;
+ if (needs?.runtime?.length && !hasFiles(inventoryOf(w), needs.runtime)) return "run-files";
// A workflow with model variants: the files (its own or a variant's) and the memory of the choice this worker would
// run. Either way, streaming from RAM counts as well as the VRAM need (memoryFit).
if (needs?.workflowId && hasVariants(loadIndex(), needs.workflowId)) {
- if (!workerFiles(w, needs.workflowId, bytesOf(needs.runtime))) return false;
- } else if (!memoryFor(needs, w)) return false;
- if (now - t.created_at < w.claim_after_ms + (allow[lane]?.delayMs ?? 0)) return false;
- return true;
+ if (!workerFiles(w, needs.workflowId, bytesOf(needs.runtime))) return variantWhy(w, needs.workflowId);
+ } else if (!memoryFor(needs, w)) return "memory";
+ if (now - t.created_at < w.claim_after_ms + (allow[lane]?.delayMs ?? 0)) return "delay";
+ return null;
+}
+
+/**
+ * Why workerFiles has no choice for a workflow with model variants: "memory" when a file set it has would do with all
+ * the GPU memory there is, else "files". Asked only once the choice failed.
+ */
+function variantWhy(w: WorkerRow, workflowId: string): FitCode {
+ const roomy = { ...w, facts_json: JSON.stringify({ ...json<ComputerFacts>(w.facts_json, {}), vramBytes: Number.MAX_SAFE_INTEGER }) };
+ return workerFiles(roomy, workflowId) ? "memory" : "files";
}
/**
* 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.
+ * slot; anything else only in its GPU's slot. Then `fitWhy` as for any task. Null: it may; else the first reason.
*/
-function fitsSlot(t: TaskRow, w: WorkerRow, now: number, slot: WorkerSlot): boolean {
- if (slotFor(t, w) !== slot) return false;
+function fitSlotWhy(t: TaskRow, w: WorkerRow, now: number, slot: WorkerSlot): FitCode | null {
+ if (slotFor(t, w) !== slot) return "finish";
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);
+ if (kind === null) return fitWhy(t, w, now);
+ if (!(t.pools ?? "").split(",").includes(w.pool)) return "pool";
+ if (t.only_worker && t.only_worker !== w.id) return "elsewhere";
+ if (t.stop) return "stopped";
+ if (refusedBy(t).includes(refusalKey(w))) return "refused";
+ return cpuSlotOf(w)?.finishes.includes(kind) ? null : "finish";
+}
+
+/** May this slot of this worker run this task (fitSlotWhy)? */
+function fitsSlot(t: TaskRow, w: WorkerRow, now: number, slot: WorkerSlot): boolean {
+ return fitSlotWhy(t, w, now, slot) === null;
+}
+
+/** Each reason a worker can't run a task, in plain words (a worker of another pool isn't listed). */
+export const FIT_WORDS: Record<Exclude<FitCode, "pool">, string> = {
+ elsewhere: "sent to another worker",
+ stopped: "stopped",
+ "lane-off": "not allowed this kind of job",
+ ceiling: "beyond what its PC may run",
+ version: "needs its worker program updated",
+ refused: "refused it before",
+ files: "lacks its model files",
+ "run-files": "lacks the files this run adds",
+ memory: "needs more GPU memory",
+ finish: "doesn't run this finishing step",
+ delay: "takes it after its delay",
+};
+
+/**
+ * A worker's state in one word for a run's fit: taking jobs ("idle": ready, or behind the site's version, when the fit
+ * says which jobs it takes), running one ("busy"), not taking any now ("paused": paused in either place, finishing its
+ * last job before a pause, outside its hours, its GPU or ComfyUI taken or down, local work first), or not heard from
+ * ("offline").
+ */
+export type FitState = "idle" | "busy" | "paused" | "offline";
+
+export const fitState = (s: WorkerState): FitState => (s === "idle" || s === "update-worker" ? "idle" : s === "busy" ? "busy" : s === "offline" || s === "new" ? "offline" : "paused");
+
+/** Whether one worker can run a run, why not (`code`, `words`: FIT_WORDS), and its state (`stateCode`, `stateWords`: workerState). */
+export interface WorkerFit {
+ name: string;
+ can: boolean;
+ code: Exclude<FitCode, "pool"> | null;
+ words: string | null;
+ state: FitState;
+ stateCode: WorkerState;
+ stateWords: string;
+}
+
+/** Which workers of a run's pools can run it and in what state they are, and the GPU memory it needs in whole GB (null: none named). */
+export interface RunFit {
+ needGb: number | null;
+ workers: WorkerFit[];
+}
+
+/**
+ * Which workers can run this task, by the claim's own rules (fitSlotWhy, for the slot each would take it in; delays
+ * aside), and the state each one is in. `workers`: each worker with its workerState, read once for a whole view.
+ */
+export function runFit(t: TaskRow, workers: readonly { w: WorkerRow; state: { state: WorkerState; words: string } }[], now = Date.now()): RunFit {
+ const fit: WorkerFit[] = [];
+ for (const { w, state } of workers) {
+ const code = fitSlotWhy({ ...t, created_at: 0 }, w, now, slotFor(t, w));
+ if (code === "pool") continue;
+ fit.push({ name: w.name, can: code === null, code, words: code ? FIT_WORDS[code] : null, state: fitState(state.state), stateCode: state.state, stateWords: state.words });
+ }
+ const need = json<Needs | null>(t.needs_json, null)?.minVramBytes ?? 0;
+ return { needGb: need > 0 ? Math.round(need / minVramBytesFor(1)) : null, workers: fit };
}
/** The retry rule: a worker that lost or failed this task takes it again only when no other capable worker is about. */
diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.ts
index 668a907c..73c05938 100644
--- a/src/server/computer/queue-live.ts
+++ b/src/server/computer/queue-live.ts
@@ -6,7 +6,7 @@ import { laneLabel } from "@/lib/lanes";
import { HOLDING_OTHER, HOLDING_WHY, SENT_STATES, type WorkerHolding } from "@/lib/relay";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
-import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ownerHandsOn, ownerWaitingNow, workerState } from "./pool";
+import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ownerHandsOn, ownerWaitingNow, runFit, workerState, type RunFit } from "./pool";
import { controlWords, effectiveMode, liveOverrides, MODE_WORDS, overrideView, personKey, poolMode, poolModes, recentOverrides, sweepControls, workerModeOf, type EffectiveMode, type OverrideView, type QueueMode } from "./queue-controls";
import type { LocalWork } from "@/lib/relay";
import { json, taskCold, taskProgress, type TaskRow, jobNowOf, type JobNow } from "./tasks";
@@ -75,6 +75,11 @@ export interface QueuedJob {
guest: boolean;
/** The owner's hands-on run (pool.ts ownerHandsOn): it waits and runs as a person's run does. */
handsOn?: true;
+ /**
+ * Which workers of its pools can run it, why the others can't ("lacks its model files", "needs more GPU memory"), and
+ * the state each one is in (pool.ts runFit), with the GPU memory it needs.
+ */
+ fit: RunFit;
}
/** A worker's mode and the local work on its PC, for the owner's Queue page. */
@@ -222,6 +227,8 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
const items = lines.flatMap((l) => l.items.map((x) => ({ ...x, mode: l.mode }))).filter((x) => !seen.has(x.task.id) && !!seen.add(x.task.id));
const ordered = [...items.filter((x) => x.rank !== null), ...items.filter((x) => x.rank === null)];
const nameOf = (id: string) => byId.get(id)?.name ?? null;
+ // Each worker's state, read once for the fit of every job listed.
+ const stateOf = workers.map((w) => ({ w, state: workerState(w, now) }));
const queued: QueuedJob[] = ordered.slice(0, QUEUED_LIMIT).map(({ task: t, rank, base, control, mode }) => {
const g = genOf(t.generation_id);
const o = control.by;
@@ -242,6 +249,7 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
person: t.account ? personKey(t.account) : null,
guest: !!t.account?.startsWith("guest"),
...(ownerHandsOn(t) && { handsOn: true as const }),
+ fit: runFit(t, stateOf, now),
};
});
diff --git a/tests/admin-queue-live.test.ts b/tests/admin-queue-live.test.ts
index 1cff651e..a346fbb1 100644
--- a/tests/admin-queue-live.test.ts
+++ b/tests/admin-queue-live.test.ts
@@ -210,8 +210,8 @@ describe("what the workers do now", () => {
db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 9 * MIN, b.id);
// People first: the account's run ahead of the owner's own, although the owner's came first.
expect(liveQueue(clock).queued).toEqual([
- { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "People first", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false },
- { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN, rank: 2, why: "Our work: after people's runs", code: "class", override: null, person: null, guest: false },
+ { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "People first", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false, fit: { needGb: null, workers: [] } },
+ { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN, rank: 2, why: "Our work: after people's runs", code: "class", override: null, person: null, guest: false, fit: { needGb: null, workers: [] } },
]);
// A worker takes the account's run first (people's runs go before the owner's own): the owner's stays in line.
const w = worker("takes");
diff --git a/tests/queue-fit.test.ts b/tests/queue-fit.test.ts
new file mode 100644
index 00000000..a3b5535a
--- /dev/null
+++ b/tests/queue-fit.test.ts
@@ -0,0 +1,143 @@
+/**
+ * A waiting job's fit in the owner's queue view (GET /api/admin/queue, `queued[].fit`): which workers of its pools can
+ * run it by the claim's own rules (pool.ts runFit over fitSlotWhy), why the others can't, and the state each one is in.
+ */
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-queue-fit-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+
+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 workers = await import("@/server/computer/workers");
+const { liveQueue } = await import("@/server/computer/queue-live");
+
+const LANE = "aaaaaaaaaaaa";
+const MIN = 60_000;
+const GB = 2 ** 30;
+let clock = Date.now();
+
+type W = { id: string; token: string };
+const row = (w: W) => workers.getWorker(w.id)!;
+
+function worker(name: string, o: { vramGb: number; workflows?: string[]; lanes?: string[]; pool?: string; allow?: boolean } = { vramGb: 32 }): W {
+ const w = pool.addWorker(name, o.pool ?? "pool");
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: o.allow === false ? {} : { [LANE]: { delayMs: 0 } }, claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: o.lanes ?? [LANE], workflows: o.workflows ?? ["wf-a"] }), JSON.stringify({ vramBytes: o.vramGb * GB }), w.id);
+ beat(w);
+ return w;
+}
+
+function beat(w: W, o: { local?: { paused?: boolean; why?: string | null } } = {}) {
+ return pool.workerBeat(
+ row(w),
+ pool.cleanBeat({
+ device: `wkr-${w.id}`,
+ protocol: 2,
+ version: "1.0.0",
+ local: { paused: o.local?.paused ?? false, why: o.local?.why ?? null, until: null },
+ gpu: {},
+ inventoryHash: null,
+ running: [],
+ stopped: [],
+ }),
+ clock,
+ );
+}
+
+let gens = 0;
+function task(o: { needGb?: number; workflowId?: string; account?: string } = {}): { id: string; gid: string } {
+ const gid = `fit-gen-${++gens}`;
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, message, request_json, outputs_json, created_at, updated_at) VALUES (?, 'video', 'm-test', 'open', 'comfyui', 'upscale', 'video', 'queued', NULL, ?, '[]', ?, ?)",
+ )
+ .run(gid, JSON.stringify(o.account ? { account: o.account } : {}), clock, clock);
+ const t = tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], account: o.account, rankAt: clock, lane: LANE, needs: { workflowId: o.workflowId ?? "wf-a", files: [], packs: [], minVramBytes: Math.round((o.needGb ?? 0) * GB * 0.97) } },
+ });
+ return { id: t.id, gid };
+}
+
+const fitOf = (gid: string) => liveQueue(clock).queued.find((q) => q.generationId === gid)!.fit;
+
+beforeAll(() => setSetting("comfyWhere", "workers"));
+beforeEach(() => {
+ resetRates();
+ clock += 60 * MIN;
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued','running')").run();
+});
+
+describe("a waiting job's fit", () => {
+ it("names the one worker that can run it, paused here, and why the others can't", () => {
+ const big = worker("Big", { vramGb: 32 });
+ worker("Mid", { vramGb: 10, workflows: [] });
+ worker("Small", { vramGb: 8, workflows: [] });
+ beat(big, { local: { paused: true } });
+ const { gid } = task({ needGb: 24, account: "acct-1" });
+ expect(fitOf(gid)).toEqual({
+ needGb: 24,
+ workers: [
+ { name: "Big", can: true, code: null, words: null, state: "paused", stateCode: "paused", stateWords: "Paused here" },
+ { name: "Mid", can: false, code: "files", words: "lacks its model files", state: "idle", stateCode: "idle", stateWords: "Ready" },
+ { name: "Small", can: false, code: "files", words: "lacks its model files", state: "idle", stateCode: "idle", stateWords: "Ready" },
+ ],
+ });
+ });
+
+ it("says a worker with the files and too little GPU memory needs more", () => {
+ worker("Mid", { vramGb: 10 });
+ const { gid } = task({ needGb: 24 });
+ expect(fitOf(gid).workers).toEqual([expect.objectContaining({ name: "Mid", can: false, code: "memory", words: "needs more GPU memory", state: "idle" })]);
+ });
+
+ it("says a worker that may not take its lane isn't allowed it, and leaves out a worker of another pool", () => {
+ worker("Closed", { vramGb: 32, allow: false });
+ worker("Elsewhere", { vramGb: 32, pool: "other" });
+ const { gid } = task();
+ expect(fitOf(gid)).toEqual({ needGb: null, workers: [expect.objectContaining({ name: "Closed", can: false, code: "lane-off", words: "not allowed this kind of job" })] });
+ });
+
+ it("says an offline worker is offline, and a worker paused on the website is paused", () => {
+ const gone = worker("Gone", { vramGb: 32 });
+ const held = worker("Held", { vramGb: 32 });
+ pool.patchWorker(held.id, { paused: true });
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(clock - 60 * MIN, gone.id);
+ const { gid } = task();
+ expect(fitOf(gid).workers).toEqual([
+ expect.objectContaining({ name: "Gone", can: true, state: "offline", stateCode: "offline", stateWords: "Offline" }),
+ expect.objectContaining({ name: "Held", can: true, state: "paused", stateWords: "Paused on the website" }),
+ ]);
+ });
+
+ it("agrees with the claim: the worker it says can run the job takes it once it may", () => {
+ const big = worker("Big", { vramGb: 32 });
+ const mid = worker("Mid", { vramGb: 10 });
+ beat(big, { local: { paused: true } });
+ const { id, gid } = task({ needGb: 24 });
+ expect(fitOf(gid).workers.map((x) => [x.name, x.can])).toEqual([["Big", true], ["Mid", false]]);
+ expect(pool.workerClaim(row(mid), [], clock)).toBeNull();
+ beat(big);
+ expect(pool.workerClaim(row(big), [], clock)?.id).toBe(id);
+ });
+
+ it("is quiet about a job with no worker at all", () => {
+ const { gid } = task({ needGb: 24 });
+ expect(fitOf(gid)).toEqual({ needGb: 24, workers: [] });
+ });
+});