Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Queue: people take turns, each with their fastest run

Adarsh7635b3c0d33b
diff --git a/docs/billing-hook.md b/docs/billing-hook.md
index a563c81d..0184bf0c 100644
--- a/docs/billing-hook.md
+++ b/docs/billing-hook.md
@@ -246,7 +246,7 @@ answers again.
| 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 }, timing?: { runMs, pausedMs, heldMs? } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, class?, text, startAt? }` 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 }, timing?: { runMs, pausedMs, heldMs? } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, class?, priority?, text, startAt? }` or `{ ok: false, code: RefuseCode \| "price-changed", text, quote?, action?, offer? }` |
| `POST /v1/release` | `{ holdId, reason: "not-created" }` or `{ requestId, 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 }` |
@@ -295,9 +295,12 @@ with the time to send its files and results. `pausedMs` is the time a started ru
`pausedBudgetS`, two hours unless the owner sets another). A service sets the deadline to at least now + `maxWaitMs` +
`runMs` + `pausedMs`. A run past it still delivers its result. A service that doesn't read `timing` keeps its own rule.
-`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.
+`class` is the run's class: `"paid"` or `"free"` (no `class`: `"free"`). People's runs of both classes take turns in
+one line, and the install's own jobs come after them. `priority` is the run's priority within its class: a whole number
+from 0 (none, the same as no `priority`) to 9, higher first in each round of the line (a value out of range is read as
+the nearest one, anything else as 0). `boostMs` is a head start, at most a day: where two people's turns would tie, the
+run counts as having come that much earlier. All three are kept for every row of the run, and a browser never sees them.
+The order of the line is in [gpu-workers.md](gpu-workers.md).
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.
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 6fedf13f..eb15bbe4 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -470,20 +470,38 @@ A worker gets a job only when all of these are true, all in one SQLite transacti
- it verified every run-time file the job loads (see "Run-time files" below);
- the retry rule allows it: a worker that lost or failed the job gets it again only when no other worker that can run
the job was heard from in the last 10 minutes;
+- a job whose attempt failed waits for the line to be free (below);
- near the end of its hours, the job's estimate fits before the window closes;
- 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;
- no free worker with a higher pick order would take the job next, for the first-pick grace (see "Who picks first"
below).
-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 one of the owner's own jobs in its
-warm lane (the models it has loaded) ahead of the owner's best job, while that job has waited less than the pick
-allowance (or the worker's own `switch_after_ms`, if that is lower). A warm lane never makes a person wait: while a
-person's run waits that the worker can take, its next claim takes the best of them, whatever lane it has loaded. 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.
+People's runs (an account's, a guest's, the owner's hands-on run) go before the owner's own jobs, in this order
+(`smartLine` in `src/server/computer/pool.ts`):
+
+1. A run that has waited 20 minutes or longer goes to the front, the oldest first. No run waits forever behind quicker
+ ones.
+2. The others go in rounds. Each person with a run waiting has one turn in each round, and the turn takes that
+ person's quickest run for the worker that asks (the lane's bench on that worker, else the lane's typical run, else
+ a guess from the job's size). In each round, people watching their runs go first (a page of theirs asked about
+ their runs in the last minute: the runs list, a run, or its live picture, which an open page asks for while a run
+ waits or works), then by the run's `priority` from the billing service (higher first), then people with no finished
+ run on the GPUs yet, then everyone else. At each level, the person who has waited longest goes first. A person's
+ turns count the runs a worker holds for them now, those a worker finished for them since the oldest run still
+ waiting came, and their runs in step 1.
+3. A run whose attempt failed (it stalled, or ran past its run limit) goes to the back. It has its last try only when
+ no other person's run waits that a worker on now could take; if that try fails too, the run fails. A worker that
+ went silent, a ComfyUI that went down or lost the job, or a job given back for memory or a busy PC is a recovery:
+ the run keeps its place, and the third lost attempt fails it.
+
+A worker takes the first job in that order that it can run, with one exception: a job that only it can make (no other
+worker on now could run it) goes first, so a big GPU doesn't take what a smaller one could while a job only it can
+make waits. The owner's own jobs go in the order they came. With the pick allowance at 0 (the default), that is the
+whole rule. Above 0, a worker may take one of the owner's own jobs in its warm lane (the models it has loaded) ahead
+of the owner's best job, while that job has waited less than the pick allowance (or the worker's own
+`switch_after_ms`, if that is lower). A warm lane never makes a person wait: while a person's run waits that the
+worker can take, its next claim takes the best of them, whatever lane it has loaded.
**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:
@@ -492,7 +510,7 @@ in that class came.
|---|---|---|
| `runCeilingS` | `{ default, lanes }`: the longest one attempt at a job may run, in seconds, with a value per lane that overrides the default. A worker's run limit is never longer, and the run's own clock is set from it (below) | `{ "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` |
+| `fairShare` | Kept as saved; people always take turns (above), whatever it says | `false` |
| `pickAllowanceMs` | How long a job in a worker's warm lane may go ahead of an older one (above). 0: strict order | `0` |
| `firstPickGraceMs` | How long a job may be left for a free worker with a higher pick order before another worker takes it (see "Who picks first" below). 0: no job is left for anyone | `20000` (20 seconds) |
| `pausedBudgetS` | How long, in all, a run that has started may spend back in line while its worker steps aside, and still be inside the deadline its hold asks for ([billing-hook.md](billing-hook.md)). A run past it still delivers its result | `7200` (2 hours) |
@@ -589,10 +607,10 @@ or hidden: it keeps its place in line and starts after the hold ends.
| Mode | Order on the workers | Local work on the worker's PC |
| --- | --- | --- |
-| `people-first` (the default) | paid runs, free runs, then the owner's own jobs | makes room for people's runs (studio jobs first) |
+| `people-first` (the default) | people's runs (in the order above), then the owner's own jobs | makes room for people's runs (studio jobs first) |
| `people-only` | people's runs only; the owner's own jobs wait | starts nothing new |
-| `ours-first` | the owner's own jobs, then paid runs, then free runs | keeps the GPU while it runs; people's runs start when it is idle |
-| `balanced` | paid runs, then free runs and the owner's own jobs together, by when they came | makes room for people's runs |
+| `ours-first` | the owner's own jobs, then people's runs | keeps the GPU while it runs; people's runs start when it is idle |
+| `balanced` | people's runs and the owner's own jobs together: the owner takes turns as one more person | makes room for people's runs |
A mode lasts 1 minute to a week (`forMin`), or until the owner switches it back. A mode past its end is gone at the next
beat, and the admin log gets a `queue.mode.end` row (actor `system`). In `ours-first`, the beat's `claimableNow` counts
@@ -608,8 +626,8 @@ override.
to a week. "Hold" keeps them in place until the hold ends. A run's own override wins over its person's override. The
queue view names a person by a key (`p-` and 12 hex digits), never by an account id.
-The order in one look at the line: runs sent next, then boosted people's runs, then the mode's classes, each group in
-its own order (fair share included). A person's place in line (`placeInLine`, the billing service's line facts) reads
+The order in one look at the line: runs sent next, then boosted people's runs, then the mode's groups, each in its
+own order (the rounds above). A person's place in line (`placeInLine`, the billing service's line facts) reads
the same order, with the pool's mode.
**The turns folder.** A worker with a turns folder writes the mode from each beat answer (`worker.queue`) to
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 017c7084..ecc89248 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -22,8 +22,9 @@ import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, notePr
import { queueSettings, runCeilingMs } from "../queue-settings";
import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
import { modelLabel } from "./queue-live";
-import { effectiveMode, workerModeOf, LOCAL_WORK, lineControls, liveOverrides, modeClass, modeClassSql, overrideTargets, plainLine, poolMode, sweepControls, taskControl, DEFAULT_MODE, type EffectiveMode, type LineControls, type QueueMode, type TaskControl } from "./queue-controls";
+import { effectiveMode, workerModeOf, LOCAL_WORK, lineControls, liveOverrides, modeClassSql, overrideTargets, plainLine, poolMode, sweepControls, taskControl, DEFAULT_MODE, type EffectiveMode, type LineControls, type QueueMode, type TaskControl } from "./queue-controls";
import type { LocalWork, WorkerGpuStats, WorkerStats } from "@/lib/relay";
+import { watchingNow } from "./watching";
import { cleanLogLines, lastEventOf, lastOfKind, logWorkerEvent, logWorkerEvents, setEventNames, type NewWorkerEvent, type WorkerEventKind } from "./worker-events";
/**
@@ -101,14 +102,16 @@ export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.c
* room on a worker's PC as a person's run does. The owner's scripts' runs (a batch, a drill…) stay the owner's class.
*/
export const ownerHandsOn = (t: Pick<TaskRow, "class" | "account">): boolean => !t.account && classRank(t) !== OWNER_CLASS;
+/** People's runs (0: an account's, a guest's, the owner's hands-on run) or the owner's own jobs (2), as SQL (classRank). */
+const PEOPLE_OR_OWNER = `(CASE WHEN ${CLASS_RANK} = ${OWNER_CLASS} THEN ${OWNER_CLASS} ELSE 0 END)`;
/**
- * 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).
+ * The window of waiting tasks one look at the line reads, in SQL: people's runs before the owner's own jobs, then by
+ * rank (a requeued task keeps its own, so it keeps its place), then by when each was made. The order workers serve them
+ * in is worked out from that window in code (smartLine), and the claim and the place in line read the same order.
*/
-const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;
+const LINE_ORDER = `${PEOPLE_OR_OWNER}, rank_at, created_at, id`;
/** The columns the line's counts read (never a task's graph or files). */
-const LINE_COLS = "id, generation_id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json, slot, finish_json";
+const LINE_COLS = "id, generation_id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json, slot, finish_json, priority, failed_once";
/**
* A task a worker took that is still sending its files to its ComfyUI this long after the claim (or after its ComfyUI lost
* it and it began sending them again on the same claim) goes back in line.
@@ -661,7 +664,8 @@ export function ownerWaitingNow(w: WorkerRow, now = Date.now()): number {
/** The first job in line this worker may claim right now (people's before the owner's), or null: what a worker that holds back the line would take first. */
export function firstClaimableNow(w: WorkerRow, now = Date.now()): TaskRow | null {
- return gpuClaimableRows(w, now, "people")[0] ?? gpuClaimableRows(w, now, "owner")[0] ?? null;
+ const first = (rows: TaskRow[]) => (rows.length > 1 ? lineOrder(rows, controlsOf(w, now).mode, { now, worker: w, workers: [w] })[0] : rows[0]);
+ return first(gpuClaimableRows(w, now, "people")) ?? first(gpuClaimableRows(w, now, "owner")) ?? null;
}
function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): number {
@@ -701,8 +705,8 @@ function controlsOf(w: Pick<WorkerRow, "pool" | "mode_json"> | string, now: numb
return lineControls((typeof w === "string" ? poolMode(w, now) : effectiveMode(w, now)).mode, liveOverrides(now));
}
-/** The line's order in SQL under a mode: the mode's class, then rank, when it came and id (LINE_ORDER for people first). */
-const lineOrderSql = (mode: QueueMode) => (mode === DEFAULT_MODE ? LINE_ORDER : `${modeClassSql(CLASS_RANK, mode)}, rank_at, created_at, id`);
+/** The window's order in SQL under a mode: the mode's group, then rank, when it came and id (LINE_ORDER for people first). */
+const lineOrderSql = (mode: QueueMode) => (mode === DEFAULT_MODE ? LINE_ORDER : `${modeClassSql(PEOPLE_OR_OWNER, mode)}, rank_at, created_at, id`);
/**
* The waiting rows one look at the line reads: the first `limit` in the mode's order and, wherever they stand, the rows
@@ -721,14 +725,15 @@ function lineRows(cols: string, where: string, args: unknown[], c: LineControls,
}
/**
- * Waiting tasks in the order a worker (`workerId`; null: the line as a whole) serves them under the owner's controls:
- * the mode's order (lineOrder), then runs sent next first, then boosted people's runs, each group keeping its order.
- * The ones it doesn't take now (held, pinned to another worker, the owner's own in People only) are left out, except
- * `keep` (the task whose own place is asked).
+ * Waiting tasks in the order a worker (`look.worker`; null: the line as a whole) serves them under the owner's
+ * controls: the mode's order (smartLine), then runs sent next first, then boosted people's runs, each group keeping
+ * its order. The ones it doesn't take now (held, pinned to another worker, the owner's own in People only) are left
+ * out, except `keep` (the task whose own place is asked).
*/
-function controlledOrder(rows: TaskRow[], fairShare: boolean, c: LineControls, workerId: string | null, keep?: string): TaskRow[] {
- const ordered = lineOrder(rows, fairShare, c.mode);
+function controlledOrder(rows: TaskRow[], c: LineControls, look: LineLook, keep?: string): TaskRow[] {
+ const ordered = lineOrder(rows, c.mode, look);
if (plainLine(c)) return ordered;
+ const workerId = look.worker?.id ?? null;
const tiers = new Map<string, number>();
const kept = ordered.filter((t) => {
const tc = taskControl(t, classRank(t), c, workerId);
@@ -879,7 +884,9 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), s
// worker could take now is still its own (marked streamed, so the fallback after running out of memory applies).
const asking = noStream ? withoutStreaming(fresh) : fresh;
const wholeHere = (x: TaskRow) => fitsSlot(x, asking, now, slot);
- let { task: t, looked } = pick(fresh, now, slot, leave);
+ const first = pick(fresh, now, slot, leave);
+ const looked = first.looked;
+ let t = first.task;
if (noStream && t && !wholeHere(t)) {
const taken = streamTakers(fresh, now, leave);
if (taken.has(t.id)) t = pick(fresh, now, slot, leave, (x) => wholeHere(x) || !taken.has(x.id)).task;
@@ -1232,12 +1239,13 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
}
/**
- * The best task this worker may run, in the line's order (lineOrder). People's runs always come first, and a warm lane
- * 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); `also`: one more test a task must pass (a
- * claim with `noStream`: workerClaim).
+ * The best task this worker may run, in the line's order for it (smartLine, with its own estimates). People's runs
+ * always come first, and a warm lane never makes a person wait: while any person's run waits that this worker can take,
+ * it takes the best of them. Best GPU for the job: a run only this worker can make now goes before the others (onlyHere), so a big GPU doesn't take
+ * what a smaller one could while a run only it can make waits. 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); `also`: one more test a task must pass (a claim with `noStream`: workerClaim).
*/
function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu", leave?: ReadonlySet<string>, also?: (t: TaskRow) => boolean): { task: TaskRow | null; looked: number } {
const settings = queueSettings(now);
@@ -1246,8 +1254,12 @@ function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu", leave?: Reado
// 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) => !leave?.has(t.id) && fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now) && (!also || also(t)));
+ const ok = controlledOrder(rows, c, { now, worker: w, workers: [w] }).filter(
+ (t) => !leave?.has(t.id) && fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now) && (!also || also(t)),
+ );
if (!ok.length) return { task: null, looked };
+ const only = slot === "gpu" ? onlyHere(w, ok, c, now) : null;
+ if (only) return { task: only, looked };
const best = ok[0];
const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
// A run the owner sent next, or a boosted person's, never waits for a warm lane either.
@@ -1317,58 +1329,211 @@ function firstPicks(w: WorkerRow, now: number): Map<string, string> {
return out;
}
+// ---------------------------------------------------------------------------
+// The smart order: people take turns, in rounds
+
+/** A person's run that has waited this long or longer goes to the front of the line, the oldest first. */
+export const AGED_MS = 20 * 60_000;
+
/**
- * 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.
+ * Why a waiting task stands where it does in the line (the owner's Queue page reads ORDER_WORDS): it waited 20 minutes
+ * ("aged"), its person is watching it, has a priority, or has no finished run yet ("first-run"), it is its person's
+ * fastest in their turn ("turn"), it failed once and waits for its last try ("second-try"), only one GPU on now can make
+ * it ("only-gpu"), or it is the owner's own job ("owner").
*/
-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;
+export type OrderWhy = "aged" | "watching" | "priority" | "first-run" | "turn" | "second-try" | "only-gpu" | "owner";
+
+/** The owner's words for why a run stands where it does (never shown to a visitor). */
+export const ORDER_WORDS: Record<Exclude<OrderWhy, "owner">, string> = {
+ watching: "Watching",
+ priority: "Plan priority",
+ "first-run": "First run",
+ turn: "Fastest of theirs",
+ aged: "Waited 20 min",
+ "second-try": "Second try when the line is free",
+ "only-gpu": "Only this GPU can make it",
+};
+
+/**
+ * One look at the line: when, the worker that asks (null: the line as a whole, for a place in line and the owner's
+ * view), and the pool's workers (a task's estimate on the line as a whole is its lane's bench on the quickest of them).
+ */
+export interface LineLook {
+ now: number;
+ worker: WorkerRow | null;
+ workers: readonly WorkerRow[];
+}
+
+/**
+ * The group a task is served in under a mode, lower first: people's runs (an account's, a guest's, the owner's
+ * hands-on run), then the owner's own jobs. Our work first turns the two round; Balanced puts them in one group, where
+ * the owner takes turns as one more person; People only leaves the owner's own jobs out (queue-controls.ts).
+ */
+function groupOf(t: Pick<TaskRow, "class" | "account">, mode: QueueMode): number {
+ const owner = classRank(t) === OWNER_CLASS;
+ if (mode === "balanced") return 0;
+ if (mode === "ours-first") return owner ? 0 : 1;
+ return owner ? (mode === "people-only" ? 2 : 1) : 0;
+}
+
+/** Whose turn a task takes: its account's (all guests share one), or the owner's. */
+const personOf = (t: Pick<TaskRow, "account" | "principal">) => t.account ?? t.principal;
+
+/** Two tasks in the order they came: by their place (rank: a requeued task keeps its own), then when each came, then id. */
+const cameOrder = (a: TaskRow, b: TaskRow) => (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);
+
+/** A rough time for a job from its size alone (more pictures, more pixels, more seconds take longer). */
+function sizeGuessMs(t: Pick<TaskRow, "needs_json">): number {
+ const s = json<Needs | null>(t.needs_json, null)?.size;
+ const mp = Math.max(0.25, s?.megapixels || 1);
+ const n = Math.max(1, s?.outputs || 1);
+ return Math.round((s?.seconds ? s.seconds * 20_000 : 8_000) * mp * n);
+}
+
+/**
+ * How long each task should take, for its person's turn: its lane's bench on the worker that asks (on the line as a
+ * whole: on the quickest of the pool's workers), its own estimate, its lane's typical run, else a guess from its size.
+ * Ties go to the smaller job (sizeGuessMs).
+ */
+function estimates(look: LineLook): (t: TaskRow) => number {
+ const typical = memo(typicalPoolMs);
+ const kept = new Map<string, number>();
+ const on = look.worker ? [look.worker] : look.workers;
+ return (t) => {
+ let ms = kept.get(t.id);
+ if (ms === undefined) {
+ const bench = on.map((w) => (t.lane && benchOf(w as WorkerRow)[t.lane]?.medianMs) || 0).filter((x) => x > 0);
+ ms = (bench.length ? Math.min(...bench) : 0) || t.est_ms || (t.lane ? typical(t.lane) : null) || sizeGuessMs(t);
+ kept.set(t.id, ms);
+ }
+ return ms;
+ };
+}
+
+/**
+ * Turns people already had in this round of the line, by person: runs a worker holds for them now, and runs a worker
+ * took and finished for them since `since` (when the oldest run still waiting came), up to `now`. GPU jobs only; the
+ * owner's own jobs only with `owner` (Balanced).
+ */
+function servedTurns(since: number, now: number, owner: boolean): Map<string, number> {
+ const rows = db()
+ .prepare(
+ `SELECT COALESCE(account, principal) AS k, COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND slot IS NULL AND finish_json IS NULL
+ ${owner ? "" : `AND ${CLASS_RANK} <> ${OWNER_CLASS}`}
+ AND (state IN ('sending','queued','running','collecting') OR (state IN ('done','failed') AND claimed_at IS NOT NULL AND finished_at > ? AND finished_at <= ?))
+ GROUP BY k`,
+ )
+ .all(since, now) as { k: string; n: number }[];
+ return new Map(rows.map((r) => [r.k, r.n]));
}
-/** 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}`;
+/** Of these accounts, the ones with a finished run on this install's GPUs (one that ended done). */
+function finishedOnce(accounts: string[]): Set<string> {
+ if (!accounts.length) return new Set();
+ const principals = JSON.stringify(accounts.map((a) => `acct:${a}`));
+ const rows = db()
+ .prepare(
+ `SELECT principal FROM worker_jobs WHERE event = 'done' AND principal IN (SELECT value FROM json_each(?))
+ UNION SELECT principal FROM relay_tasks WHERE pools IS NOT NULL AND state = 'done' AND principal IN (SELECT value FROM json_each(?))`,
+ )
+ .all(principals, principals) as { principal: string }[];
+ return new Set(rows.map((r) => r.principal.slice(5)));
+}
/**
- * Two tasks of one class in the line's order (LINE_ORDER after the class, in code): by rank, then when each came, then
- * id. The class comes first, in the order of the mode (lineOrder).
+ * The line in the order workers serve it, with why each task stands there (pure but for what it reads of the people:
+ * who is watching, who has a finished run, the turns they had). By group (groupOf), and in a group of people's runs:
+ *
+ * 1. Runs that waited AGED_MS or longer, the oldest first, so no run is ever starved by quicker ones.
+ * 2. Rounds over people: each person with a run waiting has one turn in each round, and their turn takes their fastest
+ * run (estimates: on the worker that asks). In a round, a person watching their runs goes first, then by priority
+ * (higher first), then a person with no finished run yet, then everyone else, and at each level the person who has
+ * waited longest (their run that has stood in line longest). A person's turns already taken count: the runs a worker
+ * holds for them now, those it finished since the oldest run still waiting came, and their runs in step 1.
+ * 3. Runs that failed once, in the order they came.
+ *
+ * The owner's own jobs (a group of their own, unless Balanced) go in the order they came, failed once last.
*/
-const sameClassOrder = (a: TaskRow, b: TaskRow) => (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);
+export function smartLine(rows: readonly TaskRow[], mode: QueueMode, look: LineLook): { task: TaskRow; why: OrderWhy }[] {
+ const groups = new Map<number, TaskRow[]>();
+ for (const t of rows) {
+ const g = groupOf(t, mode);
+ groups.set(g, [...(groups.get(g) ?? []), t]);
+ }
+ const out: { task: TaskRow; why: OrderWhy }[] = [];
+ for (const g of [...groups.keys()].sort((a, b) => a - b)) {
+ const list = groups.get(g)!;
+ const people = mode === "balanced" || list.some((t) => classRank(t) !== OWNER_CLASS);
+ if (!people) {
+ out.push(...list.filter((t) => !t.failed_once).sort(cameOrder).map((task) => ({ task, why: "owner" as const })));
+ out.push(...list.filter((t) => !!t.failed_once).sort(cameOrder).map((task) => ({ task, why: "second-try" as const })));
+ continue;
+ }
+ out.push(...rounds(list, mode === "balanced", look));
+ }
+ return out;
+}
+
+/** A group of people's runs in its order (smartLine). */
+function rounds(list: TaskRow[], owner: boolean, look: LineLook): { task: TaskRow; why: OrderWhy }[] {
+ const { now } = look;
+ const failed = list.filter((t) => !!t.failed_once).sort(cameOrder);
+ const live = list.filter((t) => !t.failed_once);
+ const aged = live.filter((t) => now - t.created_at >= AGED_MS).sort((a, b) => a.created_at - b.created_at || cameOrder(a, b));
+ const rest = live.filter((t) => now - t.created_at < AGED_MS);
+ const byPerson = new Map<string, TaskRow[]>();
+ for (const t of rest) byPerson.set(personOf(t), [...(byPerson.get(personOf(t)) ?? []), t]);
+ const turnsOut: { task: TaskRow; why: OrderWhy }[] = [];
+ if (byPerson.size) {
+ const est = estimates(look);
+ const watching = watchingNow(now);
+ const accounts = [...new Set(rest.map((t) => t.account).filter((a): a is string => !!a && !a.startsWith("guest")))];
+ const finished = finishedOnce(accounts);
+ const served = servedTurns(Math.min(...live.map((t) => t.created_at)), now, owner);
+ const agedTurns = new Map<string, number>();
+ for (const t of aged) agedTurns.set(personOf(t), (agedTurns.get(personOf(t)) ?? 0) + 1);
+ const keyed: { task: TaskRow; round: number; watch: number; prio: number; first: number; waited: number; who: string; why: OrderWhy }[] = [];
+ for (const [who, runs] of byPerson) {
+ runs.sort((a, b) => est(a) - est(b) || sizeGuessMs(a) - sizeGuessMs(b) || cameOrder(a, b));
+ const account = runs[0].account;
+ const watch = !!account && watching.has(account);
+ const prio = Math.max(...runs.map((t) => cleanPriority(t.priority)));
+ const first = !!account && !account.startsWith("guest") && !finished.has(account);
+ const why: OrderWhy = watch ? "watching" : prio > 0 ? "priority" : first ? "first-run" : "turn";
+ const waited = Math.min(...runs.map((t) => t.rank_at ?? t.created_at));
+ const had = (served.get(who) ?? 0) + (agedTurns.get(who) ?? 0);
+ runs.forEach((task, i) => keyed.push({ task, round: had + i, watch: watch ? 0 : 1, prio, first: first ? 0 : 1, waited, who, why }));
+ }
+ keyed.sort((a, b) => a.round - b.round || a.watch - b.watch || b.prio - a.prio || a.first - b.first || a.waited - b.waited || (a.who < b.who ? -1 : a.who > b.who ? 1 : 0));
+ turnsOut.push(...keyed.map((k) => ({ task: k.task, why: k.why })));
+ }
+ return [...aged.map((task) => ({ task, why: "aged" as const })), ...turnsOut, ...failed.map((task) => ({ task, why: "second-try" as const }))];
+}
+
+/** The waiting tasks in the order workers serve them (smartLine), without the reasons. */
+export function lineOrder(rows: readonly TaskRow[], mode: QueueMode = DEFAULT_MODE, look: Partial<LineLook> = {}): TaskRow[] {
+ return smartLine(rows, mode, { now: look.now ?? Date.now(), worker: look.worker ?? null, workers: look.workers ?? poolWorkers() }).map((x) => x.task);
+}
/**
- * 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.
+ * The first of these tasks (a worker's line, in its order) that only this worker can make now: no other worker of its
+ * pool that is on now (eligible) could run it, its delays aside. Only in the same tier of the owner's controls and the
+ * same group of the line as the first task, and never a second try. Null: none, or it is the first task already.
*/
-export function lineOrder(rows: TaskRow[], fairShare: boolean, mode: QueueMode = DEFAULT_MODE): TaskRow[] {
- // The class in the mode's order (people first: paid, free, the owner's own).
- const cls = (t: TaskRow) => modeClass(classRank(t), mode);
- const strict = (a: TaskRow, b: TaskRow) => cls(a) - cls(b) || sameClassOrder(a, b);
- if (rows.length < 2) return rows;
- if (!fairShare) return [...rows].sort(strict);
- const held = servedTurns(rows);
- const seen = new Map<string, number>();
- const turns = new Map<string, number>();
- for (const r of [...rows].sort(strict)) {
- const k = turnKey(r);
- const n = seen.get(k) ?? 0;
- seen.set(k, n + 1);
- turns.set(r.id, (held.get(k) ?? 0) + n);
+function onlyHere(w: WorkerRow, ok: readonly TaskRow[], c: LineControls, now: number): TaskRow | null {
+ const best = ok[0];
+ if (!best) return null;
+ const others = poolWorkers().filter((x) => x.id !== w.id && x.pool === w.pool && eligible(x, now));
+ if (!others.length) return null;
+ const tier = (t: TaskRow) => (plainLine(c) ? 2 : taskControl(t, classRank(t), c, w.id).tier);
+ const bestTier = tier(best);
+ const bestGroup = groupOf(best, c.mode);
+ for (const t of ok) {
+ if (tier(t) !== bestTier || groupOf(t, c.mode) !== bestGroup) break;
+ if (t.failed_once) continue;
+ if (!others.some((x) => fitsSlot({ ...t, created_at: 0 }, x, now, slotFor(t, x)))) return t.id === best.id ? null : t;
}
- return [...rows].sort((a, b) => cls(a) - cls(b) || turns.get(a.id)! - turns.get(b.id)! || strict(a, b));
+ return null;
}
// ---------------------------------------------------------------------------
@@ -1753,30 +1918,15 @@ export function placeInLine(t: TaskRow, now = Date.now()): LinePlace {
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. */
+/**
+ * The waiting tasks served before this one (at most LOOK_AHEAD looked at), in the order of the line as a whole
+ * (smartLine, with each task's estimate on the quickest worker) under the owner's controls (the pool's mode, runs or
+ * people sent first or held): those held are left out (they take no turn before it).
+ */
function lineBefore(t: TaskRow, now: number): TaskRow[] {
- const d = db();
- const rank = t.rank_at ?? t.created_at;
- const cls = classRank(t);
- // The owner's controls (the pool's mode, runs or people sent first or held): the line as the pool's workers serve it,
- // with those that wait held left out (they take no turn before it).
const c = controlsOf((t.pools ?? "pool").split(",")[0] || "pool", now);
- if (!plainLine(c)) {
- const rows = lineRows(LINE_COLS, "pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?", [t.id], c, LOOK_AHEAD);
- const line = controlledOrder([...rows, t], queueSettings(now).fairShare, c, null, t.id);
- return line.slice(0, line.findIndex((x) => x.id === t.id));
- }
- 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);
+ const rows = lineRows(LINE_COLS, "pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?", [t.id], c, LOOK_AHEAD);
+ const line = controlledOrder([...rows, t], c, { now, worker: null, workers: poolWorkers() }, t.id);
return line.slice(0, line.findIndex((x) => x.id === t.id));
}
@@ -2680,18 +2830,26 @@ export const lanesCatalog = () => catalogLanes().lanes.map((l) => ({ lane: l.lan
/**
* The waiting line of a pool as the owner's Queue page shows it (GET /api/admin/queue): in the order its workers serve
- * it under the owner's controls (the pool's mode, runs and people sent first), each with its place (`rank`, 1 first)
- * and what the controls say of it. The tasks no worker takes now (held, the owner's own in People only) follow, with no
- * place. At most `limit` tasks are looked at.
+ * it under the owner's controls (the pool's mode, runs and people sent first), each with its place (`rank`, 1 first),
+ * what the controls say of it, and why the line puts it there (`order`: smartLine). The tasks no worker takes now (held,
+ * the owner's own in People only) follow, with no place. At most `limit` tasks are looked at.
*/
-export function controlledLine(pool = "pool", now = Date.now(), limit = LOOK_AHEAD): { mode: QueueMode; items: { task: TaskRow; rank: number | null; base: number; control: TaskControl }[] } {
+export function controlledLine(
+ pool = "pool",
+ now = Date.now(),
+ limit = LOOK_AHEAD,
+): { mode: QueueMode; items: { task: TaskRow; rank: number | null; base: number; control: TaskControl; order: OrderWhy }[] } {
const c = controlsOf(pool, now);
const rows = lineRows("*", "pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0", [`,${pool},`], c, limit);
- const all = lineOrder(rows, queueSettings(now).fairShare, c.mode).map((task, i) => ({ task, i, base: classRank(task), control: taskControl(task, classRank(task), c, null) }));
+ const all = smartLine(rows, c.mode, { now, worker: null, workers: poolWorkers().filter((w) => w.pool === pool) }).map(({ task, why }, i) => ({
+ task,
+ i,
+ base: classRank(task),
+ control: taskControl(task, classRank(task), c, null),
+ order: why,
+ }));
const served = all.filter((x) => !x.control.out).sort((a, b) => a.control.tier - b.control.tier || a.i - b.i);
const out = all.filter((x) => x.control.out);
- return {
- mode: c.mode,
- items: [...served.map((x, k) => ({ task: x.task, rank: k + 1, base: x.base, control: x.control })), ...out.map((x) => ({ task: x.task, rank: null, base: x.base, control: x.control }))],
- };
+ const item = (x: (typeof all)[number], rank: number | null) => ({ task: x.task, rank, base: x.base, control: x.control, order: x.order });
+ return { mode: c.mode, items: [...served.map((x, k) => item(x, k + 1)), ...out.map((x) => item(x, null))] };
}
diff --git a/src/server/computer/queue-controls.ts b/src/server/computer/queue-controls.ts
index fbd6e031..da204337 100644
--- a/src/server/computer/queue-controls.ts
+++ b/src/server/computer/queue-controls.ts
@@ -16,8 +16,8 @@ import type { WorkerRow } from "./workers";
* - "people-only": workers take only people's runs; the owner's own jobs wait, and local work on the PC pauses.
* - "ours-first": the owner's own jobs before people's runs, and local work on the PC keeps the GPU (people's runs
* wait in line, in their order, and start when a GPU is free).
- * - "balanced": people's free runs and the owner's own jobs in one line by when they came (paid runs first); local
- * work makes room for people's runs as in people-first.
+ * - "balanced": people's runs and the owner's own jobs in one line, where the owner takes turns as one more person
+ * (pool.ts smartLine); local work makes room for people's runs as in people-first.
* - A run: "next" (to the front of every worker's line, or of one worker's: `worker`), or "hold" (it keeps its place
* and no worker takes it until the hold ends).
* - A person (an account, or the guests' key): "boost" (their runs go first, for a while), or "hold".
@@ -539,8 +539,8 @@ export function controlWords(tc: TaskControl, base: number, mode: QueueMode, wor
// A run sent next asks local work on a worker's PC to make room, as a person's run does (pool.ts gpuClaimableRows).
if (tc.tier === 0) return `${o?.workerId ? `Run next on ${workerName(o.workerId) ?? "its worker"}` : "Run next"}: starts as soon as the GPU is free and local work makes room`;
if (tc.tier === 1) return "Boosted: this person's runs first";
- if (own && base !== 2) return mode === "ours-first" ? "Your run: after our work (Our work first)" : mode === "balanced" ? "Your run: by when it came (Balanced)" : "Your run";
+ if (own && base !== 2) return mode === "ours-first" ? "Your run: after our work (Our work first)" : mode === "balanced" ? "Your run: taking turns (Balanced)" : "Your run";
if (mode === "ours-first") return base === 2 ? "Our work first" : "After our work (Our work first)";
- if (mode === "balanced") return base === 0 ? "Paid run" : "Balanced: by when it came";
+ if (mode === "balanced") return base === 2 ? "Balanced: our work takes turns" : "Balanced: taking turns";
return base === 0 ? "Paid run" : base === 1 ? "People first" : "Our work: after people's runs";
}
diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.ts
index 73c05938..2468a039 100644
--- a/src/server/computer/queue-live.ts
+++ b/src/server/computer/queue-live.ts
@@ -6,7 +6,7 @@ import { laneLabel } from "@/lib/lanes";
import { HOLDING_OTHER, HOLDING_WHY, SENT_STATES, type WorkerHolding } from "@/lib/relay";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
-import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ownerHandsOn, ownerWaitingNow, runFit, workerState, type RunFit } from "./pool";
+import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ORDER_WORDS, ownerHandsOn, ownerWaitingNow, runFit, workerState, type OrderWhy, type RunFit } from "./pool";
import { controlWords, effectiveMode, liveOverrides, MODE_WORDS, overrideView, personKey, poolMode, poolModes, recentOverrides, sweepControls, workerModeOf, type EffectiveMode, type OverrideView, type QueueMode } from "./queue-controls";
import type { LocalWork } from "@/lib/relay";
import { json, taskCold, taskProgress, type TaskRow, jobNowOf, type JobNow } from "./tasks";
@@ -64,8 +64,14 @@ export interface QueuedJob {
inLineAt: number;
/** Its place in the line its pool's workers serve (1: next); null while no worker takes it (held, People only). */
rank: number | null;
- /** Why it stands there, in words ("People first", "Run next", "Held by the owner"). */
+ /**
+ * Why it stands there, in words: the owner's controls ("Run next", "Held by the owner"), else the line's own reason
+ * (pool.ts ORDER_WORDS: "Watching", "Plan priority", "First run", "Fastest of theirs", "Waited 20 min", "Second try
+ * when the line is free", "Only this GPU can make it"), else its class ("Our work: after people's runs").
+ */
why: string;
+ /** Why the line puts it there (pool.ts smartLine), whatever the controls say. */
+ order: OrderWhy;
/** What decides it: the class's order ("class"), a run sent next ("next"), a boosted person ("boost"), or why no worker takes it now. */
code: "class" | "next" | "boost" | "held" | "pinned" | "paused";
/** The owner's override that decides it (null: none), with until when. */
@@ -141,6 +147,9 @@ export interface TextLine {
oldestAt: number | null;
}
+/** The reasons of a person's run in its turn of the line (pool.ts smartLine): only one GPU making it says more. */
+const TURN_WHYS = new Set<OrderWhy>(["watching", "priority", "first-run", "turn"]);
+
/** At most this many next steps are listed (oldest first); `nextTotal` counts them all. */
export const NEXT_LIMIT = 50;
/** At most this many jobs waiting in line are listed (the oldest first); `lanes` counts them all. */
@@ -229,9 +238,19 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
const nameOf = (id: string) => byId.get(id)?.name ?? null;
// Each worker's state, read once for the fit of every job listed.
const stateOf = workers.map((w) => ({ w, state: workerState(w, now) }));
- const queued: QueuedJob[] = ordered.slice(0, QUEUED_LIMIT).map(({ task: t, rank, base, control, mode }) => {
+ const queued: QueuedJob[] = ordered.slice(0, QUEUED_LIMIT).map(({ task: t, rank, base, control, mode, order: lineWhy }) => {
const g = genOf(t.generation_id);
const o = control.by;
+ const fit = runFit(t, stateOf, now);
+ // A person's run in its turn that only one of the workers taking jobs now can make, while more than one is: that
+ // worker takes it first (pool.ts onlyHere).
+ const on = fit.workers.filter((x) => x.state === "idle" || x.state === "busy");
+ const order: OrderWhy = TURN_WHYS.has(lineWhy) && on.length > 1 && on.filter((x) => x.can).length === 1 ? "only-gpu" : lineWhy;
+ const words = controlWords(control, base, mode, nameOf, ownerHandsOn(t));
+ // No override decides it: the line's own reason (the mode's words too, where the mode puts our work first or with
+ // people's runs, and for the owner's hands-on run).
+ const plain = (mode === "people-first" || mode === "people-only") && !ownerHandsOn(t);
+ const why = control.out || control.tier < 2 || order === "owner" ? words : plain ? ORDER_WORDS[order] : `${words} · ${ORDER_WORDS[order]}`;
return {
task: t.id,
generationId: t.generation_id,
@@ -243,13 +262,14 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
createdAt: g?.created_at ?? null,
inLineAt: t.rank_at ?? t.created_at,
rank,
- why: controlWords(control, base, mode, nameOf, ownerHandsOn(t)),
+ why,
+ order,
code: control.out ?? (control.tier === 0 ? "next" : control.tier === 1 ? "boost" : "class"),
override: o ? { id: o.id, until: o.until, by: o.by, at: o.at, workerId: o.workerId } : null,
person: t.account ? personKey(t.account) : null,
guest: !!t.account?.startsWith("guest"),
...(ownerHandsOn(t) && { handsOn: true as const }),
- fit: runFit(t, stateOf, now),
+ fit,
};
});
diff --git a/src/server/db.ts b/src/server/db.ts
index 772635f7..afc406ca 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -861,6 +861,7 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
CREATE INDEX IF NOT EXISTS worker_jobs_at ON worker_jobs(at);
CREATE INDEX IF NOT EXISTS worker_jobs_generation ON worker_jobs(generation_id);
CREATE INDEX IF NOT EXISTS worker_jobs_worker ON worker_jobs(worker_id);
+ CREATE INDEX IF NOT EXISTS worker_jobs_principal ON worker_jobs(principal, event);
CREATE TRIGGER IF NOT EXISTS worker_jobs_no_update BEFORE UPDATE ON worker_jobs BEGIN SELECT RAISE(ABORT, 'worker_jobs only grows'); END;
CREATE TRIGGER IF NOT EXISTS worker_jobs_kept BEFORE DELETE ON worker_jobs
WHEN OLD.at > CAST(strftime('%s', 'now') AS INTEGER) * 1000 - ${WORKER_JOBS_KEEP_MS}
@@ -1167,6 +1168,9 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_workers", "available_at", "INTEGER"],
// A run's priority within its class, from an external service (0: none; higher first: pool.ts smartLine).
["relay_tasks", "priority", "INTEGER NOT NULL DEFAULT 0"],
+ // One attempt of the task failed (it stalled, or ran past its run limit): it waits at the back of the line for its
+ // last try (pool.ts backInLine).
+ ["relay_tasks", "failed_once", "INTEGER NOT NULL DEFAULT 0"],
];
declare global {
diff --git a/src/server/queue-settings.ts b/src/server/queue-settings.ts
index 0f348215..69916b11 100644
--- a/src/server/queue-settings.ts
+++ b/src/server/queue-settings.ts
@@ -8,8 +8,8 @@ import { db } from "./db";
* 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.
+ * - `fairShare`: kept as it was saved, and read by nothing now: people always take turns in the line, one run each in
+ * every round (src/server/computer/pool.ts smartLine).
* - `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
diff --git a/tests/admin-queue-live.test.ts b/tests/admin-queue-live.test.ts
index a346fbb1..26e8bbe0 100644
--- a/tests/admin-queue-live.test.ts
+++ b/tests/admin-queue-live.test.ts
@@ -76,6 +76,8 @@ function task(o: { account?: string; message?: string | null } = {}): { id: stri
graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
pool: { pools: ["pool"], account: o.account, rankAt: clock, lane: LANE, needs: { workflowId: "wf-a", files: [], packs: [], minVramBytes: 0 } },
});
+ // Made at the test's clock (the line's 20-minute rule reads when a task came).
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock, t.id);
return { id: t.id, gid };
}
@@ -210,8 +212,8 @@ describe("what the workers do now", () => {
db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 9 * MIN, b.id);
// People first: the account's run ahead of the owner's own, although the owner's came first.
expect(liveQueue(clock).queued).toEqual([
- { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "People first", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false, fit: { needGb: null, workers: [] } },
- { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN, rank: 2, why: "Our work: after people's runs", code: "class", override: null, person: null, guest: false, fit: { needGb: null, workers: [] } },
+ { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "First run", order: "first-run", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false, fit: { needGb: null, workers: [] } },
+ { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN, rank: 2, why: "Our work: after people's runs", order: "owner", code: "class", override: null, person: null, guest: false, fit: { needGb: null, workers: [] } },
]);
// A worker takes the account's run first (people's runs go before the owner's own): the owner's stays in line.
const w = worker("takes");
diff --git a/tests/owner-hands-on.test.ts b/tests/owner-hands-on.test.ts
index 42ae7ee4..dd06cf6b 100644
--- a/tests/owner-hands-on.test.ts
+++ b/tests/owner-hands-on.test.ts
@@ -146,6 +146,8 @@ describe("the owner's run's class", () => {
expect(pool.ownerHandsOn(taskRow(mine.id))).toBe(true);
expect(pool.ownerHandsOn(taskRow(job({ source: "batch" }).id))).toBe(false);
expect(pool.ownerHandsOn(taskRow(job({ account: alice }).id))).toBe(false);
+ // (Alice's first run would go first in the round: out of the way here.)
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE account = ?").run(alice);
beat(w);
const c = claim(w);
expect(c?.id).toBe(mine.id);
@@ -277,10 +279,11 @@ describe("the Queue page", () => {
const batch = job({ source: "batch", agoMs: 10 * MIN });
const a = job({ account: alice, agoMs: MIN });
const q = liveQueue().queued;
- expect(q.map((x) => x.task)).toEqual([mine.id, a.id, batch.id]);
- expect(q[0]).toMatchObject({ principal: "owner", why: "Your run", handsOn: true, person: null });
- expect(q[1]).toMatchObject({ principal: "user", why: "People first" });
- expect(q[1]).not.toHaveProperty("handsOn");
+ // Alice has no finished run yet: her first run goes first in the round, then the owner's hands-on run.
+ expect(q.map((x) => x.task)).toEqual([a.id, mine.id, batch.id]);
+ expect(q[1]).toMatchObject({ principal: "owner", why: "Your run · Fastest of theirs", handsOn: true, person: null });
+ expect(q[0]).toMatchObject({ principal: "user", why: "First run" });
+ expect(q[0]).not.toHaveProperty("handsOn");
expect(q[2]).toMatchObject({ principal: "owner", why: "Our work: after people's runs" });
expect(q[2]).not.toHaveProperty("handsOn");
});
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index b0164e38..2b89448c 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -5,9 +5,10 @@ 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.
+ * The order of the line on this install's GPUs and its install-wide settings: people's runs (paid or free) taking turns,
+ * then the owner's own jobs in the order they came (the rest of the order: tests/pool-smart-queue.test.ts); 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 () => {} }));
@@ -140,6 +141,10 @@ function lineTask(o: { account?: string; class?: "paid" | "free" | "owner"; agoM
return t.id;
}
+/** A finished run of this account on the GPUs, long ago (it no longer counts as new). */
+const finishedLongAgo = (account: string) =>
+ db().prepare("INSERT INTO worker_jobs (at, event, task_id, generation_id, principal) VALUES (?, 'done', ?, ?, ?)").run(Date.now() - 24 * 60 * MIN, `t-${account}`, `g-${account}`, `acct:${account}`);
+
/** 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[] = [];
@@ -166,14 +171,16 @@ describe("classes", () => {
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", () => {
+ it("paid and free runs take turns in one line: the class orders nothing, and runs that waited 20 minutes go first", () => {
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]);
+ expect(pool.placeInLine(rowOf(free1)).place).toBe(1);
+ expect(pool.placeInLine(rowOf(paid2)).place).toBe(4);
+ // The two that waited 20 minutes or more, the oldest first; then one turn each, the one who waited longest first.
+ expect(served(w)).toEqual([free1, paid1, free2, paid2]);
});
it("a task from before classes reads as the owner's with no account and as a person's free run with one", () => {
@@ -309,6 +316,8 @@ describe("a run's later steps keep the run's place", () => {
it("a chain's next step keeps the run's class and place, waits past the run's wait limit behind a long line, and still runs first", async () => {
const w = standInWorker();
+ // (Both people have a finished run: neither goes first for a first run.)
+ finishedLongAgo(other);
const wait = 5 * MIN;
const first = runRow({ batch: "chain-a" });
const one = await sendStep(first, { class: "paid", waitMs: wait });
@@ -359,6 +368,7 @@ describe("a run's later steps keep the run's place", () => {
it("A5: a 3-step chain under load: each later step ranks with step 1, ahead of runs sent after it, and nothing fails after 20 minutes", async () => {
const w = standInWorker();
+ finishedLongAgo(other);
const wait = 5 * MIN;
const first = runRow({ batch: "chain-e" });
const one = await sendStep(first, { waitMs: wait });
@@ -457,18 +467,20 @@ describe("a run's later steps keep the run's place", () => {
});
});
-describe("fair share", () => {
- it("off: strict order; on: each account's first run goes before anyone's second, counting runs it has going", () => {
+describe("taking turns", () => {
+ it("each person's first run goes before anyone's second, counting runs they have going, whatever fairShare says", () => {
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 a1 = lineTask({ account: accountId, agoMs: 3 * MIN });
+ const a2 = lineTask({ account: accountId, agoMs: 2.9 * MIN });
+ const a3 = lineTask({ account: accountId, agoMs: 2.8 * MIN });
+ const b1 = lineTask({ account: other, agoMs: 1 * 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 });
+ const line = () => pool.lineOrder(db().prepare("SELECT * FROM relay_tasks WHERE state = 'waiting' AND pools IS NOT NULL").all() as never).map((t) => t.id);
+ expect(line()).toEqual([a1, b1, a2, a3, owner]);
expect(pool.placeInLine(rowOf(b1)).place).toBe(2);
+ qs.saveQueueSettings({ ...qs.queueSettings(), fairShare: true });
+ expect(line()).toEqual([a1, b1, a2, a3, owner]);
+ qs.saveQueueSettings({ ...qs.queueSettings(), fairShare: false });
expect(served(w)).toEqual([a1, b1, a2, a3, owner]);
});
});
@@ -484,7 +496,8 @@ describe("the pick allowance", () => {
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] });
+ // (The other person's turn now: their run in the lane it hasn't loaded came first, so it goes first.)
+ const old2 = lineTask({ account: other, 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);
// A warm lane never makes a person wait: people's runs keep their order, whatever lane is loaded.
diff --git a/tests/pool-smart-queue.test.ts b/tests/pool-smart-queue.test.ts
new file mode 100644
index 00000000..2f542af0
--- /dev/null
+++ b/tests/pool-smart-queue.test.ts
@@ -0,0 +1,469 @@
+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 smart order of the line on this install's GPUs (src/server/computer/pool.ts smartLine): rounds over people, each
+ * person's fastest run in their turn, and in each round people watching their runs, then by priority, then people with
+ * no finished run yet, then everyone else; runs that waited 20 minutes first; a run that failed once at the very back
+ * with one more try once the line is free; recoveries keep their place; a run only one GPU can make goes to that GPU
+ * first; the owner's own jobs last; the owner's controls on top. And where its facts come from: who is watching (the
+ * reads an open page makes), the priority the billing service gives, and the owner's Queue page's words.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-smart-queue-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+for (const k of ["FUOBE_PASSWORD", "FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_MODERATION_URL"]) delete process.env[k];
+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 generationsRoute = await import("@/app/api/generations/route");
+const { proxy } = await import("@/proxy");
+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 qc = await import("@/server/computer/queue-controls");
+const watching = await import("@/server/computer/watching");
+const { liveQueue } = await import("@/server/computer/queue-live");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const billing = await import("@/server/billing");
+const qs = await import("@/server/queue-settings");
+const { heldStamp } = await import("@/server/hosted-run");
+const { cleanPriority } = await import("@/lib/run-priority");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+
+type TaskRow = import("@/server/computer/tasks").TaskRow;
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+
+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");
+const LANES = allLanes(loadIndex(), sha).map((l) => l.lane);
+/** A quick lane and a slow one, as the stand-in workers' benches say. */
+const QUICK = LANES[0];
+const SLOW = LANES[1];
+
+let fake: FakeBilling;
+let accountId = "";
+let cookie = "";
+
+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}`;
+});
+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 = {};
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("DELETE FROM relay_watching").run();
+ db().prepare("DELETE FROM queue_overrides").run();
+ globalThis.__fuobeWatchNoted = undefined;
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state != 'canceled'").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+/** A stand-in worker that beat a moment ago: the lanes it is allowed (all by default), with a bench that makes QUICK quick and SLOW slow. */
+function standInWorker(name = "stand-in", o: { lanes?: string[]; bench?: Record<string, number> } = {}) {
+ const w = pool.addWorker(name);
+ const lanes = o.lanes ?? LANES;
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });
+ const bench = o.bench ?? { [QUICK]: 5_000, [SLOW]: 300_000 };
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3, bench_json = ?, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(
+ JSON.stringify({ lanes: LANES, workflows: loadManifest().workflows.map((x) => x.id) }),
+ JSON.stringify({ vramBytes: 96 * 2 ** 30 }),
+ catalogVersion(),
+ JSON.stringify(Object.fromEntries(Object.entries(bench).map(([l, ms]) => [l, { medianMs: ms, p90Ms: ms }]))),
+ Date.now(),
+ w.id,
+ );
+ return w;
+}
+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: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);
+const claimAs = (w: { id: string }, now = Date.now()) => {
+ beatAs(w, now);
+ return pool.workerClaim(workerRow(w), [], now);
+};
+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;
+const done = (id: string) => db().prepare("UPDATE relay_tasks SET state = 'done', finished_at = ? WHERE id = ?").run(Date.now(), id);
+const waiting = () => db().prepare("SELECT * FROM relay_tasks WHERE state = 'waiting' AND pools IS NOT NULL").all() as TaskRow[];
+/** The line as a whole, in its order (the order a place in line reads). */
+const line = (now = Date.now()) => pool.lineOrder(waiting(), "people-first", { now }).map((t) => t.id);
+
+let n = 0;
+/** A person of their own for one test (people keep their finished runs across tests). */
+const person = (name: string) => `${name}-${++n}`;
+/** A finished run of this person on the GPUs, long ago: they no longer count as new. */
+const finishedBefore = (...accounts: string[]) => {
+ for (const a of accounts) db().prepare("INSERT INTO worker_jobs (at, event, task_id, generation_id, principal) VALUES (?, 'done', ?, ?, ?)").run(Date.now() - 24 * 60 * MIN, `t-${a}`, `g-${a}`, `acct:${a}`);
+};
+const watch = (...accounts: string[]) => {
+ for (const a of accounts) watching.noteWatching(a);
+};
+
+let gens = 0;
+/** A task in the line: a person's (`account`) or the owner's own job, made `agoMs` ago, in a lane, with a priority. */
+function lineTask(o: { account?: string; agoMs?: number; lane?: string; priority?: number; class?: "paid" | "free" } = {}) {
+ const gid = `smart-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" } : { source: "batch" }), at, at);
+ 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.account ? (o.class ?? "free") : "owner", priority: o.priority, rankAt: at, lane: o.lane ?? QUICK, 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 it serves them. */
+function served(w: { id: string }): string[] {
+ const out: string[] = [];
+ for (;;) {
+ const t = claimAs(w);
+ if (!t) return out;
+ out.push(t.id);
+ done(t.id);
+ }
+}
+
+describe("rounds over people", () => {
+ it("in each round: watching, then by priority, then a first run, then everyone else", () => {
+ const w = standInWorker();
+ const [W, P2, P1, F, E] = [person("watcher"), person("max"), person("pro"), person("new"), person("else")];
+ finishedBefore(W, P2, P1, E);
+ watch(W);
+ // In the order they came alone, the last of them would go first.
+ const e = lineTask({ account: E, agoMs: 5 * MIN });
+ const f = lineTask({ account: F, agoMs: 4 * MIN });
+ const p1 = lineTask({ account: P1, agoMs: 3 * MIN, priority: 1 });
+ const p2 = lineTask({ account: P2, agoMs: 2 * MIN, priority: 2 });
+ const wa = lineTask({ account: W, agoMs: 1 * MIN });
+ expect(line()).toEqual([wa, p2, p1, f, e]);
+ expect(pool.placeInLine(rowOf(wa)).place).toBe(1);
+ expect(pool.placeInLine(rowOf(e)).place).toBe(5);
+ expect(served(w)).toEqual([wa, p2, p1, f, e]);
+ });
+
+ it("a watcher with four quick runs takes one turn a round: the others' runs come in the first round", () => {
+ const w = standInWorker();
+ const [A, B, C] = [person("watcher"), person("pro"), person("free")];
+ watch(A);
+ const a = [1, 2, 3, 4].map((i) => lineTask({ account: A, agoMs: (10 - i) * 1000 }));
+ const b = lineTask({ account: B, agoMs: 5000, priority: 1 });
+ const c = lineTask({ account: C, agoMs: 4000 });
+ expect(line()).toEqual([a[0], b, c, a[1], a[2], a[3]]);
+ expect(served(w)).toEqual([a[0], b, c, a[1], a[2], a[3]]);
+ });
+
+ it("two watchers, one with four quick runs and one with one slow run: the slow run comes second, not fifth", () => {
+ const w = standInWorker();
+ const [W1, W2] = [person("quick"), person("slow")];
+ watch(W1, W2);
+ const quick = [1, 2, 3, 4].map((i) => lineTask({ account: W1, agoMs: (10 - i) * 1000, lane: QUICK }));
+ const slow = lineTask({ account: W2, agoMs: 2000, lane: SLOW });
+ expect(line()).toEqual([quick[0], slow, quick[1], quick[2], quick[3]]);
+ expect(served(w)).toEqual([quick[0], slow, quick[1], quick[2], quick[3]]);
+ });
+
+ it("a person with a priority and a person with none, three runs each: they alternate, the priority first in each round", () => {
+ const w = standInWorker();
+ const [M, F] = [person("max"), person("free")];
+ finishedBefore(M, F);
+ const f = [1, 2, 3].map((i) => lineTask({ account: F, agoMs: (10 - i) * 1000 }));
+ const m = [1, 2, 3].map((i) => lineTask({ account: M, agoMs: (5 - i) * 1000, priority: 2 }));
+ expect(line()).toEqual([m[0], f[0], m[1], f[1], m[2], f[2]]);
+ expect(served(w)).toEqual([m[0], f[0], m[1], f[1], m[2], f[2]]);
+ });
+
+ it("each person's turn takes their fastest run for the worker that asks; within a level, who waited longest goes first", () => {
+ const w = standInWorker();
+ const [A, B] = [person("a"), person("b")];
+ const aSlow = lineTask({ account: A, agoMs: 3 * MIN, lane: SLOW });
+ const aQuick = lineTask({ account: A, agoMs: 1 * MIN, lane: QUICK });
+ const b = lineTask({ account: B, agoMs: 2 * MIN, lane: SLOW });
+ // A waited longest: A's quickest first, then B's, then A's slow one.
+ expect(line()).toEqual([aQuick, b, aSlow]);
+ // On a worker where that lane is the slow one, A's other run is the quicker.
+ const other = standInWorker("reversed", { bench: { [QUICK]: 300_000, [SLOW]: 5_000 } });
+ expect(pool.lineOrder(waiting(), "people-first", { worker: workerRow(other), workers: [workerRow(other)] }).map((t) => t.id)).toEqual([aSlow, b, aQuick]);
+ db().prepare("DELETE FROM relay_workers WHERE id = ?").run(other.id);
+ expect(served(w)).toEqual([aQuick, b, aSlow]);
+ });
+
+ it("a run a worker holds for a person now is their turn this round", () => {
+ const w1 = standInWorker("w1");
+ const w2 = standInWorker("w2");
+ const [A, B] = [person("a"), person("b")];
+ finishedBefore(A, B);
+ const a1 = lineTask({ account: A, agoMs: 5000 });
+ const a2 = lineTask({ account: A, agoMs: 4000 });
+ const b1 = lineTask({ account: B, agoMs: 1000 });
+ expect(claimAs(w1)?.id).toBe(a1);
+ // A's first run is being made: B's turn comes before A's second.
+ expect(line()).toEqual([b1, a2]);
+ expect(claimAs(w2)?.id).toBe(b1);
+ });
+
+ it("paid credits without a priority stand with everyone else: the class orders nothing", () => {
+ const w = standInWorker();
+ const [P, F] = [person("paid"), person("free")];
+ finishedBefore(P, F);
+ const f = lineTask({ account: F, agoMs: 3000 });
+ const p = lineTask({ account: P, agoMs: 1000, class: "paid" });
+ expect(served(w)).toEqual([f, p]);
+ });
+});
+
+describe("waiting 20 minutes", () => {
+ it("a run that waited 20 minutes goes to the front, the oldest first; at 19 minutes it waits its turn", () => {
+ const w = standInWorker();
+ const [W, E, G] = [person("watcher"), person("else"), person("older")];
+ finishedBefore(E, G);
+ watch(W);
+ const now = Date.now();
+ const quick = [1, 2].map((i) => lineTask({ account: W, agoMs: i * 1000 }));
+ const e = lineTask({ account: E, agoMs: 19 * MIN, lane: SLOW });
+ expect(line(now)).toEqual([quick[1], e, quick[0]]);
+ // A minute later it has waited 20: to the front.
+ expect(line(now + MIN + 1000)).toEqual([e, quick[1], quick[0]]);
+ // Two that waited: the oldest first, whatever their people.
+ const g = lineTask({ account: G, agoMs: 25 * MIN, lane: SLOW });
+ expect(line(now + MIN + 1000)).toEqual([g, e, quick[1], quick[0]]);
+ expect(served(w).slice(0, 1)).toEqual([g]);
+ });
+});
+
+describe("recoveries", () => {
+ it("keep their place: a worker that went silent, and a run given back for memory, wait where they were, with nothing failed", () => {
+ const w = standInWorker();
+ const [A, B] = [person("a"), person("b")];
+ const a = lineTask({ account: A, agoMs: 5 * MIN });
+ expect(claimAs(w)?.id).toBe(a);
+ const b = lineTask({ account: B, agoMs: 1 * MIN });
+ // Its worker goes quiet: back in line, at its place.
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 10 * MIN, w.id);
+ pool.sweepPool();
+ expect(rowOf(a)).toMatchObject({ state: "waiting", requeues: 1, failed_once: 0 });
+ expect(line()).toEqual([a, b]);
+ expect(pool.placeInLine(rowOf(a)).place).toBe(1);
+ // A run given back by a worker that can't make its clips: the same.
+ const c = claimAs(w)!;
+ expect(c.id).toBe(a);
+ tasks.report(rowOf(a), { event: "sent", promptId: c.promptId }, () => ({ error: "unused" }));
+ tasks.report(rowOf(a), { event: "give-back", why: "media" }, () => ({ error: "unused" }));
+ expect(rowOf(a)).toMatchObject({ state: "waiting", requeues: 2, failed_once: 0 });
+ expect(line()).toEqual([a, b]);
+ });
+});
+
+describe("best GPU for the job", () => {
+ it("a worker takes a run only it can make before one another GPU could; with no other GPU on, it follows the order", () => {
+ const big = standInWorker("big");
+ const small = standInWorker("small", { lanes: [QUICK] });
+ const [A, B] = [person("a"), person("b")];
+ const q = lineTask({ account: A, agoMs: 3 * MIN, lane: QUICK });
+ const s = lineTask({ account: B, agoMs: 1 * MIN, lane: SLOW });
+ expect(line()).toEqual([q, s]);
+ // Only the big worker can make B's run: it takes that one; the small one takes A's.
+ expect(claimAs(big)?.id).toBe(s);
+ expect(claimAs(small)?.id).toBe(q);
+ done(s);
+ done(q);
+ // The small worker is off: the big one follows the order.
+ const q2 = lineTask({ account: A, agoMs: 3 * MIN, lane: QUICK });
+ const s2 = lineTask({ account: B, agoMs: 1 * MIN, lane: SLOW });
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 10 * MIN, small.id);
+ expect(claimAs(big)?.id).toBe(q2);
+ done(q2);
+ done(s2);
+ // A run the owner sent next goes first all the same.
+ beatAs(small);
+ const q3 = lineTask({ account: A, agoMs: 3 * MIN, lane: QUICK });
+ lineTask({ account: B, agoMs: 1 * MIN, lane: SLOW });
+ const o = qc.checkOverride({ kind: "run", generationId: rowOf(q3).generation_id, action: "next" });
+ if ("error" in o) throw new Error(o.error);
+ qc.addOverride(o, "owner");
+ expect(claimAs(big)?.id).toBe(q3);
+ });
+});
+
+describe("the owner's own jobs and the owner's controls", () => {
+ it("runs sent next, boosted people and holds still work on top of the order", () => {
+ const w = standInWorker();
+ const [W, E] = [person("watcher"), person("else")];
+ finishedBefore(E);
+ watch(W);
+ const wa = lineTask({ account: W, agoMs: 1000 });
+ const e = lineTask({ account: E, agoMs: 2000 });
+ const owner = lineTask({ agoMs: 60 * MIN });
+ const add = (body: unknown) => {
+ const o = qc.checkOverride(body);
+ if ("error" in o) throw new Error(o.error);
+ const r = qc.addOverride(o, "owner");
+ if ("error" in r) throw new Error(r.error);
+ };
+ expect(line()).toEqual([wa, e, owner]);
+ add({ kind: "run", generationId: rowOf(owner).generation_id, action: "next" });
+ add({ kind: "person", account: E, action: "boost", forMin: 30 });
+ add({ kind: "person", account: W, action: "hold" });
+ expect(pool.placeInLine(rowOf(owner)).place).toBe(1);
+ expect(pool.placeInLine(rowOf(e)).place).toBe(2);
+ expect(served(w)).toEqual([owner, e]);
+ expect(rowOf(wa).state).toBe("waiting");
+ });
+});
+
+describe("who is watching", () => {
+ it("an account's page that reads its runs counts as watching for 60 seconds; other reads, guests and the owner don't", async () => {
+ const at = Date.now();
+ const ask = (path: string, c?: string) => proxy(new NextRequest(`http://${HOST}${path}`, { method: "GET", headers: { host: HOST, ...(c && { cookie: c }) } }));
+ await ask("/api/models", cookie);
+ expect(watching.watchingNow(at).has(accountId)).toBe(false);
+ await ask("/api/generations?statuses=queued,running&steps=1&limit=100", cookie);
+ expect(watching.watchingNow().has(accountId)).toBe(true);
+ expect(watching.watchingNow(Date.now() + 59_000).has(accountId)).toBe(true);
+ expect(watching.watchingNow(Date.now() + 61_000).has(accountId)).toBe(false);
+ // The reads that follow runs: the list, one run, its live picture; not the Library's counts, the Trash or a zip.
+ for (const p of ["/api/generations", "/api/generations/g-1", "/api/generations/g-1/preview"]) expect(watching.followsRuns("GET", p), p).toBe(true);
+ for (const p of ["/api/generations/facets", "/api/generations/trash", "/api/generations/zip", "/api/generations/g-1/cancel", "/api/models"]) expect(watching.followsRuns("GET", p), p).toBe(false);
+ expect(watching.followsRuns("POST", "/api/generations")).toBe(false);
+ await ask("/api/generations");
+ expect([...watching.watchingNow()]).toEqual([accountId]);
+ });
+
+ it("is written at most every 15 seconds for one account", () => {
+ const at = Date.now();
+ watching.noteWatching("acct-throttle", at);
+ watching.noteWatching("acct-throttle", at + 10_000);
+ const seen = () => (db().prepare("SELECT seen_at FROM relay_watching WHERE account = ?").get("acct-throttle") as { seen_at: number }).seen_at;
+ expect(seen()).toBe(at);
+ watching.noteWatching("acct-throttle", at + 16_000);
+ expect(seen()).toBe(at + 16_000);
+ });
+});
+
+describe("priority from the billing service", () => {
+ it("is a whole number from 0 to 9: out of range is the nearest, anything else 0", () => {
+ expect([0, 1, 2, 9, 12, -3, 2.7, Number.NaN, Infinity].map(cleanPriority)).toEqual([0, 1, 2, 9, 9, 0, 2, 0, 0]);
+ for (const v of ["2", null, undefined, {}, true]) expect(cleanPriority(v)).toBe(0);
+ const ok = { ok: true as const, holdId: "h", amount: 0, boostMs: 0, maxWaitMs: 0, text: "" };
+ expect(heldStamp({ ...ok, priority: 2 }, undefined).priority).toBe(2);
+ expect(heldStamp({ ...ok, priority: 40 }, undefined).priority).toBe(9);
+ expect(heldStamp({ ...ok, priority: 0 }, undefined)).not.toHaveProperty("priority");
+ expect(heldStamp(ok, undefined)).not.toHaveProperty("priority");
+ });
+
+ it("an account's run takes the priority the reserve answer gives, kept on the run, and the browser never sees it", 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", priority: 2 };
+ 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;
+ const taskOf = () => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(id) as TaskRow | undefined;
+ let t = taskOf();
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf();
+ }
+ expect(t).toMatchObject({ class: "paid", priority: 2 });
+ 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.priority).toBe(2);
+ expect(pool.runPlaceOf(id)?.priority).toBe(2);
+ expect((getGeneration(id) as unknown as { request?: Record<string, unknown> }).request?.priority).toBeUndefined();
+ });
+});
+
+describe("the owner's Queue page", () => {
+ it("says why each run stands where it does; the person reading their run sees none of it", () => {
+ const big = standInWorker("big");
+ standInWorker("small", { lanes: [QUICK] });
+ const [W, P, F, E, G, S, O] = [person("watcher"), person("pro"), person("new"), person("else"), person("older"), person("failed"), person("only")];
+ finishedBefore(W, P, E, G, S, O);
+ watch(W);
+ const ids = {
+ aged: lineTask({ account: G, agoMs: 25 * MIN }),
+ watching: lineTask({ account: W, agoMs: 1000 }),
+ priority: lineTask({ account: P, agoMs: 2000, priority: 1 }),
+ first: lineTask({ account: F, agoMs: 3000 }),
+ turn: lineTask({ account: E, agoMs: 5000 }),
+ only: lineTask({ account: O, agoMs: 4000, lane: SLOW }),
+ second: lineTask({ account: S, agoMs: 6000 }),
+ owner: lineTask({ agoMs: 60 * MIN }),
+ };
+ db().prepare("UPDATE relay_tasks SET failed_once = 1 WHERE id = ?").run(ids.second);
+ const q = liveQueue().queued;
+ const why = (id: string) => q.find((x) => x.task === id)?.why;
+ expect(why(ids.aged)).toBe("Waited 20 min");
+ expect(why(ids.watching)).toBe("Watching");
+ expect(why(ids.priority)).toBe("Plan priority");
+ expect(why(ids.first)).toBe("First run");
+ expect(why(ids.turn)).toBe("Fastest of theirs");
+ expect(why(ids.only)).toBe("Only this GPU can make it");
+ expect(why(ids.second)).toBe("Second try when the line is free");
+ expect(why(ids.owner)).toBe("Our work: after people's runs");
+ expect(q.map((x) => x.task)).toEqual([ids.aged, ids.watching, ids.priority, ids.first, ids.turn, ids.only, ids.second, ids.owner]);
+ expect(q.map((x) => x.rank)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
+ // The big worker, the only one that makes the slow lane, takes that run first.
+ expect(claimAs(big)?.id).toBe(ids.only);
+ const words = /Watching|Plan priority|First run|Fastest of theirs|Waited 20 min|Second try|Only this GPU/;
+ for (const id of Object.values(ids)) expect(JSON.stringify(getGeneration(rowOf(id).generation_id))).not.toMatch(words);
+ });
+});
diff --git a/tests/queue-controls.test.ts b/tests/queue-controls.test.ts
index 8785fa71..4bf80347 100644
--- a/tests/queue-controls.test.ts
+++ b/tests/queue-controls.test.ts
@@ -167,13 +167,15 @@ describe("modes", () => {
expect(served(w)).toEqual([owner.id]);
});
- it("balanced: free runs and the owner's own jobs in one line by when they came; paid runs first", () => {
+ it("balanced: people's runs and the owner's own jobs take turns in one line, the owner as one more person", () => {
const w = worker("w1");
- const owner = job({ agoMs: 30 * MIN });
- const a = job({ account: alice, agoMs: 20 * MIN });
+ const owner1 = job({ agoMs: 5 * MIN });
+ const owner2 = job({ agoMs: 4 * MIN });
+ const a = job({ account: alice, agoMs: 3 * MIN });
const paid = job({ account: bob, class: "paid", agoMs: 1 * MIN });
setMode({ mode: "balanced", forMin: 60 });
- expect(served(w)).toEqual([paid.id, owner.id, a.id]);
+ // Round one: Alice and Bob (no finished run yet: first) by who waited longest, then the owner; round two: the owner.
+ expect(served(w)).toEqual([a.id, paid.id, owner1.id, owner2.id]);
});
it("a worker's own mode wins over its pool's; back to normal follows the pool again", () => {
@@ -390,7 +392,8 @@ describe("the admin routes", () => {
expect(body.controls.pools.pool.mode).toBe("people-first");
expect(body.controls.workers).toEqual([expect.objectContaining({ name: "w1", mode: expect.objectContaining({ mode: "people-only", from: "worker" }) })]);
expect(body.controls.modes).toHaveLength(4);
- expect(body.queued[0]).toMatchObject({ why: "People first", person: qc.personKey(alice) });
+ // (Alice has no finished run on the GPUs yet: her first run goes first in its round.)
+ expect(body.queued[0]).toMatchObject({ why: "First run", order: "first-run", person: qc.personKey(alice) });
expect(JSON.stringify(body)).not.toContain(alice);
});
});
diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.ts
index ecc23043..72469fd2 100644
--- a/tests/recovery-server.test.ts
+++ b/tests/recovery-server.test.ts
@@ -115,6 +115,9 @@ beforeAll(async () => {
a1 = session(A);
a2 = session(A);
b1 = session(B);
+ // Both have a finished run on the GPUs already: neither goes first in a round as a new person (the line's own order is
+ // checked in tests/pool-smart-queue.test.ts; here, the place a recovery keeps).
+ for (const id of [A, B]) db().prepare("INSERT INTO worker_jobs (at, event, task_id, generation_id, principal) VALUES (?, 'done', ?, ?, ?)").run(Date.now(), `t-${id}`, `g-${id}`, `acct:${id}`);
settings();
ensureRunner();
runnerByHand();
@@ -143,6 +146,9 @@ beforeEach(async () => {
db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
db().prepare("DELETE FROM pool_admissions").run();
+ // Both people count as watching their runs throughout (the checks look at one person's run and not the other's; the
+ // line's own order is checked in tests/pool-smart-queue.test.ts): here, the place a recovery keeps.
+ for (const id of [A, B]) db().prepare("INSERT INTO relay_watching (account, seen_at) VALUES (?, ?) ON CONFLICT(account) DO UPDATE SET seen_at = excluded.seen_at").run(id, Date.now() + 10 * 365 * 24 * 60 * MIN);
});
afterEach(() => {
vi.useRealTimers();
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index 38da1589..6859bf53 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -408,6 +408,8 @@ describe("order (checks 8, 9)", () => {
const owner2 = task({ rankAgoMs: 23 * 60 * MIN });
const guest = task({ account: "guest", rankAgoMs: 2 * MIN });
const person = task({ account: "acct-a", rankAgoMs: 1 * MIN });
+ // (A person with no finished run yet goes first in a round: this one has one, so the guest, who came first, goes first.)
+ db().prepare("INSERT INTO worker_jobs (at, event, task_id, generation_id, principal) VALUES (?, 'done', 't-earlier', 'g-earlier', 'acct:acct-a')").run(clock - 60 * MIN);
const order: string[] = [];
for (let i = 0; i < 4; i++) {
const c = claim(w);