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: the owner's own job makes room for a person's run

Adarshf02516422ef5
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 23d0ef63..e2ff4194 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -385,7 +385,14 @@ default). It also keeps:
and its VRAM;
- its class: `paid` or `free` for an account's run (the billing service says which; `free` without one), `owner` for
the owner's own jobs. People's runs always go first: the owner's jobs wait until no person's run waits that the
- same worker could take.
+ same worker could take. In the modes People first (the default) and People only, a worker that runs one of the
+ owner's own jobs on its GPU makes room for a person: when a person's run waits that this worker can take, and no
+ other worker that is free can take it, the beat answer lists the owner's job in `stops`. The worker takes its
+ prompt off its ComfyUI, and the job goes back in line with no attempt counted and its `rank_at` kept. The worker's
+ next claim takes the person's run, and the owner's job runs again from the start once no person waits. Its run says
+ "Paused for a moment · starts again automatically" until then. A person's run is never stopped for another person,
+ and neither is a job that is saving its results, one whose finished results the worker keeps, or its CPU slot's
+ task. An older worker reads `stops` as it always did.
- `rank_at`: `created_at`, minus the head start the billing service gave the run inside its class (at most a day). Only
people's runs get a head start: the owner's own jobs keep `created_at`, so they go in the order they came. A job that
goes back in line keeps its `rank_at`, so it keeps its place.
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 61eddc3e..bc6f30c9 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -538,6 +538,8 @@ export const POOL_WORDS = {
working: "Working",
/** Working, with its model still loading (the GPU had another one loaded): no progress yet. */
gettingReady: "Warming up · starting in a moment",
+ /** The owner's own run, given back to the line so that a person's run could start first (pool.ts, people first). */
+ paused: "Paused for a moment · starts again automatically",
failed: "That one didn't come out right — try again, or try a similar model.",
} as const;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 50c19fb4..8b497463 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -4,7 +4,7 @@ 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, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, packKey, partLanes, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";
-import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";
+import { POOL_WORDS, RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";
import { runtimeFileKeys } from "@/lib/runtime-files";
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
@@ -378,6 +378,16 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
stops.push({ task: t.id, promptId: t.prompt_id, ...(t.prefix && { prefix: t.prefix }) });
}
d.prepare("UPDATE relay_workers SET stop_now = 0 WHERE id = ?").run(w.id);
+ } else {
+ // People first: the owner's own job on its GPU goes back in line when a person's run waits that this worker can
+ // take and no other free worker can. No attempt counted, its place among the owner's jobs kept; it runs again
+ // from the start once no person waits. Never a person's run, never its CPU slot's task.
+ for (const t of ownerJobsToPreempt(fresh, new Set(b.held ?? []), now)) {
+ if (!backInLine(t, { blame: false, sentBack: "made room for a person's run" })) continue;
+ const back = taskById(t.id);
+ if (back) setTask(t.id, { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(back.extra_json, {}), preempted: now }) });
+ stops.push({ task: t.id, promptId: t.prompt_id, ...(t.prefix && { prefix: t.prefix }) });
+ }
}
const state = workerState(fresh, now);
if (state.state !== before?.state) {
@@ -427,6 +437,31 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
}).immediate();
}
+/**
+ * The owner's own jobs this worker's GPU runs that go back in line for people (workerBeat), in People first and People
+ * only: while it may take work, a person's run waits that it can take, and no other worker that is free (taking work,
+ * its GPU's slot empty) can take that run. Not one that is saving its results, nor one whose finished results the
+ * worker keeps, nor light CPU work.
+ */
+function ownerJobsToPreempt(w: WorkerRow, held: Set<string>, now: number): TaskRow[] {
+ // Only where people come before the owner's own jobs (People first, People only); never in Our work first or Balanced.
+ const mode = effectiveMode(w, now).mode;
+ if (mode !== "people-first" && mode !== "people-only") return [];
+ if (!eligible(w, now)) return [];
+ const d = db();
+ const mine = (d.prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running') AND stop = 0").all(w.id, slotDevice(w, "gpu")) as TaskRow[]).filter(
+ (t) => classRank(t) === OWNER_CLASS && t.slot !== "cpu" && !t.finish_json && !held.has(t.id),
+ );
+ if (!mine.length) return [];
+ const people = gpuClaimableRows(w, now, "people");
+ if (!people.length) return [];
+ const others = (d.prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND id != ?").all(w.id) as WorkerRow[]).filter(
+ (o) => eligible(o, now) && !d.prepare("SELECT 1 FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting')").get(o.id, slotDevice(o, "gpu")),
+ );
+ const someoneElse = (t: TaskRow) => others.some((o) => fitsSlot(t, o, now, "gpu") && retryOk(t, o, now) && beforeWindowEnds(t, o, now));
+ return people.some((t) => !someoneElse(t)) ? mine : [];
+}
+
/**
* People's tasks (an account's, never the owner's own) this worker may claim right now: in its pool, in a lane it is
* allowed and able to run, with the files and VRAM they need, past their delays, and ending before its hours do. Its
@@ -446,13 +481,17 @@ export function ownerWaitingNow(w: WorkerRow, now = Date.now()): number {
}
function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): number {
- if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;
+ return gpuClaimableRows(w, now, whose).length;
+}
+
+function gpuClaimableRows(w: WorkerRow, now: number, whose: "people" | "owner"): TaskRow[] {
+ if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return [];
const c = controlsOf(w, now);
// Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room (left out in the query, so a long
// line of CPU work never hides the GPU's).
const rows = lineRows(LINE_COLS, `pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS ${whose === "people" ? "NOT NULL" : "NULL"} AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}`, [`,${w.pool},`], c, LOOK_AT);
const fit = rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
- if (plainLine(c)) return fit.length;
+ if (plainLine(c)) return fit;
// Held runs and people, runs pinned to another worker, and the owner's own jobs in People only don't count. In Our work
// first, while local work on its PC runs, people's runs ask it for no room unless the owner sent them next or boosted
// them: the owner's work keeps the GPU, and people's runs start once it is free.
@@ -460,7 +499,7 @@ function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): num
return fit.filter((t) => {
const tc = taskControl(t, classRank(t), c, w.id);
return !tc.out && (!keepGpu || tc.tier < 2);
- }).length;
+ });
}
/** The controls one look at the line reads: the mode of this worker (or of a pool: `w` its name) and the live overrides. */
@@ -658,7 +697,10 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed
// A job ticket's task keeps the time of its claim before this one, and which claim that note is for (`claimFor`, this
// claim's time): a refusal of the ticket on this same claim, before anything ran (another catalog, more than the PC
// allows), puts it back as it was, so a task no worker ever ran keeps its wait limit.
- const before = t.ticket_json && t.state === "waiting" ? { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), claimedBefore: t.claimed_at ?? null, claimFor: now }) } : {};
+ // A run given back for people (workerBeat) is no longer paused once a worker takes it again.
+ const { preempted, ...extra } = json<Record<string, unknown>>(t.extra_json, {});
+ const ticketNote = !!t.ticket_json && t.state === "waiting";
+ const before = ticketNote || preempted !== undefined ? { extra_json: JSON.stringify({ ...extra, ...(ticketNote && { claimedBefore: t.claimed_at ?? null, claimFor: now }) }) } : {};
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 GPU job taken by a worker with another model loaded (or none) loads its model first: it is "getting ready" until
// its first step reports. A light CPU job and a finishing job load none.
@@ -1455,6 +1497,8 @@ export const poolWaitMs = () => {
/** The waiting words of a task for workers ("Waiting for a GPU · 2 ahead", "No GPU is on now"). */
export function poolWaitWords(t: TaskRow, now = Date.now()): string {
+ // The owner's own run, given back so that a person's run could start first: it starts again by itself.
+ if (json<{ preempted?: unknown }>(t.extra_json, {}).preempted !== undefined) return POOL_WORDS.paused;
const p = placeInLine(t, now);
if (p.etaSeconds === null) return "Waiting for a GPU to come on";
return p.place > 1 ? `Waiting for a GPU · ${p.place - 1} ahead` : "Next for a GPU";
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index 5a969ad1..ecfef0da 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -89,7 +89,7 @@ function addWorker(): W {
let gens = 0;
/** A job for the workers that loads one input (a picture, or a clip) and saves a picture (or what `save` says). */
-function addTask(o: { clip?: Buffer; save?: { class_type: string; inputs: Record<string, unknown> } } = {}): { id: string; input: string } {
+function addTask(o: { clip?: Buffer; save?: { class_type: string; inputs: Record<string, unknown> }; account?: string } = {}): { id: string; input: string } {
const gid = `recovery-gen-${++gens}`;
const now = Date.now();
db()
@@ -101,7 +101,7 @@ function addTask(o: { clip?: Buffer; save?: { class_type: string; inputs: Record
principal: "owner",
generationId: gid,
graph: { "1": loader, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": o.save ?? { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },
- pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
+ pool: { pools: ["pool"], account: o.account, rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
});
return { id: t.id, input };
}
@@ -645,6 +645,33 @@ describe("the worker's timeline", () => {
});
});
+describe("people first", () => {
+ it("a person's run that waits stops the owner's job on its ComfyUI: back in line with no attempt counted, then it runs again from the start", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const own = addTask();
+ start(w, s, p, { steps: 30, stepMs: 150 });
+ await until(async () => {
+ const c = comfyOf(p);
+ return state(own.id).state === "running" && c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2;
+ });
+ // A person's run comes (this harness can't run an account's job: the worker gives it back, and the line has only
+ // the owner's job again).
+ const person = addTask({ account: "acct-preempt" });
+ await until(() => state(own.id).state === "waiting" && state(own.id));
+ expect(state(own.id).requeues).toBe(0);
+ expect(pool.poolWaitWords(state(own.id))).toBe("Paused for a moment · starts again automatically");
+ // The worker took the person's run next.
+ await until(() => state(person.id).claimed_at && state(person.id));
+ const t = await ended(own.id);
+ expect(t.state).toBe("done");
+ expect(t.requeues).toBe(0);
+ // Its ComfyUI got the owner's prompt twice: the one it stopped, and the run from the start.
+ expect(prompts(p)).toBe(2);
+ }, 120_000);
+});
+
describe("new worker code", () => {
/** A watch on a checkout of its own (its parts taken as whole) and the PC's home folder, looked at every turn. */
function watch(p: Pc) {
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index b205cebb..ec3c2cc8 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -459,6 +459,83 @@ describe("order (checks 8, 9)", () => {
});
});
+describe("people first: the owner's own job on a worker makes room for a person's run", () => {
+ const PAUSED = "Paused for a moment · starts again automatically";
+
+ it("the beat stops the owner's job, which goes back in line with no attempt counted and its place kept; the person's run is claimed next; then the owner's job runs again", () => {
+ const w = worker("preempt");
+ const owner1 = task({ rankAgoMs: 10 * MIN });
+ const owner2 = task({ rankAgoMs: 5 * MIN });
+ expect(claim(w)?.id).toBe(owner1);
+ const rank = state(owner1).rank_at;
+ // No person waits: the owner's job goes on.
+ expect(beat(w, {}, [owner1]).stops).toEqual([]);
+ const person = task({ account: "acct-p" });
+ const a = beat(w, {}, [owner1]);
+ expect(a.stops.map((x) => x.task)).toEqual([owner1]);
+ const back = state(owner1);
+ expect(back.state).toBe("waiting");
+ expect(back.requeues).toBe(0);
+ expect(back.worker_id).toBeNull();
+ expect(back.rank_at).toBe(rank);
+ expect(pool.poolWaitWords(back, clock)).toBe(PAUSED);
+ // The next claim takes the person's run, then the owner's jobs in their own order.
+ expect(claim(w)?.id).toBe(person);
+ expect(beat(w, {}, [person]).stops).toEqual([]);
+ db().prepare("UPDATE relay_tasks SET state = 'done' WHERE id = ?").run(person);
+ expect(claim(w)?.id).toBe(owner1);
+ expect(JSON.parse(state(owner1).extra_json ?? "{}").preempted).toBeUndefined();
+ expect(state(owner2).state).toBe("waiting");
+ expect(pool.poolWaitWords(state(owner2), clock)).not.toBe(PAUSED);
+ });
+
+ it("never a person's run for another person, paid or free", () => {
+ const w = worker("people");
+ const a = task({ account: "acct-a", rankAgoMs: 2 * MIN });
+ expect(claim(w)?.id).toBe(a);
+ task({ account: "acct-b" });
+ db().prepare("UPDATE relay_tasks SET class = 'paid' WHERE state = 'waiting' AND account = 'acct-b'").run();
+ expect(beat(w, {}, [a]).stops).toEqual([]);
+ expect(state(a).worker_id).toBe(w.id);
+ });
+
+ it("not while another free worker can take the person's run, nor a job saving its results, nor one whose results the worker keeps", () => {
+ const w = worker("busy-owner");
+ const own = task({ rankAgoMs: 5 * MIN });
+ expect(claim(w)?.id).toBe(own);
+ const idle = worker("idle");
+ task({ account: "acct-p" });
+ expect(beat(w, {}, [own]).stops).toEqual([]);
+ // The other worker goes away: now the owner's job makes room, unless its results are being saved or kept.
+ pool.patchWorker(idle.id, { paused: true });
+ db().prepare("UPDATE relay_tasks SET state = 'collecting' WHERE id = ?").run(own);
+ expect(beat(w, {}, [own]).stops).toEqual([]);
+ db().prepare("UPDATE relay_tasks SET state = 'running' WHERE id = ?").run(own);
+ const b = pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [{ task: own }], stopped: [], held: [own] }), clock);
+ expect(b.stops).toEqual([]);
+ expect(beat(w, {}, [own]).stops.map((x) => x.task)).toEqual([own]);
+ });
+
+ it("not when the person's run can't run on this worker, nor while the worker may take no work", () => {
+ const w = worker("other-lane", { lanes: [LANE_A] });
+ const own = task({ rankAgoMs: 5 * MIN });
+ expect(claim(w)?.id).toBe(own);
+ task({ account: "acct-p", lane: LANE_B });
+ expect(beat(w, {}, [own]).stops).toEqual([]);
+ task({ account: "acct-q" });
+ // Our work first and Balanced keep the owner's job going; People first (the default) makes room.
+ for (const mode of ["ours-first", "balanced"]) {
+ db().prepare("UPDATE relay_workers SET mode_json = ? WHERE id = ?").run(JSON.stringify({ mode, until: null, by: "test", at: clock }), w.id);
+ expect(beat(w, {}, [own]).stops).toEqual([]);
+ }
+ db().prepare("UPDATE relay_workers SET mode_json = NULL WHERE id = ?").run(w.id);
+ pool.patchWorker(w.id, { drain: true });
+ expect(beat(w, {}, [own]).stops).toEqual([]);
+ pool.patchWorker(w.id, { drain: false });
+ expect(beat(w, {}, [own]).stops.map((x) => x.task)).toEqual([own]);
+ });
+});
+
describe("people's runs this worker may take now (the beat's claimableNow)", () => {
it("counts people's waiting runs it can run here, never the owner's own, and not runs for other lanes, files or VRAM", () => {
const w = worker("counts", { lanes: [LANE_A], workflows: ["wf-a"], vram: 12 * GB });