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 hands-on run waits with people's runs, and Run next asks local work for room

Adarsh12519c013e46
diff --git a/docs/admin-api.md b/docs/admin-api.md
index 960c7b2b..44e737dd 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -115,7 +115,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `POST /api/admin/outputs/remove` | the same, and `evidence?: true` to keep the files in a locked folder | `{ removed }` |
| `GET /api/admin/files/{path}` | `Range` works | the file, an account's or the owner's own (held ones too); 404 for unknown paths |
| `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |
-| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). A `holding` row for a worker that holds back the line (`task` null) names the job it would take first (`generationId`, `model`, `op`, `principal`). `controls`: `{ pools, workers, overrides, ended, modes }` ([gpu-workers.md](gpu-workers.md#the-queue)) |
+| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). A `holding` row for a worker that holds back the line (`task` null) names the job it would take first (`generationId`, `model`, `op`, `principal`). A run of the owner's that the owner made by hand (no `source`) has `handsOn: true` in `queued`, `running` and `holding`: it waits with people's runs, and its `why` says "Your run". `controls`: `{ pools, workers, overrides, ended, modes }` ([gpu-workers.md](gpu-workers.md#the-queue)) |
| `POST /api/admin/queue/mode` | `{ pool?, worker?, mode, forMin? }`: `mode` is `people-first`, `people-only`, `ours-first`, `balanced`, or `null` (back to normal); `forMin` is 1 to 10080, or `null` (until switched back) | `{ mode, before }`; 400 for a value out of bounds, 404 for no such worker |
| `GET /api/admin/queue/overrides` | | `{ live, ended }` (the last 20 that ended) |
| `POST /api/admin/queue/overrides` | `{ kind: "run", generationId, action: "next" | "hold", worker?, forMin? }` or `{ kind: "person", person | account, action: "boost" | "hold", forMin }` (`forMin` is needed for a boost) | 201 `{ override, replaced }`; 404 for no such run, worker or person with a run on the GPUs; 409 for a run that ended |
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 775be09c..c696108d 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -394,7 +394,11 @@ default). It also keeps:
- what it needs: the workflow, its files (folder, name, exact size, and SHA-256 where it is pinned), its node packs
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
+ the owner's own jobs: the runs a script said it made (`source` on `POST /api/generations`: `batch`, `drill`,
+ `example` or `test`), and every other step of the same press of Run. The owner's hands-on run (no `source`) is
+ `free`, like a person's run: it waits in line with people's runs (a later step keeps its run's place), counts in the
+ beat's `claimableNow` (so local work makes room for it), is taken in People only, and never waits for a warm lane.
+ The worker still gets `class: "owner"` with it in its claim, since it comes as a graph. People's runs always go first: the owner's jobs wait until no person's run waits that the
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
@@ -934,8 +938,9 @@ its target), at most once an hour each.
"waiting-for-yield", until }`, where `until` is the helper's estimate of the start time, or null. After 3 minutes
with no answer, `why` is `"waiting-for-yield:no-answer"`. The worker may still take jobs, and its jobs keep their
place.
- - The answer also carries `claimableNow`, for studio jobs first: the number of people's jobs (never the owner's own)
- that this worker may take now. `ownerWaitingNow` is the same count for the owner's own jobs: they ask for no turn,
+ - The answer also carries `claimableNow`, for studio jobs first: the number of people's jobs (the owner's hands-on
+ runs and any run the owner sent next too, never the owner's other own jobs) that this worker may take now. `ownerWaitingNow` is the same count for the
+ owner's own jobs: they ask for no turn,
but idle local ComfyUI work is asked to free its memory for them. It counts the jobs in the worker's pool that it can run (its lanes, files and VRAM)
and that end before its hours do. It is 0 while the worker is paused on the website, drains, is outside its hours
or runs an older worker program. The worker's own pause on the PC does not change it. The answer has no wait time
diff --git a/scripts/eval/lib/run.mjs b/scripts/eval/lib/run.mjs
index 699243e2..d296e78b 100644
--- a/scripts/eval/lib/run.mjs
+++ b/scripts/eval/lib/run.mjs
@@ -561,7 +561,8 @@ async function runJob(client, job, ctx) {
watched = routeResult(answer, job.submit.result);
row.steps = (answer.items ?? []).map((g) => g.id);
} else {
- const request = { ...job.request, prompt: mention(job.request.prompt), inputs };
+ // An eval's run is a test run (an account's run drops it): on the install's workers it waits after people's runs.
+ const request = { ...job.request, prompt: mention(job.request.prompt), inputs, source: job.request.source ?? "test" };
row.request = request;
// The preview again with the real prompt: it names the route and the LoRAs it loads.
const p = ctx.element ? await client.request("POST", "/api/generations", { json: request, query: { preview: 1 } }) : job.preview;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 2f726802..29ef6e7d 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -86,6 +86,11 @@ const CLASS_RANK = "(CASE WHEN class = 'paid' THEN 0 WHEN class = 'owner' OR (cl
/** The owner's own jobs' class (classRank): after every person's run. */
const OWNER_CLASS = 2;
export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.class === "paid" ? 0 : t.class === "owner" || (!t.class && !t.account) ? 2 : 1);
+/**
+ * The owner's hands-on run (no account, in a person's class): a run the owner made by hand, which waits, runs and makes
+ * room on a worker's PC as a person's run does. The owner's scripts' runs (a batch, a drill…) stay the owner's class.
+ */
+export const ownerHandsOn = (t: Pick<TaskRow, "class" | "account">): boolean => !t.account && classRank(t) !== OWNER_CLASS;
/**
* The order workers serve waiting tasks in: by class, then by rank (a requeued task keeps its own, so it keeps its
* place), then by when it was made. The claim and the place in line read the same order. With fair share on
@@ -506,7 +511,8 @@ function ownerJobsToPreempt(w: WorkerRow, held: Set<string>, now: number): TaskR
}
/**
- * 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
+ * People's tasks (an account's, the owner's hands-on run: ownerHandsOn, and any run the owner sent next; never the
+ * owner's other own jobs) 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
* own pause doesn't count here (its machine reads this to know whether a person's run waits for it); a pause on the
* website, a drain, an older worker program or being outside its hours does.
@@ -516,7 +522,8 @@ export function claimableNow(w: WorkerRow, now = Date.now()): number {
}
/**
- * The owner's own tasks this worker may claim right now, by the same rules as claimableNow. They never ask local
+ * The owner's own jobs (a batch, a drill…; never a hands-on run, nor one sent next) this worker may claim right now, by the same rules as
+ * claimableNow. They never ask local
* ComfyUI work to make room: its machine reads this only to let an idle local ComfyUI free the memory it keeps.
*/
export function ownerWaitingNow(w: WorkerRow, now = Date.now()): number {
@@ -537,7 +544,14 @@ function gpuClaimableRows(w: WorkerRow, now: number, whose: "people" | "owner"):
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);
+ // By class: people's runs and the owner's hands-on runs, or the owner's own jobs (a batch, a drill…). A run the owner
+ // sent next counts as a person's, whatever its class: local work on the PC makes room for it as for a person's run.
+ const sentNext = JSON.stringify(overrideTargets(c).generations);
+ const byClass =
+ whose === "people"
+ ? `(${CLASS_RANK} <> ${OWNER_CLASS} OR generation_id IN (SELECT value FROM json_each(?)))`
+ : `${CLASS_RANK} = ${OWNER_CLASS} AND generation_id NOT IN (SELECT value FROM json_each(?))`;
+ const rows = lineRows(LINE_COLS, `pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND ${byClass} AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}`, [sentNext, `,${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;
// Held runs and people, runs pinned to another worker, and the owner's own jobs in People only don't count. In Our work
@@ -1547,6 +1561,30 @@ export function runPlaceOf(generationId: string): { class: "paid" | "free"; rank
};
}
+/**
+ * The class of the owner's job on the workers. "owner" (after people's runs) for a run a script said it made
+ * (request.source: a batch, a drill, an example, a test), and for every other step of the same press of Run (its batch:
+ * a join or a first frame a chain adds carries no source of its own). Else "free": a hands-on run, which waits, runs and
+ * makes room on a worker's PC as a person's run does (ownerHandsOn).
+ */
+export function ownerRunClass(generationId: string): "free" | "owner" {
+ const d = db();
+ const g = d.prepare("SELECT batch_id, created_at, json_extract(request_json, '$.source') AS source FROM generations WHERE id = ?").get(generationId) as
+ | { batch_id: string | null; created_at: number; source: unknown }
+ | undefined;
+ if (!g) return "free";
+ if (typeof g.source === "string" && g.source !== "hands-on") return "owner";
+ if (!g.batch_id) return "free";
+ // A press makes its rows together: the batch's rows are read within two days of this one (by the created_at index).
+ const tagged = d
+ .prepare(
+ `SELECT 1 FROM generations WHERE created_at BETWEEN ? AND ? AND batch_id = ?
+ AND COALESCE(json_extract(request_json, '$.source'), 'hands-on') <> 'hands-on' LIMIT 1`,
+ )
+ .get(g.created_at - 2 * 24 * 60 * 60_000, g.created_at + 2 * 24 * 60 * 60_000, g.batch_id);
+ return tagged ? "owner" : "free";
+}
+
/**
* 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).
@@ -1680,7 +1718,7 @@ export function updateOf(w: WorkerRow, now = Date.now()): WorkerUpdate {
const state = !behind ? "current" : behindMs < BEHIND_NOTICE_MS ? "updating" : "behind";
const key = refusalKey(w);
const held = behind
- ? (db().prepare("SELECT extra_json FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND account IS NOT NULL AND INSTR(extra_json, ?) > 0").all(key) as Pick<TaskRow, "extra_json">[]).filter((t) => refusedBy(t).includes(key)).length
+ ? (db().prepare(`SELECT extra_json FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND ${CLASS_RANK} <> ${OWNER_CLASS} AND INSTR(extra_json, ?) > 0`).all(key) as Pick<TaskRow, "extra_json">[]).filter((t) => refusedBy(t).includes(key)).length
: 0;
const waiting = live && w.kind === "pool" ? claimableNow(w, now) : 0;
const words =
diff --git a/src/server/computer/queue-controls.ts b/src/server/computer/queue-controls.ts
index b84318d4..5b62fc55 100644
--- a/src/server/computer/queue-controls.ts
+++ b/src/server/computer/queue-controls.ts
@@ -525,14 +525,19 @@ export function overrideTargets(c: LineControls): { generations: string[]; accou
return { generations: [...new Set(gens)].slice(0, 500), accounts: [...new Set(accounts)].slice(0, 100) };
}
-/** Why a task stands where it does, in the owner's words ("Run next", "Boosted"); the override's `until` says until when. */
-export function controlWords(tc: TaskControl, base: number, mode: QueueMode, workerName: (id: string) => string | null): string {
+/**
+ * Why a task stands where it does, in the owner's words ("Run next", "Boosted"); the override's `until` says until when.
+ * `own`: the owner's hands-on run (pool.ts ownerHandsOn), which stands with people's runs as "Your run".
+ */
+export function controlWords(tc: TaskControl, base: number, mode: QueueMode, workerName: (id: string) => string | null, own = false): string {
const o = tc.by;
if (tc.out === "held") return o?.kind === "person" ? "Held: this person's runs wait" : "Held by the owner";
if (tc.out === "pinned") return `Pinned to ${workerName(o!.workerId!) ?? "another worker"}`;
if (tc.out === "paused") return "Waits: People only";
- if (tc.tier === 0) return o?.workerId ? `Run next on ${workerName(o.workerId) ?? "its worker"}` : "Run next";
+ // A run sent next asks local work on a worker's PC to make room, as a person's run does (pool.ts gpuClaimableRows).
+ if (tc.tier === 0) return `${o?.workerId ? `Run next on ${workerName(o.workerId) ?? "its worker"}` : "Run next"}: starts as soon as the GPU is free and local work makes room`;
if (tc.tier === 1) return "Boosted: this person's runs first";
+ if (own && base !== 2) return mode === "ours-first" ? "Your run: after our work (Our work first)" : mode === "balanced" ? "Your run: by when it came (Balanced)" : "Your run";
if (mode === "ours-first") return base === 2 ? "Our work first" : "After our work (Our work first)";
if (mode === "balanced") return base === 0 ? "Paid run" : "Balanced: by when it came";
return base === 0 ? "Paid run" : base === 1 ? "People first" : "Our work: after people's runs";
diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.ts
index e3017ef1..392540a9 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, ownerWaitingNow, workerState } from "./pool";
+import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ownerHandsOn, ownerWaitingNow, workerState } 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 } from "./tasks";
@@ -41,6 +41,8 @@ export interface RunningJob {
/** When its run was made (pressed). */
createdAt: number | null;
principal: PrincipalKind;
+ /** The owner's hands-on run (pool.ts ownerHandsOn): it waits and runs as a person's run does. */
+ handsOn?: true;
}
/** A job waiting in line for a worker, in the order the workers serve them (the ones no worker takes now last). */
@@ -66,6 +68,8 @@ export interface QueuedJob {
/** The person whose run it is, as a key (never an account id; null: the owner's own), and whether a guest's. */
person: string | null;
guest: boolean;
+ /** The owner's hands-on run (pool.ts ownerHandsOn): it waits and runs as a person's run does. */
+ handsOn?: true;
}
/** A worker's mode and the local work on its PC, for the owner's Queue page. */
@@ -106,6 +110,8 @@ export interface HeldJob {
/** When its run was made (a job it took). */
createdAt?: number | null;
waiting?: number;
+ /** The owner's hands-on run (pool.ts ownerHandsOn): it waits and runs as a person's run does. */
+ handsOn?: true;
}
/** A later step of a chain that waits for its earlier steps. */
@@ -177,7 +183,7 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
else if (t.state === "sending") held = { why: "Sending its files to the worker", code: "sending", since: t.sending_since ?? t.claimed_at };
else if (t.state === "queued") held = { why: p?.position ? `In its worker's ComfyUI queue (place ${p.position})` : "In its worker's ComfyUI queue", code: "queued", since: t.sent_at ?? t.claimed_at };
if (held) {
- holding.push({ worker: w?.name ?? "?", ...base, principal: who, ...held, createdAt: g?.created_at ?? null });
+ holding.push({ worker: w?.name ?? "?", ...base, principal: who, ...held, createdAt: g?.created_at ?? null, ...(ownerHandsOn(t) && { handsOn: true as const }) });
continue;
}
const cold = taskCold(t);
@@ -195,6 +201,7 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
claimedAt: t.claimed_at,
createdAt: g?.created_at ?? null,
principal: who,
+ ...(ownerHandsOn(t) && { handsOn: true as const }),
});
}
@@ -220,11 +227,12 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
createdAt: g?.created_at ?? null,
inLineAt: t.rank_at ?? t.created_at,
rank,
- why: controlWords(control, base, mode, nameOf),
+ why: controlWords(control, base, mode, nameOf, ownerHandsOn(t)),
code: control.out ?? (control.tier === 0 ? "next" : control.tier === 1 ? "boost" : "class"),
override: o ? { id: o.id, until: o.until, by: o.by, at: o.at, workerId: o.workerId } : null,
person: t.account ? personKey(t.account) : null,
guest: !!t.account?.startsWith("guest"),
+ ...(ownerHandsOn(t) && { handsOn: true as const }),
};
});
@@ -240,7 +248,7 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
// The job it would take first: whose run the worker holds back.
const first = firstClaimableNow(w, now);
const g = first ? genOf(first.generation_id) : undefined;
- const next = first ? { generationId: first.generation_id, model: modelLabel(g?.model_id), op: g?.op ?? null, principal: principalKind(first) } : { generationId: null, model: null, op: null, principal: null };
+ const next = first ? { generationId: first.generation_id, model: modelLabel(g?.model_id), op: g?.op ?? null, principal: principalKind(first), ...(ownerHandsOn(first) && { handsOn: true as const }) } : { generationId: null, model: null, op: null, principal: null };
if (h && now - w.seen_at <= HOLDING_FRESH_MS) holding.push({ worker: w.name, task: null, ...next, why: holdingWords(h.why), code: h.why, since: h.since, waiting });
else if (!busy.has(w.id) && s.state !== "idle" && s.state !== "busy") holding.push({ worker: w.name, task: null, ...next, why: s.words, code: s.state, since: null, waiting });
}
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index bd896c63..bddd6e4a 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -842,7 +842,9 @@ export function takeTask(t: TaskRow, device: string, now: number, fields: Partia
lease,
...(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 }) }),
+ // The worker reads "owner" as the owner's job, the only kind that comes as a graph: the owner's hands-on run (no
+ // account, in a person's class in the line) is "owner" to it too.
+ ...(t.pools && { class: (!t.account || t.class === "owner" ? "owner" : t.class === "paid" ? "paid" : "free") 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.
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 49215bc4..3309cdc6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -93,7 +93,7 @@ import {
type Principal,
type TaskRow,
} from "../computer/tasks";
-import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun, workersHold } from "../computer/pool";
+import { attemptDeadline, ownerRunClass, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun, workersHold } from "../computer/pool";
import { notOnGpusText } from "../runs-here";
import { catalogVersion } from "../computer/catalog-version";
import { ticketProblem, type JobTicket } from "@/lib/job-ticket";
@@ -326,6 +326,17 @@ function accountPoolFields(workflowId: string, account: string, generationId: st
});
}
+/**
+ * Where the owner's job waits in line on the workers. A run a script said it made (a batch, a drill, an example, a
+ * test: pool.ts ownerRunClass) is the owner's class, after every person's run, in the order its jobs came. A hands-on
+ * run waits as a person's free run does: a later step of it keeps its run's place (runPlaceOf).
+ */
+function ownerPoolFields(workflowId: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; runtime?: FileNeed[] }) {
+ const cls = generationId ? ownerRunClass(generationId) : "owner";
+ const run = cls === "free" && generationId ? runPlaceOf(generationId) : null;
+ return poolFields(workflowId, { class: cls, ...(run?.rankAt != null && { rankAt: run.rankAt }), waitMs: ownerWaitMs(), size: o.size, runtime: o.runtime });
+}
+
/** Said to the owner when a job is larger than every worker's PC may ever run (its ceiling: `fuobe worker setup`). */
export const NO_WORKER_FOR_SIZE = "No worker may run a job this large: each PC's limits, set with fuobe worker setup, are lower. Pick a smaller size, a shorter clip or fewer results.";
@@ -2063,9 +2074,10 @@ export const comfyProvider: ProviderAdapter = {
...(forPool && {
pool:
computer === "owner"
- ? // The owner's jobs on the workers: the lane and files they need, after every person's run (the owner's
- // class), with the owner's own wait limit (none unless the owner sets one: queue-settings.ts).
- poolFields(manifest.id, { class: "owner", waitMs: ownerWaitMs(), size: prepared.size, runtime: runtime?.files })
+ ? // The owner's jobs on the workers: the lane and files they need, with the owner's own wait limit (none
+ // unless the owner sets one: queue-settings.ts). A script's run (a batch, a drill…) waits after every
+ // person's run (the owner's class); a hands-on run waits with people's runs, at its run's place.
+ ownerPoolFields(manifest.id, generationId, { size: prepared.size, runtime: runtime?.files })
: // An account's: the lane and files they need, in its class (paid before free), in the order they came
// (with the billing service's head start inside the class), with the wait set for the run.
// A ticket's task goes only to a worker built for its catalog, and inside that PC's ceiling.
diff --git a/tests/owner-hands-on.test.ts b/tests/owner-hands-on.test.ts
new file mode 100644
index 00000000..61893e18
--- /dev/null
+++ b/tests/owner-hands-on.test.ts
@@ -0,0 +1,284 @@
+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 { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The owner's runs on the install's workers: a hands-on run (no `source`) waits, counts and makes room as a person's
+ * run does in every mode; a run a script tagged (batch, drill, example, test) stays the owner's own job, after people's
+ * runs; a run the owner sent next asks local work to make room too.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-owner-hands-on-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+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 qc = await import("@/server/computer/queue-controls");
+const { liveQueue } = await import("@/server/computer/queue-live");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const qs = await import("@/server/queue-settings");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { SiteTurns } = await import("../bin/lib/worker/turns.mjs");
+const { siteOf } = await import("../bin/lib/worker/run.mjs");
+
+const MIN = 60_000;
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+type TaskRow = import("@/server/computer/tasks").TaskRow;
+
+let alice = "";
+
+beforeAll(() => {
+ auth.setPassword("install password");
+ alice = auth.createAccount("[email protected]", "long enough").id;
+});
+beforeEach(() => {
+ resetRates();
+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);
+ setSetting("comfyWhere", "workers");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("DELETE FROM queue_overrides").run();
+ db().prepare("DELETE FROM settings WHERE key = 'queue.modes'").run();
+ globalThis.__fuobeQueueModes = undefined;
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state != 'canceled'").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+function worker(name: string) {
+ const w = pool.addWorker(name);
+ 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 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), Date.now(), w.id);
+ return w;
+}
+const row = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+const beat = (w: { id: string }, extra: Record<string, unknown> = {}, now = Date.now()) =>
+ pool.workerBeat(row(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(), ...extra }), now);
+const claim = (w: { id: string }, now = Date.now()) => pool.workerClaim(row(w), [], now);
+const done = (id: string) => db().prepare("UPDATE relay_tasks SET state = 'done', finished_at = ? WHERE id = ?").run(Date.now(), id);
+const taskRow = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;
+
+let gens = 0;
+/**
+ * A run in line, made `agoMs` ago: a person's (`account`), or the owner's with the class its source gives it
+ * (pool.ts ownerRunClass): hands-on (no source) or tagged (`source`).
+ */
+function job(o: { account?: string; source?: "batch" | "drill" | "example" | "test" | "api" | "hands-on"; agoMs?: number; batch?: string; noTask?: boolean } = {}) {
+ const gid = `oh-gen-${++gens}`;
+ const at = Date.now() - (o.agoMs ?? 0);
+ db()
+ .prepare("INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, ?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(gid, o.batch ?? null, JSON.stringify(o.account ? { account: o.account, place: "pool" } : o.source ? { source: o.source } : {}), at, at);
+ if (o.noTask) return { id: "", gid };
+ const cls = o.account ? "free" : pool.ownerRunClass(gid);
+ const t = tasks.createTask({
+ principal: o.account ? `acct:${o.account}` : "owner",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], account: o.account, class: cls, rankAt: at, lane: allLanes(loadIndex(), sha)[0].lane, needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 } },
+ });
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(at, t.id);
+ return { id: t.id, gid };
+}
+
+function served(w: { id: string }): string[] {
+ const out: string[] = [];
+ for (;;) {
+ beat(w);
+ const t = claim(w);
+ if (!t) return out;
+ out.push(t.id);
+ done(t.id);
+ }
+}
+
+const setMode = (mode: string) => {
+ const c = qc.checkModeChange({ mode }, "owner");
+ if ("error" in c) throw new Error(c.error);
+ qc.applyModeChange(c);
+};
+const sendNext = (gid: string) => {
+ const o = qc.checkOverride({ kind: "run", generationId: gid, action: "next" });
+ if ("error" in o) throw new Error(o.error);
+ const r = qc.addOverride(o, "owner");
+ if ("error" in r) throw new Error(r.error);
+};
+const localRunning = { localWork: { state: "running", why: null, waiting: 3, running: true, at: Date.now() } };
+
+describe("the owner's run's class", () => {
+ it("is a person's (free) with no source, and the owner's with a script's source or a tagged step of the same press", () => {
+ expect(pool.ownerRunClass(job({ noTask: true }).gid)).toBe("free");
+ expect(pool.ownerRunClass(job({ source: "hands-on", noTask: true }).gid)).toBe("free");
+ for (const source of ["batch", "drill", "example", "test", "api"] as const) expect(pool.ownerRunClass(job({ source, noTask: true }).gid)).toBe("owner");
+ // A chain's first frame carries no source of its own: its press's tagged step decides.
+ const first = job({ batch: "press-1", noTask: true });
+ job({ batch: "press-1", source: "batch", noTask: true });
+ expect(pool.ownerRunClass(first.gid)).toBe("owner");
+ const other = job({ batch: "press-2", noTask: true });
+ expect(pool.ownerRunClass(other.gid)).toBe("free");
+ expect(pool.ownerRunClass("no-such-run")).toBe("free");
+ });
+
+ it("a hands-on run is the owner's hands-on run; the worker still gets it as the owner's graph job", () => {
+ const w = worker("w1");
+ const mine = job();
+ expect(pool.ownerHandsOn(taskRow(mine.id))).toBe(true);
+ expect(pool.ownerHandsOn(taskRow(job({ source: "batch" }).id))).toBe(false);
+ expect(pool.ownerHandsOn(taskRow(job({ account: alice }).id))).toBe(false);
+ beat(w);
+ const c = claim(w);
+ expect(c?.id).toBe(mine.id);
+ expect(c?.class).toBe("owner");
+ expect(c?.graph).toBeDefined();
+ });
+});
+
+describe("the line in each mode", () => {
+ it("people first: a hands-on run with people's runs by when it came; a tagged run after both", () => {
+ const w = worker("w1");
+ const batch = job({ source: "batch", agoMs: 60 * MIN });
+ const mine = job({ agoMs: 20 * MIN });
+ const a = job({ account: alice, agoMs: 10 * MIN });
+ expect(served(w)).toEqual([mine.id, a.id, batch.id]);
+ });
+
+ it("people only: a hands-on run is taken; a tagged run waits", () => {
+ setMode("people-only");
+ const w = worker("w1");
+ const batch = job({ source: "test", agoMs: 60 * MIN });
+ const mine = job({ agoMs: 5 * MIN });
+ expect(served(w)).toEqual([mine.id]);
+ expect(liveQueue().queued.find((q) => q.task === batch.id)).toMatchObject({ code: "paused", why: "Waits: People only" });
+ });
+
+ it("our work first: a tagged run first, a hands-on run with people's runs after it", () => {
+ setMode("ours-first");
+ const w = worker("w1");
+ const a = job({ account: alice, agoMs: 30 * MIN });
+ const mine = job({ agoMs: 20 * MIN });
+ const batch = job({ source: "example", agoMs: 5 * MIN });
+ expect(served(w)).toEqual([batch.id, a.id, mine.id]);
+ });
+
+ it("balanced: free runs, hands-on runs and tagged runs by when they came", () => {
+ setMode("balanced");
+ const w = worker("w1");
+ const batch = job({ source: "drill", agoMs: 30 * MIN });
+ const mine = job({ agoMs: 20 * MIN });
+ const a = job({ account: alice, agoMs: 10 * MIN });
+ expect(served(w)).toEqual([batch.id, mine.id, a.id]);
+ });
+});
+
+describe("the worker's site turn", () => {
+ it("a hands-on run counts in claimableNow (so siteWaiting asks local work for room); a tagged run only in ownerWaitingNow", () => {
+ const w = worker("w1");
+ job({ source: "batch", agoMs: 5 * MIN });
+ let answer = beat(w);
+ expect(answer.claimableNow).toBe(0);
+ expect(answer.ownerWaitingNow).toBe(1);
+ job({ agoMs: MIN });
+ answer = beat(w);
+ expect(answer.claimableNow).toBe(1);
+ expect(answer.ownerWaitingNow).toBe(1);
+ expect(pool.updateOf(row(w)).peopleWaiting).toBe(1);
+
+ // The worker's turn: its site.json says a studio job waits, and local work that holds the GPU is asked for room.
+ const folder = path.join(dir, "turns-folder");
+ fs.mkdirSync(folder, { recursive: true });
+ const turns = new SiteTurns({ folder, stateFile: path.join(dir, "turns-state.json") });
+ const t = Date.now();
+ const s = siteOf(answer);
+ const turn = turns.step(t, { may: true, claimable: s.claimable, busy: false, workHolds: true, workThere: true, serverInterrupt: false, unsure: false });
+ expect(turn.siteWaiting).toBeGreaterThanOrEqual(1);
+ expect(turn.waitForYield).toBe(true);
+ });
+
+ it("a tagged run alone asks for no turn", () => {
+ const w = worker("w1");
+ job({ source: "batch" });
+ const s = siteOf(beat(w));
+ const folder = path.join(dir, "turns-folder-2");
+ fs.mkdirSync(folder, { recursive: true });
+ const turns = new SiteTurns({ folder, stateFile: path.join(dir, "turns-state-2.json") });
+ expect(turns.step(Date.now(), { may: true, claimable: s.claimable, busy: false, workHolds: true, workThere: true, serverInterrupt: false, unsure: false }).siteWaiting).toBe(0);
+ });
+
+ it("our work first while local work runs: a hands-on run asks for no room, as a person's run", () => {
+ setMode("ours-first");
+ const w = worker("w1");
+ job();
+ expect(beat(w, localRunning).claimableNow).toBe(0);
+ });
+
+ it("a hands-on run makes a tagged job on the GPU go back in line, as a person's run does", () => {
+ const w = worker("w1");
+ const batch = job({ source: "batch", agoMs: 10 * MIN });
+ beat(w);
+ expect(claim(w)?.id).toBe(batch.id);
+ const mine = job();
+ const answer = beat(w);
+ expect(answer.stops.map((s) => s.task)).toEqual([batch.id]);
+ expect(claim(w)?.id).toBe(mine.id);
+ });
+
+ it("a hands-on run is never sent back for a person's run", () => {
+ const w = worker("w1");
+ const mine = job({ agoMs: 10 * MIN });
+ beat(w);
+ expect(claim(w)?.id).toBe(mine.id);
+ job({ account: alice });
+ expect(beat(w).stops).toEqual([]);
+ });
+});
+
+describe("Run next", () => {
+ it("a tagged run sent next counts as a person's for the turn (local work makes room) and says so on the Queue page", () => {
+ const w = worker("w1");
+ const batch = job({ source: "batch", agoMs: 5 * MIN });
+ expect(beat(w).claimableNow).toBe(0);
+ sendNext(batch.gid);
+ const answer = beat(w);
+ expect(answer.claimableNow).toBe(1);
+ expect(answer.ownerWaitingNow).toBe(0);
+ // In our work first too, while local work runs.
+ setMode("ours-first");
+ expect(beat(w, localRunning).claimableNow).toBe(1);
+ const q = liveQueue().queued.find((x) => x.task === batch.id);
+ expect(q).toMatchObject({ rank: 1, code: "next", why: "Run next: starts as soon as the GPU is free and local work makes room" });
+ });
+});
+
+describe("the Queue page", () => {
+ it("says \"Your run\" of a hands-on run, flags it, and keeps the tagged run's words", () => {
+ worker("w1");
+ const mine = job({ agoMs: 5 * MIN });
+ const batch = job({ source: "batch", agoMs: 10 * MIN });
+ const a = job({ account: alice, agoMs: MIN });
+ const q = liveQueue().queued;
+ expect(q.map((x) => x.task)).toEqual([mine.id, a.id, batch.id]);
+ expect(q[0]).toMatchObject({ principal: "owner", why: "Your run", handsOn: true, person: null });
+ expect(q[1]).toMatchObject({ principal: "user", why: "People first" });
+ expect(q[1]).not.toHaveProperty("handsOn");
+ expect(q[2]).toMatchObject({ principal: "owner", why: "Our work: after people's runs" });
+ expect(q[2]).not.toHaveProperty("handsOn");
+ });
+});
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index 1983d420..078b7aaa 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -195,12 +195,26 @@ describe("classes", () => {
standInWorker();
const route = { provider: "comfyui", endpoint: loadManifest().workflows[0].id, op: "t2i" } as never;
const submit = (gid: string) => onComputer("owner", () => comfyProvider.submit({ route, input: { prompt: "a lighthouse" } as never, generationId: gid } as never));
+ // The owner's runs as stored: a script's (a source) and a hands-on one (none).
+ const made = (gid: string, request: Record<string, unknown>) =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(gid, JSON.stringify(request), Date.now(), Date.now());
+ made("owner-gen-1", { source: "batch" });
+ made("owner-gen-2", { source: "test" });
+ made("owner-gen-hands", {});
const first = rowOf(String(((await submit("owner-gen-1")).meta as { relay: string }).relay));
expect(first.class).toBe("owner");
expect(first.account).toBeNull();
expect(first.not_after).toBeNull();
+ // A hands-on run waits as a person's free run does (still the owner's: no account), with the owner's wait limit.
+ const hands = rowOf(String(((await submit("owner-gen-hands")).meta as { relay: string }).relay));
+ expect(hands.class).toBe("free");
+ expect(hands.account).toBeNull();
+ expect(hands.not_after).toBeNull();
qs.saveQueueSettings({ ...qs.queueSettings(), ownerWaitLimitS: 3600 });
const second = rowOf(String(((await submit("owner-gen-2")).meta as { relay: string }).relay));
+ expect(second.class).toBe("owner");
expect(second.not_after! - second.created_at).toBeGreaterThanOrEqual(3600_000 - 1000);
expect(second.not_after! - second.created_at).toBeLessThanOrEqual(3600_000 + 1000);
});
@@ -632,7 +646,9 @@ describe("the run ceiling", () => {
await tick();
await new Promise((res) => setTimeout(res, 20));
}
- expect(taskOf(ownerId)?.class).toBe("owner");
+ // Made in the browser, it is the owner's hands-on run: in line with people's runs.
+ expect(taskOf(ownerId)?.class).toBe("free");
+ expect(taskOf(ownerId)?.account).toBeNull();
await tick();
// By the runner's own count, both waited past every wait limit it knows (their tasks keep the real ones), and each
// poll fails (the database is busy).
diff --git a/tests/worker-queue.test.ts b/tests/worker-queue.test.ts
index c2cd6aaf..1a43e490 100644
--- a/tests/worker-queue.test.ts
+++ b/tests/worker-queue.test.ts
@@ -276,7 +276,7 @@ describe("the beat", () => {
accountTask();
accountTask();
const owner = accountTask();
- db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL WHERE id = ?").run(owner.id);
+ db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL, class = 'owner' WHERE id = ?").run(owner.id);
expect(beatAs(w).claimableNow).toBe(2);
pool.patchWorker(w.id, { paused: true });
expect(beatAs(w).claimableNow).toBe(0);
@@ -287,7 +287,7 @@ describe("the beat", () => {
accountTask();
const owner = accountTask();
const other = accountTask();
- db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL WHERE id IN (?, ?)").run(owner.id, other.id);
+ db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL, class = 'owner' WHERE id IN (?, ?)").run(owner.id, other.id);
expect(beatAs(w)).toMatchObject({ claimableNow: 1, ownerWaitingNow: 2 });
// One it can't run (another pool) doesn't count.
db().prepare("UPDATE relay_tasks SET pools = 'elsewhere' WHERE id = ?").run(other.id);