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' line: people's runs first, in classes, with the queue's settings

Adarsh91106fde9c5e
diff --git a/docs/admin-api.md b/docs/admin-api.md
index e78a71a2..d3c4ecfd 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -46,7 +46,8 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/download` |
| `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke |
| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those |
-| `queue:read` | `GET /api/admin/queue` |
+| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings` |
+| `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share and the pick allowance |
| `audit:read` | `GET /api/admin/audit` |
Any valid admin token may call `GET /api/admin/tokens/self`, which says the token's name and scopes, so a tool can
@@ -106,6 +107,8 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `GET /api/admin/files/{path}` | `Range` works | the file; 404 for the owner's own files (held or not) and unknown paths |
| `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |
| `GET /api/admin/queue` | | `{ lanes }` |
+| `GET /api/admin/queue/settings` | | `{ settings: { runCeilingS: { default, lanes }, ownerWaitLimitS, fairShare, pickAllowanceMs } }` ([gpu-workers.md](gpu-workers.md#the-queue)) |
+| `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane |
| `GET /api/admin/workers` | | `{ workers, lanes }` |
| `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once |
| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |
@@ -117,7 +120,8 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
A log row is `{ id, at, actor: "owner" | "token", token: { id, name } | null, action, target, detail, status }`.
`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,
`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,
-`worker.rotate`, `worker.revoke`, `token.create`, `token.revoke`, `token.revoke_all`; a token's reads `accounts.list`, `accounts.csv`,
+`worker.rotate`, `worker.revoke`, `queue.settings` (with the values before and after), `token.create`, `token.revoke`,
+`token.revoke_all`; a token's reads `accounts.list`, `accounts.csv`,
`account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and action every 10 minutes) and
`file.view` (one row per token and file every hour); and refusals `scope.denied` and `rate.limited`. The owner's own
reads in the browser aren't logged. Rows go after a year.
diff --git a/docs/billing-hook.md b/docs/billing-hook.md
index b898740b..6960b65a 100644
--- a/docs/billing-hook.md
+++ b/docs/billing-hook.md
@@ -67,7 +67,7 @@ type Policy = {
| Call | Request | Answer |
|---|---|---|
| `POST /v1/quote` | `{ account: AccountFacts \| null, run: RunFacts, queue: QueueFacts \| null }` | `Quote` |
-| `POST /v1/reserve` | `{ requestId, account: AccountFacts, run: RunFacts, queue: QueueFacts \| null, shown: { amount, priceVersion } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, text }` or `{ ok: false, code: RefuseCode \| "price-changed", text, quote?, action?, offer? }` |
+| `POST /v1/reserve` | `{ requestId, account: AccountFacts, run: RunFacts, queue: QueueFacts \| null, shown: { amount, priceVersion } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, class?, text }` or `{ ok: false, code: RefuseCode \| "price-changed", text, quote?, action?, offer? }` |
| `POST /v1/release` | `{ holdId, reason: "not-created" }` | `{ ok: true }` |
| `POST /v1/settle` | `{ holdId, generationId, rows, status: "succeeded", final: { outputs, megapixels, seconds }, providerUsd, gpuMs, device, reachedProvider }` | `{ ok: true, charged }` |
| `POST /v1/refund` | `{ holdId, generationId, rows, status: "failed" \| "canceled" \| "hidden" \| "unchecked", reason, reachedProvider, gpuMs, device }` | `{ ok: true, text }` |
@@ -82,6 +82,10 @@ A reserve's `text` is shown on the result once it succeeded ("7 units"). `maxWai
line before a GPU first takes it; past it the row fails and is refunded. Once a GPU has taken it, the limit is over: a
run that goes back in line (a GPU paused or restarted) keeps its place and waits there.
+`class` puts the run in a class of the line: `"paid"` runs go before `"free"` ones (no `class`: `"free"`). The
+install's own jobs come after both. `boostMs` is a head start inside the class, at most a day: the run stands in line as
+if it had come that much earlier. Both are kept for every row of the run, and a browser never sees them.
+
On the workers ([gpu-workers.md](gpu-workers.md)), `queue` counts the line the way the workers serve it: `ahead` is
every task the workers that may run this one would serve first, whatever its model, and `lane` is the workflow's lane.
A report's `gpuMs` is the time the workers' ComfyUI spent running the row's jobs, as they measured it (no waits, no
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 9922a14f..ccce1c40 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -113,10 +113,14 @@ default). It also keeps:
with no big file is in the lane `small`.
- what it needs: the workflow, its files (folder, name, exact size, and SHA-256 where it is pinned), its node packs
and its VRAM;
-- `rank_at`: `created_at` minus a boost. The owner's jobs get a one-day boost. A job that goes back in line keeps
- its `rank_at`, so it keeps its place.
-- a wait limit (`FUOBE_POOL_WAIT_MIN`, 30 minutes, or what the billing service set for an account's run). It applies
- only until a worker first takes the job: past it, a job that no worker took fails with "The GPUs were busy".
+- 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.
+- `rank_at`: `created_at`, minus the head start the billing service gave the run inside its class (at most a day). A
+ job that goes back in line keeps its `rank_at`, so it keeps its place.
+- a wait limit: for an account's run, `FUOBE_POOL_WAIT_MIN` (30 minutes) or what the billing service set; for the
+ owner's own jobs, the owner's wait limit (none by default; see the queue's settings below). It applies only until a
+ worker first takes the job: past it, a job that no worker took fails with "The GPUs were busy".
- how many results its workflow makes. An owner's job keeps no more than that (and at least 16), as an account's job
keeps at most 16. Results are never saved past the disk's free floor.
@@ -132,8 +136,26 @@ A worker gets a job only when all of these are true, all in one SQLite transacti
- it holds no other job. A worker runs one job at a time: while it holds one, a claim gives it that job again when
it lost track of it, and nothing new.
-The lowest `rank_at` goes first (then the oldest). A worker keeps to its warm lane (the models that it has loaded)
-until another lane's best job has waited longer than `switch_after_ms` (30 minutes) and is older.
+Jobs go by class (`paid`, then `free`, then `owner`), then by the lowest `rank_at` (then the oldest). With the
+pick allowance at 0 (the default), that is the whole rule. Above 0, a worker may take a job in its warm lane (the
+models it has loaded) ahead of the best job, in the same class, while the best job has waited less than the pick
+allowance (or the worker's own `switch_after_ms`, if that is lower). With fair share on, each class goes round its
+accounts: an account's next run goes after every other account's run that is an earlier turn of its own. An account's
+turns count the runs a worker holds for it now and those a worker finished for it since the oldest run still waiting
+in that class came.
+
+**The queue's settings.** The owner sets these with `GET` and `PATCH /api/admin/queue/settings`
+([admin-api.md](admin-api.md)). They apply at once, with no restart:
+
+| Setting | What it does | Default |
+|---|---|---|
+| `runCeilingS` | `{ default, lanes }`: the longest one attempt at a job may run, in seconds, with a value per lane that overrides the default. It ends the run's own clock, and a worker's run limit is never longer | `{ "default": 2700, "lanes": {} }` (45 minutes) |
+| `ownerWaitLimitS` | How long the owner's own jobs may wait before a worker first takes them, in seconds. `null`: no limit | `null` |
+| `fairShare` | Each class goes round its accounts (above). Off: strict order | `false` |
+| `pickAllowanceMs` | How long a job in a worker's warm lane may go ahead of an older one (above). 0: strict order | `0` |
+
+A worker's run limit for one attempt is 3 times the lane's 90th percentile on that worker plus its model load, at
+least 10 minutes and never past the lane's run ceiling. With no measured run in the lane yet, it is the ceiling.
If a worker stops answering for 2 minutes, its ComfyUI is down for 2 minutes, or the job is still sending its files
15 minutes after the worker claimed it (or after its ComfyUI lost the job and the worker sent it again), its job goes
@@ -204,6 +226,7 @@ Each worker counts against its own rate limits, so three workers that beat every
A window can go past midnight.
- `GET /api/admin/queue`: the jobs that wait in each lane, the oldest job, the estimate, and which workers have the
lane warm.
+- `GET` and `PATCH /api/admin/queue/settings`: the queue's settings (above).
### Behind Cloudflare
diff --git a/docs/public-signup.md b/docs/public-signup.md
index a7934070..d74ddf22 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -376,6 +376,9 @@ With it on:
(`detail` in `GET /api/admin/generations`). A failed run on the studio's GPUs never offers "Fix it".
- A run may wait `FUOBE_POOL_WAIT_MIN` minutes (30 by default, or what the billing service says) before a worker
first takes it; past that it fails, not charged. Once a worker took it, that limit is over.
+- People's runs go before the owner's own jobs on the same GPUs, in the order they came (a billing service can put
+ paid runs first). One attempt may run as long as its lane's run ceiling, which the owner sets (45 minutes by
+ default; [gpu-workers.md](gpu-workers.md#the-queue)).
- In a run's `params.extra`, a file input is used only when the run sent that file itself. A name of a file in the
GPUs' folders is dropped. The graph is checked before it is queued or sent: it reads only the files this run sent.
- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.
diff --git a/src/app/api/admin/queue/settings/route.ts b/src/app/api/admin/queue/settings/route.ts
new file mode 100644
index 00000000..39dbf543
--- /dev/null
+++ b/src/app/api/admin/queue/settings/route.ts
@@ -0,0 +1,36 @@
+import { connection } from "next/server";
+import { adminAccess, audit } from "@/server/admin-tokens";
+import { checkQueuePatch, queueSettings, saveQueueSettings } from "@/server/queue-settings";
+
+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 and the pick allowance (src/server/queue-settings.ts).
+ */
+export async function GET(request: Request) {
+ await connection();
+ const access = adminAccess(request, "queue:read", "Only the studio's owner sees the queue");
+ if (access instanceof Response) return access;
+ return Response.json({ settings: queueSettings() }, { headers: NO_STORE });
+}
+
+/**
+ * Change them (owner only, or an admin token with queue:write): any of `{ runCeilingS: { default, lanes },
+ * ownerWaitLimitS, fairShare, pickAllowanceMs }`. 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) {
+ const access = adminAccess(request, "queue:write", "Only the studio's owner changes the queue");
+ if (access instanceof Response) return access;
+ const body = (await request.json().catch(() => null)) as unknown;
+ const before = queueSettings();
+ const r = checkQueuePatch(body, before);
+ if ("error" in r) {
+ audit(access.actor, "queue.settings", null, { keys: body && typeof body === "object" ? Object.keys(body).slice(0, 8) : [] }, 400);
+ return Response.json({ error: r.error }, { status: 400, headers: NO_STORE });
+ }
+ const settings = saveQueueSettings(r.settings);
+ audit(access.actor, "queue.settings", null, { before, after: settings }, 200);
+ return Response.json({ settings }, { headers: NO_STORE });
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index ed57ee6f..477198f3 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1119,6 +1119,10 @@ export interface GenerationRequest {
checkOutputs?: boolean;
/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */
waitMs?: number;
+ /** Server-only: the run's class in the line on this install's GPUs ("paid" goes before "free"), from the billing service. */
+ class?: "paid" | "free";
+ /** Server-only: a head start in line within its class (ms), from the billing service. */
+ boostMs?: number;
feature: string;
presetId?: string;
modelId: string;
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index 1596c52d..172659a3 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -31,6 +31,7 @@ export const SCOPES = [
"workers:write",
"workers:tokens",
"queue:read",
+ "queue:write",
"audit:read",
] as const;
@@ -50,7 +51,8 @@ export const SCOPE_LABELS: Record<Scope, string> = {
"workers:read": "See workers",
"workers:write": "Pause, resume, change and revoke workers",
"workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)",
- "queue:read": "See the queue",
+ "queue:read": "See the queue and its settings",
+ "queue:write": "Change the queue's settings: the run ceiling, the owner's wait limit, fair share and the pick allowance",
"audit:read": "See the admin log",
};
diff --git a/src/server/billing.ts b/src/server/billing.ts
index 7eb6d2b7..6acb2930 100644
--- a/src/server/billing.ts
+++ b/src/server/billing.ts
@@ -99,7 +99,19 @@ export interface Policy {
}
export type ReserveAnswer =
- | { ok: true; holdId: string; amount: number; boostMs: number; maxWaitMs: number; pools?: string[]; text: string }
+ | {
+ ok: true;
+ holdId: string;
+ amount: number;
+ /** A head start in line within the run's class (ms). */
+ boostMs: number;
+ /** The longest the run may wait before a worker first takes it (ms; 0: the install's own limit). */
+ maxWaitMs: number;
+ pools?: string[];
+ /** The run's class in the line: "paid" goes before "free" (absent: "free"). */
+ class?: "paid" | "free";
+ text: string;
+ }
| { ok: false; code: RefuseCode | "price-changed"; text: string; quote?: Quote; action?: Action; offer?: Offer };
export interface Balance {
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 29791c34..67f30caa 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -6,6 +6,7 @@ import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setTask, takeTask, taskById, type TaskRow } from "./tasks";
+import { queueSettings, runCeilingMs } from "../queue-settings";
import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
/**
@@ -24,17 +25,30 @@ export const RETRY_WINDOW_MS = 10 * 60_000;
export const MAX_ATTEMPTS = 3;
/** A worker that beat this recently may claim. */
const FRESH_BEAT_MS = 30_000;
-/** The run limit: 3 × the lane's p90 on that worker, at least 5 minutes, at most 45. */
-export const runLimitMs = (p90?: number | null) => Math.min(45 * 60_000, Math.max(5 * 60_000, 3 * (p90 ?? 0)));
-/** The owner's own tasks go ahead of everyone else's by this much (rank_at = created_at - boost). */
-export const OWNER_BOOST_MS = 24 * 60 * 60_000;
/**
- * The order workers serve waiting tasks in: 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.
+ * The run limit of one attempt: 3 × the lane's p90 on that worker plus its model load, at least 10 minutes, and never
+ * past the lane's run ceiling (queue-settings.ts; 45 minutes unless the owner sets another). With no p90 yet, the
+ * ceiling.
*/
-const LINE_ORDER = "rank_at, created_at, id";
+export const runLimitMs = (p90?: number | null, lane?: string | null, loadMs?: number | null) => {
+ const ceiling = runCeilingMs(lane);
+ if (!p90 || p90 <= 0) return ceiling;
+ return Math.min(ceiling, Math.max(10 * 60_000, 3 * p90 + Math.max(0, loadMs ?? 0)));
+};
+/**
+ * A task's class as a number, in the order workers serve them: people's paid runs (0), then their free runs (1), then
+ * the owner's own jobs (2). A task from before classes had none: the owner's (no account) is the owner's class.
+ */
+const CLASS_RANK = "(CASE WHEN class = 'paid' THEN 0 WHEN class = 'owner' OR (class IS NULL AND account IS NULL) THEN 2 ELSE 1 END)";
+export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.class === "paid" ? 0 : t.class === "owner" || (!t.class && !t.account) ? 2 : 1);
+/**
+ * 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
+ * (queue-settings.ts), each class goes round its accounts in turn (lineOrder).
+ */
+const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;
/** The columns the line's counts read (never a task's graph or files). */
-const LINE_COLS = "id, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account";
+const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class";
/** A task a worker took that is still sending its files to its ComfyUI this long after the claim goes back in line. */
export const SENDING_MS = 15 * 60_000;
@@ -269,7 +283,7 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now()):
function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {
const needs = json<Needs | null>(t.needs_json, null);
- const p90 = t.lane ? benchOf(w)[t.lane]?.p90Ms : undefined;
+ const bench = t.lane ? benchOf(w)[t.lane] : undefined;
if (t.state === "waiting") logWorkerJob("claimed", t, w.id, now);
// A worker that lost track of its own task gets it again with its first claim's time, so the sending clock (SENDING_MS)
// is never wound back by asking again.
@@ -278,7 +292,7 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed
...c,
lane: t.lane ?? undefined,
estMs: estOn(t, w),
- runLimitMs: runLimitMs(p90),
+ runLimitMs: runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs),
notAfter: t.not_after,
attempt: t.requeues + 1,
models: needs?.files ?? [],
@@ -322,17 +336,71 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
return now + (estOn(t, w) ?? 0) <= h.endsAt;
}
+/**
+ * The best task this worker may run, in the line's order (lineOrder). A task in the lane it has loaded may go ahead of
+ * the best one, in the same class, 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).
+ */
function pick(w: WorkerRow, now: number): TaskRow | null {
+ const settings = queueSettings(now);
const rows = db()
.prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ORDER BY ${LINE_ORDER} LIMIT ?`)
.all(`,${w.pool},`, LOOK_AT) as TaskRow[];
- const ok = rows.filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
+ const ok = lineOrder(rows, settings.fairShare).filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
if (!ok.length) return null;
- const warm = w.warm_lane ? ok.find((t) => t.lane === w.warm_lane) : undefined;
- const other = ok.find((t) => t.lane !== w.warm_lane);
- if (!warm) return other ?? null;
- if (other && (other.rank_at ?? 0) < now - w.switch_after_ms && (other.rank_at ?? 0) < (warm.rank_at ?? 0)) return other;
- return warm;
+ const best = ok[0];
+ const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
+ if (allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return best;
+ const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === classRank(best));
+ return warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best;
+}
+
+/**
+ * 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.
+ */
+function servedTurns(waiting: TaskRow[]): Map<string, number> {
+ const since = new Map<number, number>();
+ for (const r of waiting) since.set(classRank(r), Math.min(since.get(classRank(r)) ?? Infinity, r.created_at));
+ const out = new Map<string, number>();
+ for (const [cls, at] of since) {
+ const rows = db()
+ .prepare(
+ `SELECT COALESCE(account, principal) AS k, COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND ${CLASS_RANK} = ?
+ AND (state IN ('sending','queued','running','collecting') OR (state IN ('done','failed') AND claimed_at IS NOT NULL AND finished_at >= ?))
+ GROUP BY k`,
+ )
+ .all(cls, at) as { k: string; n: number }[];
+ for (const r of rows) out.set(`${cls}:${r.k}`, r.n);
+ }
+ return out;
+}
+
+/** Whose turn a task takes with fair share: its account's, or the owner's. */
+const turnKey = (t: Pick<TaskRow, "account" | "principal" | "class">) => `${classRank(t as Pick<TaskRow, "class" | "account">)}:${t.account ?? t.principal}`;
+
+/** The strict order (LINE_ORDER) of two tasks, in code. */
+const strictOrder = (a: TaskRow, b: TaskRow) =>
+ classRank(a) - classRank(b) || (a.rank_at ?? a.created_at) - (b.rank_at ?? b.created_at) || a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
+
+/**
+ * Waiting tasks (given in strict order) in the order workers serve them. Fair share off: as given. On: within a class,
+ * each account's (or the owner's) next run goes after every other account's run that is an earlier turn of its own. An
+ * account's turns count the runs a worker holds for it now and those a worker finished for it since the oldest run
+ * still waiting in its class came, so one account with many runs never holds the line.
+ */
+export function lineOrder(rows: TaskRow[], fairShare: boolean): TaskRow[] {
+ if (!fairShare || rows.length < 2) return rows;
+ const held = servedTurns(rows);
+ const seen = new Map<string, number>();
+ const turns = new Map<string, number>();
+ for (const r of [...rows].sort(strictOrder)) {
+ const k = turnKey(r);
+ const n = seen.get(k) ?? 0;
+ seen.set(k, n + 1);
+ turns.set(r.id, (held.get(k) ?? 0) + n);
+ }
+ return [...rows].sort((a, b) => classRank(a) - classRank(b) || turns.get(a.id)! - turns.get(b.id)! || strictOrder(a, b));
}
// ---------------------------------------------------------------------------
@@ -440,14 +508,7 @@ export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaS
const d = db();
const all = poolWorkers().filter((w) => sharePool({ pools: w.pool }, t));
const workers = all.filter((w) => eligible(w, now) && fits({ ...t, created_at: 0 }, w, now));
- const rank = t.rank_at ?? t.created_at;
- const before = d
- .prepare(
- `SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?
- AND (rank_at < ? OR (rank_at = ? AND (created_at < ? OR (created_at = ? AND id < ?))))
- ORDER BY ${LINE_ORDER} LIMIT ?`,
- )
- .all(t.id, rank, rank, t.created_at, t.created_at, t.id, LOOK_AHEAD) as TaskRow[];
+ const before = lineBefore(t, now);
// Ahead of it: a task the same workers would serve first (with none able to run it now, any that could run it at all).
const able = workers.length ? workers : all.filter((w) => fits({ ...t, created_at: 0 }, w, now));
const ahead = before.filter((x) => sharePool(x, t) && (!able.length || able.some((w) => fits({ ...x, created_at: 0 }, w, now))));
@@ -464,6 +525,25 @@ export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaS
return { place: ahead.length + 1, etaSeconds: Math.round(((sum + left) / workers.length + load + own) / 1000) };
}
+/** The waiting tasks served before this one (at most LOOK_AHEAD), in the line's order. */
+function lineBefore(t: TaskRow, now: number): TaskRow[] {
+ const d = db();
+ const rank = t.rank_at ?? t.created_at;
+ const cls = classRank(t);
+ if (!queueSettings(now).fairShare) {
+ return d
+ .prepare(
+ `SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?
+ AND (${CLASS_RANK} < ? OR (${CLASS_RANK} = ? AND (rank_at < ? OR (rank_at = ? AND (created_at < ? OR (created_at = ? AND id < ?))))))
+ ORDER BY ${LINE_ORDER} LIMIT ?`,
+ )
+ .all(t.id, cls, cls, rank, rank, t.created_at, t.created_at, t.id, LOOK_AHEAD) as TaskRow[];
+ }
+ const rows = d.prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ? ORDER BY ${LINE_ORDER} LIMIT ?`).all(t.id, LOOK_AHEAD) as TaskRow[];
+ const line = lineOrder([...rows, t], true);
+ return line.slice(0, line.findIndex((x) => x.id === t.id));
+}
+
/** A one-argument function whose answers are kept for this call's life. */
function memo<A, R>(fn: (a: A) => R): (a: A) => R {
const seen = new Map<A, R>();
@@ -521,7 +601,8 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
const workflowId = asked && !asked.includes("{") ? asked : null;
const lane = workflowId ? poolLane(workflowId) : null;
const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;
- const probe = { id: "", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null } as unknown as TaskRow;
+ // A new run of a person's, in the free class (a paid run's head start is the billing service's to price, not to quote).
+ const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null } as unknown as TaskRow;
const p = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };
const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fits({ ...probe, created_at: 0 }, w, now))).length;
const mine = accountId
@@ -532,15 +613,20 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null, mine: { waiting: mine.waiting ?? 0, running: mine.running ?? 0 } };
}
-/** What a task for workers stores: its lane, its needs, and its place in line. */
-export function poolFields(workflowId: string, o: { account?: string; boostMs?: number; waitMs?: number; onlyWorker?: string } = {}, now = Date.now()) {
+/**
+ * What a task for workers stores: its lane, its needs, its class and its place in line. A person's run is "free" unless
+ * the billing service said "paid"; the owner's own jobs are the "owner" class, served after every person's.
+ */
+export function poolFields(workflowId: string, o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; waitMs?: number; onlyWorker?: string } = {}, now = Date.now()) {
const index = loadIndex();
const needs = needsOf(index, workflowId);
const lane = poolLane(workflowId);
return {
pools: ["pool"],
account: o.account,
- rankAt: now - (o.boostMs ?? 0),
+ class: o.class ?? (o.account ? ("free" as const) : ("owner" as const)),
+ // A head start is only inside a class, and never more than a day.
+ rankAt: now - Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000)),
lane,
needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0 },
notAfter: o.waitMs ? now + o.waitMs : undefined,
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index b4463813..431444a0 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -106,6 +106,8 @@ export interface TaskRow {
not_after: number | null;
only_worker: string | null;
worker_id: string | null;
+ /** Its class in the line: "paid", "free" (people's runs) or "owner" (the owner's own jobs, served last). NULL: from before classes, read as "owner" with no account and "free" with one. */
+ class: string | null;
created_at: number;
updated_at: number;
claimed_at: number | null;
@@ -306,7 +308,7 @@ export interface NewTask {
/** How many results its workflow says one job makes (an owner's job keeps no more than that, and at least 16). */
outputs?: number;
/** For workers (pool.ts): the pools that may take it, and what they need to. */
- pool?: { pools: string[]; account?: string; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string };
+ pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string };
}
/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */
@@ -320,8 +322,8 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
const pool = t.pool;
d.prepare(
`INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,
- account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker)
- VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class)
+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
id,
t.principal,
@@ -343,6 +345,7 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
pool?.estMs ?? null,
pool?.notAfter ?? null,
pool?.onlyWorker ?? null,
+ pool ? (pool.class ?? (pool.account ? "free" : "owner")) : null,
);
const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];
let n = 0;
diff --git a/src/server/db.ts b/src/server/db.ts
index ade9b442..e784c5b1 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -986,6 +986,8 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_tasks", "not_after", "INTEGER"],
["relay_tasks", "only_worker", "TEXT"],
["relay_tasks", "worker_id", "TEXT"],
+ // The class a task waits in: "paid", "free" or "owner" (pool.ts LINE_ORDER).
+ ["relay_tasks", "class", "TEXT"],
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index d4dcbef5..6699e7cf 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -97,9 +97,11 @@ import { convertMask, decodePng, encodePng } from "./png";
import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";
import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";
import { accountSend } from "./account-send";
-import { stamped, stampOf, withRunStamp } from "./run-stamp";
+import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";
import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
import { placeInLine, poolWaitMs, runOnPool } from "./hosted";
+import { poolLane } from "./computer/pool";
+import { runCeilingMs } from "./queue-settings";
import { sweepBilling } from "./billing-outbox";
import { inDemoScope } from "./demo-scope";
import { moderationConfigured } from "./moderation";
@@ -151,8 +153,10 @@ const LIBRARY_JOIN = `generations g ${LIBRARY_JOINS}`;
export function toGeneration(r: Row): Generation {
const stored = JSON.parse(r.request_json) as GenerationRequest;
- // The billing hold is the server's: never sent to a browser or a script.
- const { hold, ...request } = stored;
+ // The run's stamp is the server's (its place, the billing hold, its class in the line): never sent to a browser or a
+ // script, so a retry that sends the request back never says where the last attempt ran.
+ const hold = stored.hold;
+ const request = withoutStamp(stored);
// A run on this install's GPUs shows the account only where it is (in line, working) and its result, or one plain
// sentence when it can't finish: never the technical reason, which the owner reads in the accounts' runs.
const pool = stored.place === "pool";
@@ -1987,7 +1991,10 @@ async function submitNow(
const POLL_MS = 1500;
/** Jobs about to finish (progress ≥ 0.9) are polled this often, so results land sooner. */
const FAST_POLL_MS = 500;
-/** How long a job may run once its provider has started it… */
+/**
+ * How long a job may run once its provider has started it… (A job on this install's own GPUs: its lane's run ceiling,
+ * which the owner sets, 45 minutes by default: runningLimitMs.)
+ */
const TIMEOUT_MS = 45 * 60 * 1000;
/** …and how long it may wait in the provider's queue first (a busy local GPU works through jobs one by one). */
const QUEUE_TIMEOUT_MS = 4 * 60 * 60 * 1000;
@@ -2154,6 +2161,17 @@ async function fastTick(): Promise<void> {
}
}
+/**
+ * How long a started job may run: on this install's own GPUs (an account's run there, or the owner's ComfyUI job), its
+ * lane's run ceiling (queue-settings.ts); anywhere else (an account's own GPU or key, a cloud provider) 45 minutes, as
+ * always.
+ */
+function runningLimitMs(r: Pick<Row, "provider">, meta: Record<string, unknown>, account: string | undefined, onPool: boolean): number {
+ if (r.provider !== "comfyui" || (account && !onPool)) return TIMEOUT_MS;
+ const wf = typeof meta.workflowId === "string" && !meta.workflowId.includes("{") ? meta.workflowId : null;
+ return runCeilingMs(wf ? poolLane(wf) : null);
+}
+
/** Order by: the owner's rows (no account in the request) before accounts'. */
const ACCOUNT_LAST = "(json_extract(request_json, '$.account') IS NOT NULL)";
@@ -2215,7 +2233,8 @@ async function pollOne(r: Row): Promise<void> {
}
// A job that has just left the queue gets its full running time from now.
const startsNow = res?.state === "running" && !run.started_at;
- const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !ownClocks && !startsNow && now - run.submitted_at > queueMs;
+ const limitMs = runningLimitMs(r, ctx.meta, account, onPool);
+ const overdue = run.started_at ? now - run.started_at > limitMs : !ownClocks && !startsNow && now - run.submitted_at > queueMs;
if (overdue) {
// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.
await adapterFor(r.provider, account)
@@ -2224,7 +2243,7 @@ async function pollOne(r: Row): Promise<void> {
update(r.id, {
status: "failed",
error: run.started_at
- ? `Timed out after ${TIMEOUT_MS / 60_000} minutes`
+ ? `Timed out after ${Math.round(limitMs / 60_000)} minutes`
: res?.state === "queued" && res.timeoutError
? res.timeoutError
: onPool
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 61d9cf38..29bbf1d6 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -189,7 +189,19 @@ export async function reservePool(account: Account, req: GenerationRequest, plan
return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };
}
forgetBalance(account.id);
- return { ok: true, stamp: { ...base, hold: a.holdId, ...(a.text && { charge: a.text }), ...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }) } };
+ // Its class and head start in the line come from the answer too (a paid run goes before every free one).
+ const boost = Number(a.boostMs);
+ return {
+ ok: true,
+ stamp: {
+ ...base,
+ hold: a.holdId,
+ ...(a.text && { charge: a.text }),
+ ...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),
+ ...(a.class === "paid" && { class: "paid" as const }),
+ ...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),
+ },
+ };
}
/**
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index d86dbeea..9a731871 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -113,7 +113,8 @@ import {
type Principal,
type TaskRow,
} from "../computer/tasks";
-import { OWNER_BOOST_MS, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords } from "../computer/pool";
+import { poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords } from "../computer/pool";
+import { ownerWaitMs } from "../queue-settings";
export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");
@@ -2568,10 +2569,12 @@ export const comfyProvider: ProviderAdapter = {
...(forPool && {
pool:
computer === "owner"
- ? // The owner's jobs on the workers: the lane and files they need, ahead of everyone else's, with a wait limit.
- poolFields(manifest.id, { boostMs: OWNER_BOOST_MS, waitMs: poolWaitMs() })
- : // An account's: the lane and files they need, in the order they came, with the wait set for the run.
- poolFields(manifest.id, { account: computer.slice(5), waitMs: runStamp()?.waitMs || poolWaitMs() }),
+ ? // 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() })
+ : // 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.
+ poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs() }),
}),
});
return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };
diff --git a/src/server/queue-settings.ts b/src/server/queue-settings.ts
new file mode 100644
index 00000000..a54182d2
--- /dev/null
+++ b/src/server/queue-settings.ts
@@ -0,0 +1,133 @@
+import "server-only";
+import { db } from "./db";
+
+/**
+ * The line's install-wide settings (the owner's, through GET and PATCH /api/admin/queue/settings; docs/admin-api.md):
+ *
+ * - `runCeilingS`: the longest one attempt at a job on this install's GPUs may run, in seconds: a default, and a value
+ * per lane that overrides it. It ends the generation's own clock and is the most a worker's run limit may be.
+ * - `ownerWaitLimitS`: how long the owner's own jobs on the workers may wait in line before a worker first takes them
+ * (null: no limit). People's runs go first, so the owner's jobs can wait a long time.
+ * - `fairShare`: off, the line goes strictly by class, then by when each job came. On, an account's (or the owner's)
+ * 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).
+ *
+ * Kept in the settings table under one key, as JSON. Nothing set: the defaults, which are today's fixed values.
+ */
+
+export interface QueueSettings {
+ runCeilingS: { default: number; lanes: Record<string, number> };
+ ownerWaitLimitS: number | null;
+ fairShare: boolean;
+ pickAllowanceMs: number;
+}
+
+export const QUEUE_DEFAULTS: QueueSettings = { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0 };
+
+/** 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 },
+ lanes: 200,
+};
+
+const KEY = "queue.settings";
+const LANE = /^[0-9a-f]{12}$|^small$/;
+
+declare global {
+ var __fuobeQueueSettings: { at: number; raw: string | null; value: QueueSettings } | undefined;
+}
+
+const copy = (s: QueueSettings): QueueSettings => ({ ...s, runCeilingS: { default: s.runCeilingS.default, lanes: { ...s.runCeilingS.lanes } } });
+
+/** A stored value read leniently: anything that isn't valid is the default (a bad row never stops a run). */
+function fromStored(raw: string | null): QueueSettings {
+ if (!raw) return copy(QUEUE_DEFAULTS);
+ try {
+ const r = checkQueuePatch(JSON.parse(raw) as unknown, QUEUE_DEFAULTS);
+ return "error" in r ? copy(QUEUE_DEFAULTS) : r.settings;
+ } catch {
+ return copy(QUEUE_DEFAULTS);
+ }
+}
+
+/** The settings in effect (read again at most every 2 s: both of a deploy's processes see a change within that). */
+export function queueSettings(now = Date.now()): QueueSettings {
+ const c = globalThis.__fuobeQueueSettings;
+ if (c && now - c.at < 2000) return copy(c.value);
+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(KEY) as { value: string } | undefined;
+ const raw = row?.value ?? null;
+ const value = c && c.raw === raw ? c.value : fromStored(raw);
+ globalThis.__fuobeQueueSettings = { at: now, raw, value };
+ return copy(value);
+}
+
+const whole = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v);
+const inRange = (v: unknown, b: { min: number; max: number }): v is number => whole(v) && v >= b.min && v <= b.max;
+
+/**
+ * A change checked against `base`: every field is optional, and a given `runCeilingS` replaces the default and the
+ * whole lane list. The error says what is wrong, in words.
+ */
+export function checkQueuePatch(body: unknown, base: QueueSettings = queueSettings()): { settings: QueueSettings } | { error: string } {
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "Send the settings as an object" };
+ const b = body as Record<string, unknown>;
+ const known = ["runCeilingS", "ownerWaitLimitS", "fairShare", "pickAllowanceMs"];
+ const unknown = Object.keys(b).filter((k) => !known.includes(k));
+ if (unknown.length) return { error: `Unknown setting: ${unknown[0]}` };
+ const out = copy(base);
+ const { min, max } = QUEUE_BOUNDS.ceilingS;
+ if (b.runCeilingS !== undefined) {
+ const r = b.runCeilingS as { default?: unknown; lanes?: unknown } | null;
+ if (!r || typeof r !== "object") return { error: "runCeilingS is { default, lanes }" };
+ if (!inRange(r.default, QUEUE_BOUNDS.ceilingS)) return { error: `runCeilingS.default is ${min} to ${max} seconds` };
+ const lanes: Record<string, number> = {};
+ if (r.lanes !== undefined && r.lanes !== null) {
+ if (typeof r.lanes !== "object" || Array.isArray(r.lanes)) return { error: "runCeilingS.lanes maps a lane to seconds" };
+ const entries = Object.entries(r.lanes as Record<string, unknown>);
+ if (entries.length > QUEUE_BOUNDS.lanes) return { error: `runCeilingS.lanes holds up to ${QUEUE_BOUNDS.lanes} lanes` };
+ for (const [lane, s] of entries) {
+ if (!LANE.test(lane)) return { error: `No such lane: ${lane.slice(0, 40)}` };
+ if (!inRange(s, QUEUE_BOUNDS.ceilingS)) return { error: `The run ceiling for ${lane} is ${min} to ${max} seconds` };
+ lanes[lane] = s;
+ }
+ }
+ out.runCeilingS = { default: r.default, lanes };
+ }
+ if (b.ownerWaitLimitS !== undefined) {
+ const w = QUEUE_BOUNDS.ownerWaitS;
+ if (b.ownerWaitLimitS !== null && !inRange(b.ownerWaitLimitS, w)) return { error: `ownerWaitLimitS is ${w.min} to ${w.max} seconds, or null for no limit` };
+ out.ownerWaitLimitS = b.ownerWaitLimitS as number | null;
+ }
+ if (b.fairShare !== undefined) {
+ if (typeof b.fairShare !== "boolean") return { error: "fairShare is true or false" };
+ out.fairShare = b.fairShare;
+ }
+ if (b.pickAllowanceMs !== undefined) {
+ const p = QUEUE_BOUNDS.pickAllowanceMs;
+ if (!inRange(b.pickAllowanceMs, p)) return { error: `pickAllowanceMs is ${p.min} to ${p.max}` };
+ out.pickAllowanceMs = b.pickAllowanceMs;
+ }
+ return { settings: out };
+}
+
+/** Save the settings (checked first with checkQueuePatch). */
+export function saveQueueSettings(s: QueueSettings): QueueSettings {
+ const value = JSON.stringify(s);
+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(KEY, value);
+ globalThis.__fuobeQueueSettings = undefined;
+ return queueSettings();
+}
+
+/** The run ceiling of a lane, in ms (the default when the lane has none of its own, or isn't known). */
+export function runCeilingMs(lane: string | null | undefined, s: QueueSettings = queueSettings()): number {
+ const own = lane ? s.runCeilingS.lanes[lane] : undefined;
+ return (own ?? s.runCeilingS.default) * 1000;
+}
+
+/** How long the owner's own job on the workers may wait for its first start (ms), or undefined for no limit. */
+export function ownerWaitMs(s: QueueSettings = queueSettings()): number | undefined {
+ return s.ownerWaitLimitS === null ? undefined : s.ownerWaitLimitS * 1000;
+}
diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.ts
index 930a24a5..e5b18da2 100644
--- a/src/server/run-stamp.ts
+++ b/src/server/run-stamp.ts
@@ -11,6 +11,7 @@ import type { GenerationRequest } from "@/lib/catalog/types";
* - `hold`: the billing service's hold for the run (billing.ts reserve); every row reports to it once (billing-outbox.ts).
* - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.
* - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).
+ * - `class` and `boostMs`: its class in the line ("paid" before "free") and its head start inside that class.
*/
export interface RunStamp {
place?: "pool";
@@ -19,6 +20,10 @@ export interface RunStamp {
checkOutputs?: boolean;
/** How long it may wait in line on this install's GPUs (ms), from the billing service. */
waitMs?: number;
+ /** Its class in the line on this install's GPUs, from the billing service (none: "free"). */
+ class?: "paid" | "free";
+ /** A head start in line within its class (ms), from the billing service. */
+ boostMs?: number;
}
declare global {
@@ -34,7 +39,7 @@ export const withRunStamp = <T,>(stamp: RunStamp, fn: () => T): T => store().run
export const runStamp = (): RunStamp | undefined => store().getStore();
/** The server-only fields of a request. */
-export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs"] as const;
+export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs", "class", "boostMs"] as const;
/** A request with the current stamp's fields, and none of a stored request's own. */
export function stamped(req: GenerationRequest): GenerationRequest {
@@ -49,10 +54,27 @@ export function stamped(req: GenerationRequest): GenerationRequest {
...(s.charge && { charge: s.charge }),
...(s.checkOutputs && { checkOutputs: true }),
...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),
+ ...(s.class === "paid" && { class: "paid" as const }),
+ ...(s.boostMs && s.boostMs > 0 && { boostMs: s.boostMs }),
};
}
/** A stored request's stamp, to run a later step of it (advanceDependents, polls) as it was decided. */
export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[number]>): RunStamp {
- return { ...(req.place === "pool" && { place: "pool" as const }), ...(req.hold && { hold: req.hold }), ...(req.charge && { charge: req.charge }), ...(req.checkOutputs && { checkOutputs: true }), ...(req.waitMs && { waitMs: req.waitMs }) };
+ return {
+ ...(req.place === "pool" && { place: "pool" as const }),
+ ...(req.hold && { hold: req.hold }),
+ ...(req.charge && { charge: req.charge }),
+ ...(req.checkOutputs && { checkOutputs: true }),
+ ...(req.waitMs && { waitMs: req.waitMs }),
+ ...(req.class === "paid" && { class: "paid" as const }),
+ ...(req.boostMs && req.boostMs > 0 && { boostMs: req.boostMs }),
+ };
+}
+
+/** A request without its server-only fields: what a browser or a script is sent (and so what a retry sends back). */
+export function withoutStamp<T extends Partial<Record<(typeof STAMP_FIELDS)[number], unknown>>>(req: T): Omit<T, (typeof STAMP_FIELDS)[number]> {
+ const out = { ...req };
+ for (const k of STAMP_FIELDS) delete out[k];
+ return out;
}
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index a491a57e..b0debc60 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -29,6 +29,7 @@ const routes = {
run: await import("@/app/api/admin/generations/[id]/route"),
outputs: await import("@/app/api/admin/outputs/[action]/route"),
queue: await import("@/app/api/admin/queue/route"),
+ queueSettings: await import("@/app/api/admin/queue/settings/route"),
workers: await import("@/app/api/admin/workers/route"),
worker: await import("@/app/api/admin/workers/[id]/route"),
download: await import("@/app/api/admin/workers/download/route"),
@@ -246,6 +247,8 @@ describe("admin tokens: every admin route asks for its scope", () => {
{ name: "POST remove", scope: "outputs:moderate", run: (o) => routes.outputs.POST(req("/api/admin/outputs/remove", { ...o, method: "POST", body: { assetIds: ["nope"] } }), ctx({ action: "remove" })) },
{ name: "GET files", scope: "outputs:view", run: (o) => routes.files.GET(req("/api/admin/files/outputs/nope.png", o), ctx({ path: ["outputs", "nope.png"] })) },
{ name: "GET queue", scope: "queue:read", run: (o) => routes.queue.GET(req("/api/admin/queue", o)) },
+ { name: "GET queue settings", scope: "queue:read", run: (o) => routes.queueSettings.GET(req("/api/admin/queue/settings", o)) },
+ { name: "PATCH queue settings", scope: "queue:write", run: (o) => routes.queueSettings.PATCH(req("/api/admin/queue/settings", { ...o, method: "PATCH", body: { fairShare: false } })) },
{ name: "GET workers", scope: "workers:read", run: (o) => routes.workers.GET(req("/api/admin/workers", o)) },
{ name: "GET download", scope: "workers:read", run: (o) => routes.download.GET(req("/api/admin/workers/download", o)) },
{ name: "POST workers", scope: "workers:tokens", run: (o) => routes.workers.POST(req("/api/admin/workers", { ...o, method: "POST", body: { name: `w${++n}` } })) },
diff --git a/tests/helpers/fake-billing.ts b/tests/helpers/fake-billing.ts
index 05967904..c6ede6e8 100644
--- a/tests/helpers/fake-billing.ts
+++ b/tests/helpers/fake-billing.ts
@@ -56,6 +56,10 @@ export interface FakeBilling {
refuse: null | { code: string; text: string };
/** The policy every account gets. */
policy: Record<string, unknown>;
+ /** The policy a guest gets (GET /v1/policy with no account); null: the same as an account. */
+ guestPolicy: Record<string, unknown> | null;
+ /** Extra fields of every reserve answer that sets a price aside (a class, say). */
+ reserveExtra: Record<string, unknown>;
/** How many times each (hold, generation) pair was reported. */
reportCount: (holdId: string, generationId: string) => number;
calls_of: (path: string) => Recorded[];
@@ -80,6 +84,8 @@ export async function startFakeBilling(): Promise<FakeBilling> {
down: false,
refuse: null,
policy: { ...FAKE_POLICY },
+ guestPolicy: null,
+ reserveExtra: {},
reportCount: (h, g) => reportCounts.get(`${h} ${g}`) ?? 0,
calls_of: (p) => f.calls.filter((c) => c.path.split("?")[0] === p),
};
@@ -102,18 +108,18 @@ export async function startFakeBilling(): Promise<FakeBilling> {
const p = path.split("?")[0];
const b = (body ?? {}) as Record<string, unknown>;
if (p === "/v1/health") return json(200, { ok: true, version: "test" });
- if (p === "/v1/policy") return json(200, f.policy);
+ if (p === "/v1/policy") return json(200, !new URLSearchParams(path.split("?")[1] ?? "").get("account") && f.guestPolicy ? f.guestPolicy : f.policy);
if (p === "/v1/quote") return json(200, quote());
if (p === "/v1/reserve") {
const requestId = String(b.requestId);
const again = [...f.holds.entries()].find(([, h]) => h.requestId === requestId);
- if (again) return json(200, { ok: true, holdId: again[0], amount: again[1].amount, boostMs: 7000, maxWaitMs: 700_000, text: `${again[1].amount} units` });
+ if (again) return json(200, { ok: true, holdId: again[0], amount: again[1].amount, boostMs: 7000, maxWaitMs: 700_000, text: `${again[1].amount} units`, ...f.reserveExtra });
if (f.refuse) return json(200, { ok: false, code: f.refuse.code, text: f.refuse.text });
const shown = b.shown as { amount: number; priceVersion: string };
if (f.price.amount > shown.amount) return json(200, { ok: false, code: "price-changed", text: `The price is now ${f.price.amount} units.`, quote: quote() });
const id = `h_${++holdN}`;
f.holds.set(id, { amount: f.price.amount, requestId, reports: new Map(), released: false });
- return json(200, { ok: true, holdId: id, amount: f.price.amount, boostMs: 7000, maxWaitMs: 700_000, text: `${f.price.amount} units` });
+ return json(200, { ok: true, holdId: id, amount: f.price.amount, boostMs: 7000, maxWaitMs: 700_000, text: `${f.price.amount} units`, ...f.reserveExtra });
}
if (p === "/v1/settle" || p === "/v1/refund") {
const h = f.holds.get(String(b.holdId));
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
new file mode 100644
index 00000000..f9a76951
--- /dev/null
+++ b/tests/pool-line-order.test.ts
@@ -0,0 +1,402 @@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The order of the line on this install's GPUs and its install-wide settings: people's paid runs, then their free runs,
+ * then the owner's own jobs, each class in the order its jobs came; fair share and the pick allowance; the run ceiling
+ * per lane on both clocks; the owner's own wait limit; and GET and PATCH /api/admin/queue/settings.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-line-order-");
+process.env.FUOBE_DATA_DIR = dir;
+const DEAD = "http://127.0.0.1:7";
+process.env.COMFYUI_URL = DEAD;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const admin = await import("@/server/admin-tokens");
+const generationsRoute = await import("@/app/api/generations/route");
+const settingsRoute = await import("@/app/api/admin/queue/settings/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const { getGeneration } = await import("@/server/generations");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const qs = await import("@/server/queue-settings");
+const { loadManifest, comfyProvider, onComputer } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const MIN = 60_000;
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+let fake: FakeBilling;
+let accountId = "";
+let cookie = "";
+let other = "";
+
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ allowed = [fake.url];
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;
+ other = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ fake.reserveExtra = {};
+ fake.policy = { ...fake.policy, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7_000_000 } };
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ // (Finished ones too: fair share counts the runs a worker finished while others waited.)
+ 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 standInWorker(name = "stand-in") {
+ 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 = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);
+ return w;
+}
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+const beatAs = (w: { id: string }, now = Date.now()) =>
+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
+const claimAs = (w: { id: string }, now = Date.now()) => pool.workerClaim(workerRow(w), [], now);
+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
+const done = (id: string) => db().prepare("UPDATE relay_tasks SET state = 'done', finished_at = ? WHERE id = ?").run(Date.now(), id);
+
+let gens = 0;
+/** A task in the line: a person's (with `account`) or the owner's, in a class, made `agoMs` ago. */
+function lineTask(o: { account?: string; class?: "paid" | "free" | "owner"; agoMs?: number; lane?: string } = {}) {
+ const gid = `line-gen-${++gens}`;
+ const at = Date.now() - (o.agoMs ?? 0);
+ 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(o.account ? { account: o.account, place: "pool" } : {}), at, at);
+ const lane = o.lane ?? allLanes(loadIndex(), sha)[0].lane;
+ 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: o.class, rankAt: at, 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 t.id;
+}
+
+/** Every waiting task, claimed one by one by a worker that finishes each at once: the order the line serves them. */
+function served(w: { id: string }): string[] {
+ const out: string[] = [];
+ for (;;) {
+ beatAs(w);
+ const t = claimAs(w);
+ if (!t) return out;
+ out.push(t.id);
+ done(t.id);
+ }
+}
+
+describe("classes", () => {
+ it("the owner's own job waits behind every person's run, even ones sent long after it", () => {
+ const w = standInWorker();
+ const owner = lineTask({ agoMs: 60 * MIN });
+ const a = lineTask({ account: accountId, agoMs: 10 * MIN });
+ const b = lineTask({ account: other, agoMs: 5 * MIN });
+ const c = lineTask({ account: accountId, agoMs: 0 });
+ expect(rowOf(owner).class).toBe("owner");
+ expect(rowOf(a).class).toBe("free");
+ // Its place counts every person's run ahead of it.
+ expect(pool.placeInLine(rowOf(owner)).place).toBe(4);
+ expect(served(w)).toEqual([a, b, c, owner]);
+ });
+
+ it("paid runs go before free ones, and each class goes in the order its runs came", () => {
+ const w = standInWorker();
+ const free1 = lineTask({ account: accountId, agoMs: 30 * MIN });
+ const paid1 = lineTask({ account: other, class: "paid", agoMs: 20 * MIN });
+ const free2 = lineTask({ account: other, agoMs: 10 * MIN });
+ const paid2 = lineTask({ account: accountId, class: "paid", agoMs: 0 });
+ expect(pool.placeInLine(rowOf(free1)).place).toBe(3);
+ expect(served(w)).toEqual([paid1, paid2, free1, free2]);
+ });
+
+ it("a task from before classes reads as the owner's with no account and as a person's free run with one", () => {
+ const w = standInWorker();
+ const old = lineTask({ agoMs: 20 * MIN });
+ const person = lineTask({ account: accountId, agoMs: 10 * MIN });
+ db().prepare("UPDATE relay_tasks SET class = NULL WHERE id IN (?, ?)").run(old, person);
+ expect(served(w)).toEqual([person, old]);
+ });
+
+ it("only people's runs count as runs this worker may take now", () => {
+ const w = standInWorker();
+ lineTask({ agoMs: 1 * MIN });
+ lineTask({ account: accountId });
+ expect(beatAs(w).claimableNow).toBe(1);
+ });
+
+ it("the owner's ComfyUI job on the workers is the owner's class, with no wait limit unless the owner sets one", async () => {
+ 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));
+ 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();
+ qs.saveQueueSettings({ ...qs.queueSettings(), ownerWaitLimitS: 3600 });
+ const second = rowOf(String(((await submit("owner-gen-2")).meta as { relay: string }).relay));
+ expect(second.not_after! - second.created_at).toBeGreaterThanOrEqual(3600_000 - 1000);
+ expect(second.not_after! - second.created_at).toBeLessThanOrEqual(3600_000 + 1000);
+ });
+});
+
+describe("the billing service's class and head start", () => {
+ it("an account's run takes the class and head start the reserve answer gives", async () => {
+ standInWorker();
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...fake.policy, hosted: true, ttlS: 0 };
+ fake.reserveExtra = { class: "paid", boostMs: 60_000 };
+ const before = Date.now();
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, {
+ method: "POST",
+ headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" },
+ body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse", shown: { amount: 7, priceVersion: "v7" } }),
+ }),
+ );
+ const body = (await r.json()) as { items?: { id: string }[] };
+ expect(r.status, JSON.stringify(body)).toBe(201);
+ const id = body.items![0].id;
+ let t = taskOf(id);
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf(id);
+ }
+ expect(t?.class).toBe("paid");
+ expect(t!.rank_at!).toBeLessThanOrEqual(t!.created_at - 60_000);
+ expect(t!.rank_at!).toBeGreaterThanOrEqual(before - 60_000 - 1000);
+ // The stored run carries its class for its later steps, and the browser never sees it.
+ const stored = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json) as Record<string, unknown>;
+ expect(stored.class).toBe("paid");
+ expect(stored.boostMs).toBe(60_000);
+ const seen = getGeneration(id) as unknown as { request?: Record<string, unknown> };
+ expect(seen.request?.class).toBeUndefined();
+ expect(seen.request?.boostMs).toBeUndefined();
+ });
+
+ it("a head start never passes a day, and a class it doesn't know is free", () => {
+ const f = pool.poolFields(loadManifest().workflows[0].id, { account: accountId, boostMs: 7 * 24 * 60 * MIN }, 1_000_000_000_000);
+ expect(f.rankAt).toBe(1_000_000_000_000 - 24 * 60 * MIN);
+ expect(f.class).toBe("free");
+ expect(pool.poolFields(loadManifest().workflows[0].id, {}, 0).class).toBe("owner");
+ });
+});
+
+describe("fair share", () => {
+ it("off: strict order; on: each account's first run goes before anyone's second, counting runs it has going", () => {
+ const w = standInWorker();
+ const a1 = lineTask({ account: accountId, agoMs: 30 * MIN });
+ const a2 = lineTask({ account: accountId, agoMs: 29 * MIN });
+ const a3 = lineTask({ account: accountId, agoMs: 28 * MIN });
+ const b1 = lineTask({ account: other, agoMs: 10 * MIN });
+ const owner = lineTask({ agoMs: 60 * MIN });
+ const strict = pool.lineOrder(db().prepare("SELECT * FROM relay_tasks WHERE state = 'waiting' AND pools IS NOT NULL").all() as never, false).map((t) => t.id);
+ expect(strict).toEqual([a1, a2, a3, b1, owner]);
+ qs.saveQueueSettings({ ...qs.queueSettings(), fairShare: true });
+ expect(pool.placeInLine(rowOf(b1)).place).toBe(2);
+ expect(served(w)).toEqual([a1, b1, a2, a3, owner]);
+ });
+});
+
+describe("the pick allowance", () => {
+ it("0 (the default): strict order whatever the worker has loaded; set, a loaded lane goes first while the best one is young", () => {
+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
+ const w = standInWorker();
+ db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(lanes[1], 60 * MIN, w.id);
+ const old = lineTask({ account: accountId, agoMs: 5 * MIN, lane: lanes[0] });
+ const warm = lineTask({ account: other, agoMs: 1 * MIN, lane: lanes[1] });
+ beatAs(w);
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(claimAs(w)?.id).toBe(old);
+ done(old);
+ const old2 = lineTask({ account: accountId, agoMs: 5 * MIN, lane: lanes[0] });
+ qs.saveQueueSettings({ ...qs.queueSettings(), pickAllowanceMs: 10 * MIN });
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(warm);
+ done(warm);
+ // Never across classes: the owner's job in the loaded lane waits behind a person's run in another.
+ lineTask({ agoMs: 1 * MIN, lane: lanes[1] });
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(old2);
+ });
+});
+
+describe("the run ceiling", () => {
+ it("a worker's run limit never passes its lane's ceiling, and with no measured run it is the ceiling", () => {
+ const [a, b] = allLanes(loadIndex(), sha).map((l) => l.lane);
+ expect(pool.runLimitMs(null, a)).toBe(45 * MIN);
+ expect(pool.runLimitMs(60_000, a)).toBe(10 * MIN);
+ expect(pool.runLimitMs(20 * MIN, a, 2 * MIN)).toBe(45 * MIN);
+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 1800, lanes: { [b]: 3600 } } });
+ expect(pool.runLimitMs(null, a)).toBe(30 * MIN);
+ expect(pool.runLimitMs(null, b)).toBe(60 * MIN);
+ expect(pool.runLimitMs(15 * MIN, b, 5 * MIN)).toBe(50 * MIN);
+ });
+
+ it("a run longer than 45 minutes in a lane with a 60 minute ceiling goes on, and past 60 it stops", async () => {
+ const w = standInWorker();
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a long one" }) }),
+ );
+ const body = (await r.json()) as { items?: { id: string }[] };
+ expect(r.status, JSON.stringify(body)).toBe(201);
+ const id = body.items![0].id;
+ let t = taskOf(id);
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf(id);
+ }
+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [t!.lane!]: 3600 } } });
+ beatAs(w);
+ const got = claimAs(w)!;
+ expect(got.id).toBe(t!.id);
+ expect(got.runLimitMs).toBe(60 * MIN);
+ tasks.setTask(t!.id, { state: "running", started_at: Date.now() });
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("running");
+ const startedAgo = (ms: number) => db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);
+ startedAgo(50 * MIN);
+ beatAs(w);
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("running");
+ startedAgo(61 * MIN);
+ beatAs(w);
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("failed");
+ });
+});
+
+describe("GET and PATCH /api/admin/queue/settings", () => {
+ const req = (o: { method?: string; token?: string; cookie?: string; body?: unknown } = {}) =>
+ new NextRequest(`http://${HOST}/api/admin/queue/settings`, {
+ method: o.method ?? "GET",
+ headers: { host: HOST, ...(o.token && { authorization: `Bearer ${o.token}` }), ...(o.cookie && { cookie: o.cookie }), ...(o.body !== undefined && { "content-type": "application/json" }) },
+ ...(o.body !== undefined && { body: JSON.stringify(o.body) }),
+ });
+ 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", 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 } });
+ });
+
+ 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 } }));
+ expect(res.status).toBe(200);
+ const want = { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, pickAllowanceMs: 0 };
+ expect(await res.json()).toEqual({ settings: want });
+ expect(qs.queueSettings()).toEqual(want);
+ const row = audits().at(-1)!;
+ expect(row.actor).toBe("owner");
+ expect(row.status).toBe(200);
+ expect(JSON.parse(row.detail_json!)).toEqual({ before: qs.QUEUE_DEFAULTS, after: want });
+ // A field left out keeps its value; null takes the owner's wait limit away.
+ const back = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body: { ownerWaitLimitS: null } }));
+ expect(((await back.json()) as { settings: unknown }).settings).toEqual({ ...want, ownerWaitLimitS: null });
+ });
+
+ it("refuses values out of bounds, unknown settings and unknown lanes, and changes nothing", async () => {
+ const before = qs.queueSettings();
+ for (const body of [
+ { runCeilingS: { default: 10 } },
+ { runCeilingS: { default: 3000, lanes: { "not-a-lane": 3000 } } },
+ { runCeilingS: { default: 3000, lanes: { small: 999_999 } } },
+ { ownerWaitLimitS: -1 },
+ { fairShare: "yes" },
+ { pickAllowanceMs: 1.5 },
+ { somethingElse: 1 },
+ [1, 2],
+ null,
+ ]) {
+ const res = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body }));
+ expect(res.status, JSON.stringify(body)).toBe(400);
+ expect(typeof ((await res.json()) as { error: string }).error).toBe("string");
+ }
+ expect(qs.queueSettings()).toEqual(before);
+ expect(audits().at(-1)!.status).toBe(400);
+ });
+
+ it("a stored value that isn't valid reads as the defaults", () => {
+ db().prepare("INSERT INTO settings (key, value) VALUES ('queue.settings', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run("{not json");
+ globalThis.__fuobeQueueSettings = undefined;
+ expect(qs.queueSettings()).toEqual(qs.QUEUE_DEFAULTS);
+ });
+
+ it("an admin token reads them with queue:read and changes them with queue:write", async () => {
+ const make = (scopes: import("@/server/admin-tokens").Scope[]) => admin.createAdminToken({ name: `t-${Math.random()}`, scopes });
+ const reader = make(["queue:read"]);
+ const writer = make(["queue:write"]);
+ expect((await settingsRoute.GET(req({ token: reader.token }))).status).toBe(200);
+ expect((await settingsRoute.GET(req({ token: writer.token }))).status).toBe(403);
+ expect((await settingsRoute.PATCH(req({ method: "PATCH", token: reader.token, body: { fairShare: true } }))).status).toBe(403);
+ const ok = await settingsRoute.PATCH(req({ method: "PATCH", token: writer.token, body: { pickAllowanceMs: 60_000 } }));
+ expect(ok.status).toBe(200);
+ expect(audits().at(-1)!.token_id).toBe(writer.info.id);
+ // Nobody else.
+ expect((await settingsRoute.GET(req())).status).toBe(403);
+ expect((await settingsRoute.PATCH(req({ method: "PATCH", cookie, body: { fairShare: true } }))).status).toBe(403);
+ });
+});
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index 28f67fd6..a85f36f1 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -24,6 +24,7 @@ const { forWorkers } = await import("@/server/providers/comfyui");
const { hoursAt, parseHours } = await import("@/lib/worker-hours");
const { lanesFor, needsOf, laneOf } = await import("@/lib/lanes");
const { loadIndex } = await import("@/server/gpu/index-file");
+const { QUEUE_DEFAULTS, queueSettings, saveQueueSettings } = await import("@/server/queue-settings");
const LANE_A = "aaaaaaaaaaaa";
const LANE_B = "bbbbbbbbbbbb";
@@ -253,9 +254,15 @@ describe("losing a worker (checks 3, 4, 5)", () => {
});
describe("order (checks 8, 9)", () => {
- it("sticky lanes: the warm lane goes first until another lane's best task passes switch_after_ms", () => {
+ it("sticky lanes: the warm lane goes first until another lane's best task passes the pick allowance", () => {
const w = worker("sticky", { lanes: [LANE_A, LANE_B] });
db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(LANE_A, 30 * MIN, w.id);
+ // The install's pick allowance is 0 by default: strict order, whatever the worker's own setting.
+ const first = task({ lane: LANE_B, rankAgoMs: 2 * MIN });
+ const warm = task({ lane: LANE_A, rankAgoMs: 1 * MIN });
+ expect(claim(w)?.id).toBe(first);
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id IN (?, ?)").run(first, warm);
+ saveQueueSettings({ ...queueSettings(), pickAllowanceMs: 60 * MIN });
const b = task({ lane: LANE_B, rankAgoMs: 10 * MIN });
const a = task({ lane: LANE_A, rankAgoMs: 1 * MIN });
expect(claim(w)?.id).toBe(a);
@@ -264,6 +271,7 @@ describe("order (checks 8, 9)", () => {
db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 31 * MIN, b);
expect(claim(w)?.id).toBe(b);
expect(state(a2).state).toBe("waiting");
+ saveQueueSettings(QUEUE_DEFAULTS);
});
it("near the end of its hours, a task that would overrun is not claimed", () => {
@@ -276,10 +284,10 @@ describe("order (checks 8, 9)", () => {
expect(state(long).state).toBe("waiting");
});
- it("the owner's tasks go by rank_at, not by arrival", () => {
+ it("tasks in one class go by rank_at, not by arrival", () => {
const w = worker("rank");
const later = task({ rankAgoMs: 0 });
- const boosted = task({ rankAgoMs: pool.OWNER_BOOST_MS });
+ const boosted = task({ rankAgoMs: 24 * 60 * MIN });
expect(claim(w)?.id).toBe(boosted);
expect(state(later).state).toBe("waiting");
});
@@ -309,7 +317,8 @@ describe("routes", () => {
const { task: t } = await c.json();
expect(t.id).toBe(id);
expect(t.lane).toBe(LANE_A);
- expect(t.runLimitMs).toBe(5 * MIN);
+ // No measured run in its lane yet: the lane's run ceiling (45 minutes unless the owner sets another).
+ expect(t.runLimitMs).toBe(45 * MIN);
const sent = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify({ event: "sent", promptId: t.promptId }) }), {
params: Promise.resolve({ id }),
});