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 pick order gives a free worker first pick of the jobs it can run

Adarshbe52e73c0b13
diff --git a/src/app/api/admin/queue/settings/route.ts b/src/app/api/admin/queue/settings/route.ts
index c472ab49..eb68cfa0 100644
--- a/src/app/api/admin/queue/settings/route.ts
+++ b/src/app/api/admin/queue/settings/route.ts
@@ -6,7 +6,8 @@ const NO_STORE = { "Cache-Control": "no-store" };
/**
* The line's settings (owner only, or an admin token with queue:read): the run ceiling (a default and per lane, in
- * seconds), the owner's wait limit, fair share, the pick allowance and the paused budget (src/server/queue-settings.ts).
+ * seconds), the owner's wait limit, fair share, the pick allowance, the first-pick grace and the paused budget
+ * (src/server/queue-settings.ts).
*/
export async function GET(request: Request) {
await connection();
@@ -17,7 +18,7 @@ export async function GET(request: Request) {
/**
* Change them (owner only, or an admin token with queue:write): any of `{ runCeilingS: { default, lanes },
- * ownerWaitLimitS, fairShare, pickAllowanceMs, pausedBudgetS }`. A given runCeilingS replaces the default and every lane's value. Each
+ * ownerWaitLimitS, fairShare, pickAllowanceMs, firstPickGraceMs, pausedBudgetS }`. A given runCeilingS replaces the default and every lane's value. Each
* change is written to the admin log with the values before and after. It applies to new claims and clocks at once.
*/
export async function PATCH(request: Request) {
diff --git a/src/app/api/admin/workers/[id]/route.ts b/src/app/api/admin/workers/[id]/route.ts
index a4b535fe..f18b8440 100644
--- a/src/app/api/admin/workers/[id]/route.ts
+++ b/src/app/api/admin/workers/[id]/route.ts
@@ -4,11 +4,11 @@ import { patchWorker, type WorkerPatch } from "@/server/computer/pool";
const NO_STORE = { "Cache-Control": "no-store" };
/** The changes a worker takes: the log names which were sent, never their values (a rotate's token least of all). */
-const KEYS = ["paused", "pauseNow", "drain", "autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs", "rotate", "revoke"] as const;
+const KEYS = ["paused", "pauseNow", "drain", "autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs", "pickOrder", "rotate", "revoke"] as const;
/**
* Change a worker (owner only, or an admin token with workers:write):
- * `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs, rotate, revoke }`.
+ * `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs, pickOrder, rotate, revoke }`.
* Each reaches the worker at its next beat. Rotate answers with the new token, once (an admin token needs
* workers:tokens for it); revoke stops the old token at once and puts its job back in line.
*/
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 5a351044..84d91147 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -657,7 +657,10 @@ function gpuClaimableRows(w: WorkerRow, now: number, whose: "people" | "owner"):
? `(${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));
+ const able = rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
+ // A job left for a free worker that picks first is not this worker's to take for now: its PC makes no room for it.
+ const left = able.length ? firstPicks(w, now) : null;
+ const fit = left?.size ? able.filter((t) => !left.has(t.id)) : able;
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
@@ -841,9 +844,13 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), s
if (slot === "gpu") noteAsked(fresh, "blocked", `Asked for work: not taking work (${blockedWhy(fresh, now)})`, now);
return null;
}
- const { task: t, looked } = pick(fresh, now, slot);
+ // First pick: its GPU leaves a job for a free worker with a higher pick order that would take it next, for a short
+ // grace (firstPicks), and takes its own next best.
+ const left = slot === "gpu" ? firstPicks(fresh, now) : new Map<string, string>();
+ const { task: t, looked } = pick(fresh, now, slot, new Set(left.keys()));
const many = `${looked}${looked >= LOOK_AT ? "+" : ""}`;
- if (slot === "gpu") noteAsked(fresh, t ? "found" : "nothing", t ? `Asked for work: took 1 of ${many} waiting` : looked ? `Asked for work: ${many} waiting, none it can run now` : "Asked for work: nothing waiting", now, { waiting: looked });
+ const none = left.size ? `Asked for work: ${many} waiting, ${left.size === 1 ? "1 left" : `${left.size} left`} for a worker that picks first` : `Asked for work: ${many} waiting, none it can run now`;
+ if (slot === "gpu") noteAsked(fresh, t ? "found" : "nothing", t ? `Asked for work: took 1 of ${many} waiting` : looked ? none : "Asked for work: nothing waiting", now, { waiting: looked, ...(left.size && { leftFor: [...new Set(left.values())] }) });
return t ? claimed(t, fresh, device, now) : null;
}).immediate();
}
@@ -1033,15 +1040,16 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
* never makes a person wait: while any person's run waits that this worker can take, it takes the best of them. Only
* among the owner's own jobs may one in the lane it has loaded go ahead of the best one, while the best one has waited
* less than the pick allowance (the install's setting, capped by this worker's switch_after_ms; 0: strict order).
+ * `leave`: the tasks it leaves for a worker that picks first (firstPicks).
*/
-function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: TaskRow | null; looked: number } {
+function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu", leave?: ReadonlySet<string>): { task: TaskRow | null; looked: number } {
const settings = queueSettings(now);
// The owner's controls: this worker's mode, and the runs and people sent first or held.
const c = controlsOf(w, now);
// Each slot looks only at its own tasks.
const rows = lineRows("*", `pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, slot)}`, [`,${w.pool},`], c, LOOK_AT);
const looked = rows.length;
- const ok = controlledOrder(rows, settings.fairShare, c, w.id).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
+ const ok = controlledOrder(rows, settings.fairShare, c, w.id).filter((t) => !leave?.has(t.id) && fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
if (!ok.length) return { task: null, looked };
const best = ok[0];
const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
@@ -1052,6 +1060,66 @@ function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: Task
return { task: warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best, looked };
}
+// ---------------------------------------------------------------------------
+// First pick: a worker with a higher pick order gets a job first, while it is free and can run it
+
+/** A worker with a higher pick order than the one that claims, free now, and the job its own claim would take next. */
+export interface FirstPicker {
+ id: string;
+ pickOrder: number;
+ /** That job, and since when it could take it (the job came, and its delays passed). Null: none. */
+ next: { taskId: string; since: number } | null;
+}
+
+/**
+ * Who gets first pick of a job a worker could take (pure): of the free workers with a pick order above the claiming
+ * worker's (`mine`), the one with the highest pick order whose next job it is, while that job has been there for it for
+ * less than `graceMs`. Null: the claiming worker takes it. A grace of 0 leaves no job for anyone.
+ */
+export function firstPickOf(taskId: string, mine: number, pickers: readonly FirstPicker[], now: number, graceMs: number): string | null {
+ if (graceMs <= 0) return null;
+ const by = pickers.filter((p) => p.pickOrder > mine && p.next?.taskId === taskId && now - p.next.since < graceMs);
+ by.sort((a, b) => b.pickOrder - a.pickOrder || (a.id < b.id ? -1 : 1));
+ return by[0]?.id ?? null;
+}
+
+/**
+ * Is this worker free to take a job now: it may take work (eligible: heard from within 30 s, paused in neither place,
+ * not draining, inside its hours), it says nothing holds it back (its beat's `holding`: starting its ComfyUI, local work
+ * first, an update…), and its GPU's slot holds no job.
+ */
+function freeNow(x: WorkerRow, now: number): boolean {
+ if (!eligible(x, now) || x.holding_json || (x.local_why ?? "").startsWith("waiting-for-yield")) return false;
+ return !db().prepare("SELECT 1 FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting')").get(x.id, slotDevice(x, "gpu"));
+}
+
+/** When a task became one this worker could take: when it came, plus the worker's claim delay and its lane's delay. */
+const claimableSince = (t: TaskRow, x: WorkerRow) => t.created_at + x.claim_after_ms + (allowOf(x)[t.lane ?? ""]?.delayMs ?? 0);
+
+/**
+ * The tasks this worker's GPU leaves for workers with a higher pick order, each to the worker it is left for
+ * (firstPickOf): each such worker that is free now (freeNow), highest pick order first, with the job its own claim
+ * would take next (pick: its pool, lanes and their delays, files, packs and memory, the retry rule, its hours and mode),
+ * the tasks left for the workers above it left out. Empty at once (one query) when no worker has a higher pick order, or
+ * the grace is 0.
+ */
+function firstPicks(w: WorkerRow, now: number): Map<string, string> {
+ const out = new Map<string, string>();
+ const graceMs = queueSettings(now).firstPickGraceMs;
+ if (graceMs <= 0) return out;
+ const mine = w.pick_order ?? 0;
+ const above = db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND id != ? AND pick_order > ? ORDER BY pick_order DESC, id").all(w.id, mine) as WorkerRow[];
+ const pickers: FirstPicker[] = [];
+ for (const x of above) {
+ if (!freeNow(x, now)) continue;
+ const t = pick(x, now, "gpu", new Set(out.keys())).task;
+ pickers.push({ id: x.id, pickOrder: x.pick_order ?? 0, next: t ? { taskId: t.id, since: claimableSince(t, x) } : null });
+ const who = t ? firstPickOf(t.id, mine, pickers, now, graceMs) : null;
+ if (t && who) out.set(t.id, who);
+ }
+ return out;
+}
+
/**
* Turns already taken in each class, by whose turn: runs a worker holds now, and runs a worker took and finished since
* the oldest of `waiting` in that class came.
@@ -1847,6 +1915,8 @@ export interface WorkerView {
allow: Record<string, Allow>;
claimAfterMs: number;
switchAfterMs: number;
+ /** Its pick order: higher gets first pick of a job that a worker with a lower one could take too, while it is free. 0: none. */
+ pickOrder: number;
warmLane: string | null;
/** The lanes it can run every workflow of. */
lanes: string[];
@@ -2092,6 +2162,7 @@ export function workerView(w: WorkerRow, now = Date.now(), typical: (lane: strin
allow: allowOf(w),
claimAfterMs: w.claim_after_ms,
switchAfterMs: w.switch_after_ms,
+ pickOrder: w.pick_order ?? 0,
warmLane: w.warm_lane,
lanes: capableOf(w).lanes,
partLanes: partLanes(loadIndex(), capableOf(w).workflows, sha),
@@ -2135,6 +2206,10 @@ export function addWorker(name: string, pool = "pool"): { id: string; token: str
return createWorker({ name: clean, kind: "pool", pool });
}
+/** The pick order a worker may have (WorkerPatch.pickOrder). */
+export const PICK_ORDER_MIN = -100;
+export const PICK_ORDER_MAX = 100;
+
export interface WorkerPatch {
paused?: boolean;
pauseNow?: boolean;
@@ -2145,6 +2220,8 @@ export interface WorkerPatch {
allow?: unknown;
claimAfterMs?: number;
switchAfterMs?: number;
+ /** A whole number from PICK_ORDER_MIN to PICK_ORDER_MAX: higher picks first (firstPicks). 0: none. */
+ pickOrder?: number;
rotate?: boolean;
revoke?: boolean;
}
@@ -2208,6 +2285,10 @@ export function patchWorker(id: string, p: WorkerPatch, now = Date.now(), by = "
}
if (p.claimAfterMs !== undefined) set.claim_after_ms = Math.max(0, Math.min(24 * 3_600_000, Math.round(Number(p.claimAfterMs) || 0)));
if (p.switchAfterMs !== undefined) set.switch_after_ms = Math.max(0, Math.min(24 * 3_600_000, Math.round(Number(p.switchAfterMs) || 0)));
+ if (p.pickOrder !== undefined) {
+ if (!Number.isInteger(p.pickOrder) || p.pickOrder < PICK_ORDER_MIN || p.pickOrder > PICK_ORDER_MAX) throw new Error(`The pick order is a whole number from ${PICK_ORDER_MIN} to ${PICK_ORDER_MAX}`);
+ set.pick_order = p.pickOrder;
+ }
const keys = Object.keys(set);
if (keys.length) d.prepare(`UPDATE relay_workers SET ${keys.map((k) => `${k} = @${k}`).join(", ")} WHERE id = @id`).run({ ...set, id });
const token = p.rotate ? rotateWorker(id) ?? undefined : undefined;
@@ -2219,7 +2300,7 @@ export function patchWorker(id: string, p: WorkerPatch, now = Date.now(), by = "
if (p.paused === false) actions.push(["resume", "Resumed on the website"]);
if (p.drain === true) actions.push(["drain", "Set to finish its job, then pause"]);
else if (p.drain === false) actions.push(["undrain", "No longer pausing after its job"]);
- const edited = (["autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs"] as const).filter((k) => p[k] !== undefined);
+ const edited = (["autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs", "pickOrder"] as const).filter((k) => p[k] !== undefined);
if (edited.length) actions.push(["edit", `Settings changed: ${edited.join(", ")}`, { keys: edited }]);
if (token) actions.push(["rotate", "New token made"]);
noteAdmin(id, actions, by, now);
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index 52a3ce36..7984484e 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -59,6 +59,8 @@ export interface WorkerRow {
allow_json: string | null;
claim_after_ms: number;
switch_after_ms: number;
+ /** Its pick order: a free worker with a higher one gets first pick of a job both can run (pool.ts firstPickOf). 0: none. */
+ pick_order?: number;
state: string;
seen_at: number | null;
/** A pool worker's next token (its SHA-256), offered in a beat answer and not used yet; its expiry; when it was made. */
diff --git a/src/server/db.ts b/src/server/db.ts
index e450273d..e80355ef 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1149,6 +1149,8 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_workers", "update_asked_commit", "TEXT"],
// A worker PC's live hardware stats as its last beat said, with when the studio heard them (WorkerBeat.stats).
["relay_workers", "stats_json", "TEXT"],
+ // A worker's pick order (pool.ts firstPickOf): higher picks first among workers that are free and can run a job.
+ ["relay_workers", "pick_order", "INTEGER NOT NULL DEFAULT 0"],
];
declare global {
diff --git a/src/server/queue-settings.ts b/src/server/queue-settings.ts
index 7d322bbf..0f348215 100644
--- a/src/server/queue-settings.ts
+++ b/src/server/queue-settings.ts
@@ -12,6 +12,8 @@ import { db } from "./db";
* next job goes after every other account's job that came before it and is the first of its own.
* - `pickAllowanceMs`: how long a job in the lane a worker has loaded may go ahead of an older one in another lane, so a
* worker doesn't reload its models for every job (0: strict order).
+ * - `firstPickGraceMs`: how long a job may wait for a worker with a higher pick order to take it, while that worker is
+ * free and can run it, before another worker takes it (0: no job waits for one).
* - `pausedBudgetS`: how long, in all, a run that has started may spend back in line while its worker steps aside (another
* program on its GPU, a pause) and still be inside its hold's deadline. With the run ceiling, it sets the time a run
* asks its hold to stay open (holdTiming). A run past it still delivers its result.
@@ -24,16 +26,18 @@ export interface QueueSettings {
ownerWaitLimitS: number | null;
fairShare: boolean;
pickAllowanceMs: number;
+ firstPickGraceMs: number;
pausedBudgetS: number;
}
-export const QUEUE_DEFAULTS: QueueSettings = { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0, pausedBudgetS: 7200 };
+export const QUEUE_DEFAULTS: QueueSettings = { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0, firstPickGraceMs: 20_000, pausedBudgetS: 7200 };
/** The bounds each value may take. */
export const QUEUE_BOUNDS = {
ceilingS: { min: 60, max: 24 * 3600 },
ownerWaitS: { min: 60, max: 7 * 24 * 3600 },
pickAllowanceMs: { min: 0, max: 3_600_000 },
+ firstPickGraceMs: { min: 0, max: 600_000 },
pausedBudgetS: { min: 0, max: 7 * 24 * 3600 },
lanes: 200,
};
@@ -48,7 +52,7 @@ declare global {
const copy = (s: QueueSettings): QueueSettings => ({ ...s, runCeilingS: { default: s.runCeilingS.default, lanes: { ...s.runCeilingS.lanes } } });
/** The settings this version knows. */
-const QUEUE_KEYS = ["runCeilingS", "ownerWaitLimitS", "fairShare", "pickAllowanceMs", "pausedBudgetS"];
+const QUEUE_KEYS = ["runCeilingS", "ownerWaitLimitS", "fairShare", "pickAllowanceMs", "firstPickGraceMs", "pausedBudgetS"];
/**
* A stored value read leniently: anything that isn't valid is the default (a bad row never stops a run). A setting
@@ -122,6 +126,11 @@ export function checkQueuePatch(body: unknown, base: QueueSettings = queueSettin
if (!inRange(b.pickAllowanceMs, p)) return { error: `pickAllowanceMs is ${p.min} to ${p.max}` };
out.pickAllowanceMs = b.pickAllowanceMs;
}
+ if (b.firstPickGraceMs !== undefined) {
+ const p = QUEUE_BOUNDS.firstPickGraceMs;
+ if (!inRange(b.firstPickGraceMs, p)) return { error: `firstPickGraceMs is ${p.min} to ${p.max}` };
+ out.firstPickGraceMs = b.firstPickGraceMs;
+ }
if (b.pausedBudgetS !== undefined) {
const p = QUEUE_BOUNDS.pausedBudgetS;
if (!inRange(b.pausedBudgetS, p)) return { error: `pausedBudgetS is ${p.min} to ${p.max} seconds` };
diff --git a/tests/pool-first-pick.test.ts b/tests/pool-first-pick.test.ts
new file mode 100644
index 00000000..3a65ec08
--- /dev/null
+++ b/tests/pool-first-pick.test.ts
@@ -0,0 +1,268 @@
+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";
+
+/**
+ * First pick (docs/gpu-workers.md, "Who picks first"): a worker with a higher pick order gets a job before the others
+ * while it is free and can run it. Any other worker leaves that job for it, and takes its own next best job, only while
+ * the preferred worker is free now (heard from, paused in neither place, not draining, inside its hours, holding no job
+ * and nothing holding it back) and the job has been there for it for less than the grace. Pick order 0 everywhere, or a
+ * grace of 0, is the line as before.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-pool-first-pick-");
+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 qs = await import("@/server/queue-settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const workers = await import("@/server/computer/workers");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const workersRoute = await import("@/app/api/admin/workers/[id]/route");
+const auth = await import("@/server/auth");
+
+const KREA = "krea2-turbo-t2i";
+const FILES = loadIndex().workflows[KREA].files;
+const GB = 2 ** 30;
+const VERSION = "e".repeat(64);
+const GRAPH = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui", `${KREA}.json`), "utf8"));
+let clock = Date.UTC(2026, 10, 4, 3, 0, 0);
+
+type W = { id: string; token: string };
+const row = (w: W) => workers.getWorker(w.id)!;
+
+function beat(w: W, local: { paused: boolean; why: string | null } = { paused: false, why: null }, more: Record<string, unknown> = {}) {
+ return pool.workerBeat(
+ row(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 5, version: "1.0.0", local: { ...local, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: VERSION, ...more }),
+ clock,
+ );
+}
+
+/** A worker on, all day, allowed Krea 2's lane, with its files and 24 GB of VRAM, and this pick order. */
+function worker(name: string, pickOrder = 0, o: { vram?: number; files?: readonly string[]; delayMs?: number } = {}): W {
+ const w = pool.addWorker(name);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { [pool.poolLane(KREA)]: { delayMs: o.delayMs ?? 0 } }, claimAfterMs: 0, pickOrder });
+ beat(w);
+ const files = (o.files ?? FILES).map((k) => {
+ const f = loadIndex().files[k as keyof ReturnType<typeof loadIndex>["files"]];
+ return { folder: f.folder, name: f.file, size: f.sizeBytes, sha256: "a".repeat(64) };
+ });
+ pool.saveInventory(row(w), { files, nodePacks: [], media: ["image"] });
+ db().prepare("UPDATE relay_workers SET facts_json = ?, catalog_version = ? WHERE id = ?").run(JSON.stringify({ vramBytes: (o.vram ?? 24) * GB }), VERSION, w.id);
+ beat(w);
+ return w;
+}
+
+let gens = 0;
+function generation() {
+ const gid = `gen-fp-${++gens}`;
+ 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, clock, clock);
+ return gid;
+}
+
+/** A task made `ago` ms before the test's clock. */
+function placed(id: string, ago = 0) {
+ db().prepare("UPDATE relay_tasks SET created_at = ?, rank_at = ? WHERE id = ?").run(clock - ago, clock - ago, id);
+ return id;
+}
+
+/** The owner's own Krea 2 job. */
+const ownerJob = (ago = 0) => placed(tasks.createTask({ principal: "owner", generationId: generation(), graph: GRAPH, workflowId: KREA, pool: pool.poolFields(KREA, {}, clock) }).id, ago);
+
+/** An account's Krea 2 run: a job ticket for this catalog. */
+const accountJob = () =>
+ placed(
+ tasks.createTask({
+ principal: "acct:a1",
+ generationId: generation(),
+ graph: {},
+ ticket: { v: 1, workflowId: KREA, catalogVersion: VERSION, op: "t2i", settings: { prompt: "a portrait", seed: 1, numOutputs: 1 }, inputs: [], outputs: { count: 1, kind: "image" }, size: { megapixels: 1, seconds: 0, outputs: 1 } },
+ workflowId: KREA,
+ pool: pool.poolFields(KREA, { account: "a1", catalogVersion: VERSION }, clock),
+ }).id,
+ );
+
+const claim = (w: W) => pool.workerClaim(row(w), [], clock);
+
+/** No worker, and nothing in line or running. */
+function clear() {
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+}
+
+beforeAll(() => setSetting("comfyWhere", "workers"));
+beforeEach(() => {
+ resetRates();
+ clock += 60 * 60_000;
+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);
+ clear();
+});
+
+describe("who gets first pick (firstPickOf)", () => {
+ const now = 100_000;
+ const picker = (id: string, pickOrder: number, taskId: string | null, since = now - 1000) => ({ id, pickOrder, next: taskId ? { taskId, since } : null });
+
+ it("a worker with a higher pick order whose next job it is, inside the grace", () => {
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, "j")], now, 20_000)).toBe("x");
+ // The highest pick order wins.
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, "j"), picker("y", 5, "j")], now, 20_000)).toBe("y");
+ });
+
+ it("nobody: another next job, no higher pick order, past the grace, or a grace of 0", () => {
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, "k")], now, 20_000)).toBeNull();
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, null)], now, 20_000)).toBeNull();
+ expect(pool.firstPickOf("j", 1, [picker("x", 1, "j")], now, 20_000)).toBeNull();
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, "j", now - 20_000)], now, 20_000)).toBeNull();
+ expect(pool.firstPickOf("j", 0, [picker("x", 1, "j")], now, 0)).toBeNull();
+ });
+});
+
+describe("a worker that picks first", () => {
+ it("free and able: the other worker leaves the job for it, and it takes it", () => {
+ const id = ownerJob();
+ const fast = worker("fast");
+ const slow = worker("slow", 1);
+ expect(claim(fast)).toBeNull();
+ expect(row(fast).asked_words).toBe("Asked for work: 1 waiting, 1 left for a worker that picks first");
+ expect(claim(slow)?.id).toBe(id);
+ });
+
+ it("the other worker takes its own next best job at once", () => {
+ const first = ownerJob(2000);
+ const second = ownerJob(1000);
+ const fast = worker("fast");
+ const slow = worker("slow", 1);
+ expect(claim(fast)?.id).toBe(second);
+ expect(claim(slow)?.id).toBe(first);
+ });
+
+ it("busy: the other worker takes the job at once", () => {
+ ownerJob(1000);
+ const next = ownerJob();
+ const fast = worker("fast");
+ const slow = worker("slow", 1);
+ expect(claim(slow)).not.toBeNull();
+ expect(claim(fast)?.id).toBe(next);
+ });
+
+ it("paused on the website or on its PC, draining, silent or outside its hours: the other worker takes it at once", () => {
+ const away: [string, (w: W) => void][] = [
+ ["paused on the website", (w) => pool.patchWorker(w.id, { paused: true })],
+ ["paused on its PC", (w) => beat(w, { paused: true, why: "here" })],
+ ["draining", (w) => pool.patchWorker(w.id, { drain: true })],
+ ["silent", (w) => db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(clock - 31_000, w.id)],
+ ["outside its hours", (w) => pool.patchWorker(w.id, { hours: null })],
+ ["held back on its PC", (w) => beat(w, undefined, { holding: { why: "starting-comfy", since: clock } })],
+ ];
+ for (const [why, make] of away) {
+ clear();
+ const id = ownerJob();
+ const fast = worker("fast");
+ make(worker("slow", 1));
+ expect(claim(fast)?.id, why).toBe(id);
+ }
+ });
+
+ it("can't run the job (its files, its memory, its lane, its lane's delay): the other worker takes it at once", () => {
+ const cant: [string, () => W][] = [
+ ["missing a file", () => worker("slow", 1, { files: FILES.slice(1) })],
+ ["too little VRAM", () => worker("slow", 1, { vram: 8 })],
+ ["lane not allowed", () => {
+ const w = worker("slow", 1);
+ pool.patchWorker(w.id, { allow: {} });
+ return w;
+ }],
+ ["its lane's delay not over", () => worker("slow", 1, { delayMs: 60_000 })],
+ ];
+ for (const [why, make] of cant) {
+ clear();
+ const id = ownerJob();
+ const fast = worker("fast");
+ make();
+ expect(claim(fast)?.id, why).toBe(id);
+ }
+ });
+
+ it("past the grace, the other worker takes the job: nobody's job waits longer for it", () => {
+ const id = ownerJob(20_000);
+ const fast = worker("fast");
+ worker("slow", 1);
+ expect(claim(fast)?.id).toBe(id);
+ // The grace is the queue's setting: 0 leaves no job for anyone.
+ clear();
+ qs.saveQueueSettings({ ...qs.QUEUE_DEFAULTS, firstPickGraceMs: 0 });
+ const next = ownerJob();
+ const again = worker("fast");
+ worker("slow", 1);
+ expect(claim(again)?.id).toBe(next);
+ });
+
+ it("the grace counts from when its lane's delay ended", () => {
+ const id = ownerJob(65_000);
+ const fast = worker("fast");
+ worker("slow", 1, { delayMs: 60_000 });
+ expect(claim(fast)).toBeNull();
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock - 80_001, id);
+ expect(claim(fast)?.id).toBe(id);
+ });
+
+ it("pick order 0 everywhere (the default) is the line as before", () => {
+ const id = ownerJob();
+ const fast = worker("fast");
+ worker("slow");
+ expect(claim(fast)?.id).toBe(id);
+ });
+
+ it("a person's run left for it asks the other worker's PC for no room", () => {
+ accountJob();
+ const fast = worker("fast");
+ const slow = worker("slow", 1);
+ expect(pool.claimableNow(row(fast), clock)).toBe(0);
+ pool.patchWorker(slow.id, { paused: true });
+ expect(pool.claimableNow(row(fast), clock)).toBe(1);
+ });
+
+ it("the worker with the higher order is never held back by one with a lower order", () => {
+ const id = ownerJob();
+ worker("fast", 0);
+ const slow = worker("slow", 1);
+ expect(claim(slow)?.id).toBe(id);
+ });
+});
+
+describe("setting the pick order", () => {
+ const ownerCookie = () => `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ const patch = (id: string, body: unknown) =>
+ workersRoute.PATCH(new Request(`http://localhost/api/admin/workers/${id}`, { method: "PATCH", headers: { cookie: ownerCookie(), "content-type": "application/json", origin: "http://localhost" }, body: JSON.stringify(body) }), {
+ params: Promise.resolve({ id }),
+ } as never);
+
+ it("the owner sets it through the workers API; the view says it", async () => {
+ const w = worker("slow");
+ expect(pool.listWorkers(clock).find((v) => v.id === w.id)?.pickOrder).toBe(0);
+ const res = await patch(w.id, { pickOrder: 1 });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { worker: { pickOrder: number } }).worker.pickOrder).toBe(1);
+ expect(row(w).pick_order).toBe(1);
+ });
+
+ it("refuses a value that isn't a whole number in range, and changes nothing", async () => {
+ const w = worker("slow", 2);
+ for (const pickOrder of [1.5, "1", 101, -101, null]) {
+ const res = await patch(w.id, { pickOrder });
+ expect(res.status, JSON.stringify(pickOrder)).toBe(400);
+ }
+ expect(row(w).pick_order).toBe(2);
+ });
+});
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index c1828ee2..ad79d75c 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -728,18 +728,18 @@ describe("GET and PATCH /api/admin/queue/settings", () => {
const ownerCookie = () => `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
const audits = () => db().prepare("SELECT * FROM admin_audit WHERE action = 'queue.settings' ORDER BY id").all() as { actor: string; detail_json: string | null; status: number; token_id: string | null }[];
- it("the defaults are today's: a 45 minute ceiling, no owner wait limit, strict order, and 2 hours back in line inside a hold", async () => {
+ it("the defaults are today's: a 45 minute ceiling, no owner wait limit, strict order, 20 s of first pick, and 2 hours back in line inside a hold", async () => {
const res = await settingsRoute.GET(req({ cookie: ownerCookie() }));
expect(res.status).toBe(200);
expect(res.headers.get("cache-control")).toBe("no-store");
- expect(await res.json()).toEqual({ settings: { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0, pausedBudgetS: 7200 } });
+ expect(await res.json()).toEqual({ settings: { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0, firstPickGraceMs: 20_000, pausedBudgetS: 7200 } });
});
it("the owner changes them; each change is logged with the values before and after", async () => {
const lane = allLanes(loadIndex(), sha)[0].lane;
- const res = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body: { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, pausedBudgetS: 3600 } }));
+ const res = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body: { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, firstPickGraceMs: 30_000, pausedBudgetS: 3600 } }));
expect(res.status).toBe(200);
- const want = { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, pickAllowanceMs: 0, pausedBudgetS: 3600 };
+ const want = { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, pickAllowanceMs: 0, firstPickGraceMs: 30_000, pausedBudgetS: 3600 };
expect(await res.json()).toEqual({ settings: want });
expect(qs.queueSettings()).toEqual(want);
const row = audits().at(-1)!;
@@ -760,6 +760,8 @@ describe("GET and PATCH /api/admin/queue/settings", () => {
{ ownerWaitLimitS: -1 },
{ fairShare: "yes" },
{ pickAllowanceMs: 1.5 },
+ { firstPickGraceMs: -1 },
+ { firstPickGraceMs: 600_001 },
{ pausedBudgetS: -1 },
{ pausedBudgetS: 8 * 24 * 3600 },
{ somethingElse: 1 },
@@ -786,7 +788,8 @@ describe("GET and PATCH /api/admin/queue/settings", () => {
globalThis.__fuobeQueueSettings = undefined;
const known: Record<string, unknown> = { ...stored };
delete known.retiredSetting;
- expect(qs.queueSettings()).toEqual(known);
+ // A setting it doesn't hold (one added since it was stored) takes its default.
+ expect(qs.queueSettings()).toEqual({ ...known, firstPickGraceMs: 20_000 });
});
it("an admin token reads them with queue:read and changes them with queue:write", async () => {