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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: one job each, a sending clock, and a log of who ran which job
Adarshc31d9d99dfdf
diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 29aa2dd3..26e3f77f 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -43,7 +43,7 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz| `outputs:hide` | `POST /api/admin/outputs/hide` || `outputs:moderate` | `POST /api/admin/outputs/hide`, `/unhide` and `/remove` || `reports:read` | `GET /api/admin/reports` (reporters' emails included) |-| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/download` |+| `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` |@@ -109,6 +109,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `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 |+| `GET /api/admin/workers/jobs` | `before`, `limit` (1 to 200, 50), `worker`, `generation` | `{ items, next }`: the workers' log, newest first. Each item: `{ id, at, event, workerId, workerName, taskId, generationId, principal, lane, execMs, device }` ([gpu-workers.md](gpu-workers.md)) || `GET /api/admin/workers/download` | | the worker program, `fuobe-worker.zip` || `GET /api/admin/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner` or `token`), `token` (a token id), `action`, `changes=1` (changes only: no reads, file views or refusals) | `{ items, next }` || `GET /api/admin/tokens/self` | | `{ id, name, prefix, scopes, expiresAt, createdAt }` |diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex cbcb1269..94e4f110 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -78,7 +78,15 @@ type Policy = {be higher, it refuses with `price-changed` and the new quote, and the person sees the new price before running again.A reserve's `text` is shown on the result once it succeeded ("7 units"). `maxWaitMs` is how long the run may wait in-line; past it the row fails and is refunded.+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.++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+files, no upload). A job that ran more than once counts once, for the attempt whose result was kept. `device` is the+GPU's name. Elsewhere `gpuMs` is the row's time from its start to its end, and+`device` is null.Example (arbitrary numbers):diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex ea8802ef..c7bbda75 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -110,8 +110,12 @@ A job for the workers belongs to the owner. It names the pools that may take itwith 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 packsand its VRAM;-- `rank_at`: `created_at` minus a boost. The owner's jobs get a one-day boost.-- a wait limit (`FUOBE_POOL_WAIT_MIN`, 30 minutes). Past it, the job fails with "The GPUs were busy".+- `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".+- 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.A worker gets a job only when all of these are true, all in one SQLite transaction:@@ -121,15 +125,29 @@ A worker gets a job only when all of these are true, all in one SQLite transacti- it has the workflow's files and packs (from its inventory) and enough VRAM;- the retry rule allows it: a worker that lost or failed the job gets it again only when no other worker that can runthe job was heard from in the last 10 minutes;-- near the end of its hours, the job's estimate fits before the window closes.--The lowest `rank_at` goes first. 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.--If a worker stops answering for 2 minutes, or its ComfyUI is down for 2 minutes, its job goes back to the queue. The-worker is added to the job's `tried_json` list, and the input reads start again. The old worker's late calls get 409,-and it deletes that prompt. After the third lost attempt, the job fails. A job that is put back because of a pause-does not count as an attempt.+- 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.++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.++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+back to the queue. The worker is added to the job's+`tried_json` list, and the input reads start again. The old worker's late calls get 409, and it deletes that prompt.+After the third lost attempt, the job fails. A job that is put back because of a pause does not count as an attempt.+The run's own clocks follow the queue's: each attempt gets its own running time.++**The place in line.** A waiting job's place counts every job that a worker able to run it would serve first, whatever+its lane: one GPU serves every lane it has in this order. The wait adds the rest of the jobs those workers run now,+the lane's load time when none has it warm, and the job's own run (the lane's median on the quickest worker, else the+median of the workers' measured runs). The billing service's line facts (`QueueFacts`) read the same line.++**The workers' log.** `worker_jobs` keeps which worker took which job, when, and how it ended (`claimed`,+`finished` with the measured run, `requeued`, `done`, `failed`, `canceled`). It holds ids, times and those facts+only. Rows are only added, and each is kept a year, like the admin API's log. The owner reads it at+`GET /api/admin/workers/jobs` ([admin-api.md](admin-api.md)).### What the worker checks itself@@ -156,7 +174,8 @@ token on every call, so a revoked token stops at once.- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,- insideHours, nextChangeAt, lanes, minProtocol, sendInventory }`.+ insideHours, nextChangeAt, lanes, minProtocol, sendInventory }` and `claimableNow`: how many people's jobs (an+ account's, never the owner's) this worker may claim right now by its lanes, files, VRAM and hours, its own pause aside.- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }] }` →`{ lanes, workflows, missing }`.- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,@@ -164,7 +183,9 @@ token on every call, so a revoked token stops at once.- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finishedjob also count: the last 20 jobs in each lane give the median and the 90th percentile.- Reports, inputs and results work as they do for the browser. `failed` can also give `unknown-node`, `unsafe-path`- or `model-unverified` as the reason.+ or `model-unverified` as the reason. `finished` (and the last `passes`) can add `execMs`, the time its ComfyUI+ spent running the job (not waits, files or the upload), and `device`, its GPU's name. The billing service gets+ them as `gpuMs` and `device`. A job that ran more than once counts once: the attempt whose result was kept.Each worker counts against its own rate limits, so three workers that beat every 5 seconds never hold each other up.diff --git a/src/app/api/admin/workers/jobs/route.ts b/src/app/api/admin/workers/jobs/route.tsnew file mode 100644index 00000000..d636eeb2--- /dev/null+++ b/src/app/api/admin/workers/jobs/route.ts@@ -0,0 +1,19 @@+import { connection } from "next/server";+import { adminAccess } from "@/server/admin-tokens";+import { listWorkerJobs, workerJobsQueryFrom } from "@/server/computer/tasks";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * The workers' log, newest first (owner only, or an admin token with workers:read; docs/gpu-workers.md): which worker+ * took which job and when, and how it ended, with the measured run. Ids, times and those facts only. `before=<id>` (the+ * `next` of the last page), `limit` (1 to 200, 50 when not given), `worker=<id>`, `generation=<run id>`.+ */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "workers:read", "Only the studio's owner sees the workers' log");+ if (access instanceof Response) return access;+ const q = workerJobsQueryFrom(new URL(request.url).searchParams);+ if ("error" in q) return Response.json({ error: q.error }, { status: 400, headers: NO_STORE });+ return Response.json(listWorkerJobs(q), { headers: NO_STORE });+}diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.tsindex c4a322d7..c8b0580a 100644--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts@@ -2,7 +2,7 @@ import { RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";import { noteFinished } from "@/server/computer/bench";-import { leased, report, type TaskRow } from "@/server/computer/tasks";+import { leased, logWorkerJob, report, type TaskRow } from "@/server/computer/tasks";import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";import { enter } from "@/server/rate";@@ -28,9 +28,9 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {case "running":return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }) };case "finished":- return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }) } : null;+ return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }), ...measured(b) } : null;case "passes":- return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never } : null;+ return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never, ...measured(b) } : null;case "failed":return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status) } : null;case "comfy-down":@@ -40,6 +40,13 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {}}+/** A worker's measured run: its ComfyUI's time on the job (at most a day) and its GPU's name, as far as each is sound. */+function measured(b: Record<string, unknown>): { execMs?: number; device?: string } {+ const ms = typeof b.execMs === "number" && Number.isFinite(b.execMs) && b.execMs >= 0 && b.execMs <= 24 * 3_600_000 ? Math.round(b.execMs) : undefined;+ const device = typeof b.device === "string" ? b.device.replace(/[^\p{L}\p{N} ._:()+/-]/gu, "").trim().slice(0, 120) : "";+ return { ...(ms !== undefined && { execMs: ms }), ...(device && { device }) };+}+/** The most a report about this job may weigh now: a finished entry while ComfyUI has it, a refusal while it sends. */const capFor = (t: TaskRow) => (t.state === "queued" || t.state === "running" ? RELAY_LIMITS.reportBytes : t.state === "sending" ? RELAY_LIMITS.refusalBytes : RELAY_LIMITS.smallReportBytes);/** The reports that carry ComfyUI's own answer; every other one is a few words. */@@ -95,8 +102,11 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute// Where the job is now (it may have moved while the body arrived).const t = leased(principal, id, lease);const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => planRelayOutputs(t, entries, passes)));- // A worker's finished job counts toward its lane's times there.- if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running") noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);+ // A worker's finished job counts toward its lane's times there, and the workers' log keeps its measured run.+ if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running") {+ noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);+ if (t.worker_id) logWorkerJob("finished", t, t.worker_id, Date.now(), { execMs: event.execMs, device: event.device });+ }return Response.json(answer, { headers: { "Cache-Control": "no-store" } });} catch (e) {return relayAnswer(e);diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 4a6fce4f..36cc01da 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -37,10 +37,13 @@ export type ReportEvent =| { event: "queued"; position: number }/** Running: the sampler's steps, and the node. */| { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }- /** Finished: its /history entry (a worker adds the most VRAM it took, for the benchmarks). */- | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number }+ /**+ * Finished: its /history entry. A worker adds the most VRAM it took (for the benchmarks), the time its ComfyUI spent+ * running the job (`execMs`: not the wait, the files or the upload) and its GPU's name (`device`).+ */+ | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string }/** A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. */- | { event: "passes"; running: boolean; entries: HistoryEntryLike[] }+ | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string }/** ComfyUI has no trace of it (restarted): the server sends it again once. */| { event: "gone" }/** The tab can't use ComfyUI: it doesn't answer, or (`why: "setting"`) it answers without Fuobe's setting. */@@ -145,6 +148,8 @@ export interface BeatAnswer {heldElsewhere: boolean;/** Tasks waiting for a computer. */waiting: number;+ /** A worker's own: people's tasks it may claim right now (its lanes, files, VRAM and hours), its own pause aside. */+ claimableNow?: number;/** Prompts to take off this computer's ComfyUI. */stops: { task: string; promptId: string; prefix?: string }[];/** A worker's own (docs/gpu-workers.md): what the studio says about it now. */diff --git a/src/server/billing-outbox.ts b/src/server/billing-outbox.tsindex fede02cc..d9c8e3cf 100644--- a/src/server/billing-outbox.ts+++ b/src/server/billing-outbox.ts@@ -29,6 +29,12 @@ interface DoneRow {started_at: number | null;completed_at: number | null;check_state: string | null;+ /**+ * A run on the workers: their measured time on its jobs (each job's last finished attempt, the one whose result was+ * kept), and the GPU of the last one (the workers' log).+ */+ exec_ms: number | null;+ exec_device: string | null;}/** Where a row stands in the output check, for its report: hidden, never checked in time, or nothing to say. */@@ -50,7 +56,10 @@ export function queueReports(now = Date.now(), limit = 200): number {.prepare(`SELECT g.id, g.status, g.error, g.outputs_json, g.external_id, g.cost_usd, g.completed_at,json_extract(g.request_json, '$.hold') AS hold, r.started_at AS started_at,- (SELECT state FROM output_checks c WHERE c.generation_id = g.id AND c.state IN ('hidden', 'unchecked') LIMIT 1) AS check_state+ (SELECT state FROM output_checks c WHERE c.generation_id = g.id AND c.state IN ('hidden', 'unchecked') LIMIT 1) AS check_state,+ (SELECT SUM(j.exec_ms) FROM worker_jobs j WHERE j.generation_id = g.id AND j.event = 'finished' AND j.exec_ms IS NOT NULL+ AND j.id = (SELECT MAX(k.id) FROM worker_jobs k WHERE k.task_id = j.task_id AND k.event = 'finished' AND k.exec_ms IS NOT NULL)) AS exec_ms,+ (SELECT j.device FROM worker_jobs j WHERE j.generation_id = g.id AND j.event = 'finished' AND j.device IS NOT NULL ORDER BY j.id DESC LIMIT 1) AS exec_deviceFROM generations g LEFT JOIN generation_runs r ON r.id = g.idWHERE json_extract(g.request_json, '$.hold') IS NOT NULLAND g.status IN ('succeeded', 'failed', 'canceled')@@ -66,7 +75,10 @@ export function queueReports(now = Date.now(), limit = 200): number {d.transaction(() => {for (const r of rows) {const n = (count.get(r.hold) as { n: number }).n;- const gpuMs = r.started_at && r.completed_at && r.completed_at > r.started_at ? r.completed_at - r.started_at : null;+ // A run on the workers: the time their ComfyUI spent on its jobs, as they measured it (no waits, no files, no+ // upload). Anything else: from its start to its end, as before.+ const gpuMs = r.exec_ms !== null ? r.exec_ms : r.started_at && r.completed_at && r.completed_at > r.started_at ? r.completed_at - r.started_at : null;+ const device = r.exec_device ?? null;const outputs = (() => {try {return JSON.parse(r.outputs_json) as { width?: number; height?: number }[];@@ -84,7 +96,7 @@ export function queueReports(now = Date.now(), limit = 200): number {final: { outputs: outputs.length, megapixels: megapixels(outputs), seconds: null },providerUsd: r.cost_usd,gpuMs,- device: null,+ device,reachedProvider: !!r.external_id,};written += insert.run(r.id, "settle", r.hold, JSON.stringify(report), now, now).changes;@@ -97,7 +109,7 @@ export function queueReports(now = Date.now(), limit = 200): number {reason: (r.error ?? "").slice(0, 500),reachedProvider: !!r.external_id,gpuMs,- device: null,+ device,};written += insert.run(r.id, "refund", r.hold, JSON.stringify(report), now, now).changes;}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex e3db034a..6092ac54 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -5,7 +5,7 @@ import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type Compuimport { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";import { loadIndex } from "../gpu/index-file";-import { cleanFacts, endTask, getTask, json, noteProgress, setPoolClocks, setTask, takeTask, type TaskRow } from "./tasks";+import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setTask, takeTask, taskById, type TaskRow } from "./tasks";import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";/**@@ -28,6 +28,15 @@ const FRESH_BEAT_MS = 30_000;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.+ */+const LINE_ORDER = "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";+/** 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;const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");@@ -164,6 +173,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatArunner: eligible(fresh, now),heldElsewhere: false,waiting,+ claimableNow: claimableNow(fresh, now),stops,worker: {paused: !!fresh.paused_server,@@ -180,6 +190,20 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA})();}+/**+ * People's tasks (an account's, never the owner's own) this worker may claim right now: in its pool, in a lane it is+ * allowed and able to run, with the files and VRAM they need, past their delays, and ending before its hours do. Its+ * own pause doesn't count here (its machine reads this to know whether a person's run waits for it); a pause on the website,+ * a drain or being outside its hours does.+ */+export function claimableNow(w: WorkerRow, now = Date.now()): number {+ if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || !hoursAt(hoursOf(w), now).inside) return 0;+ const rows = db()+ .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS NOT NULL AND INSTR(',' || pools || ',', ?) > 0 ORDER BY ${LINE_ORDER} LIMIT ?`)+ .all(`,${w.pool},`, LOOK_AT) as TaskRow[];+ return rows.filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;+}+// ---------------------------------------------------------------------------// Inventory@@ -222,10 +246,11 @@ export function inventoryHash(inv: Inventory): string {const LOOK_AT = 200;/**- * A worker asks for work, inside one transaction: first a task it had and lost track of; then, if it may take work, the- * best waiting task it can run (its pool, its allowed lanes and their delays, the files and VRAM it needs, the retry- * rule, and the end of its hours). Sticky lanes: its warm lane goes first until another lane's best task has waited- * longer than switch_after_ms (and is older).+ * A worker asks for work, inside one transaction: first a task it had and lost track of; then, if it holds none and may+ * take work, the best waiting task it can run (its pool, its allowed lanes and their delays, the files and VRAM it+ * needs, the retry rule, and the end of its hours). One task at a time: a worker that holds a task gets nothing new+ * until that one ends or goes back in line, so one worker's token never holds more than one person's job. Sticky+ * lanes: its warm lane goes first until another lane's best task has waited longer than switch_after_ms (and is older).*/export function workerClaim(w: WorkerRow, running: string[], now = Date.now()): ClaimedTask | null {const d = db();@@ -233,11 +258,10 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now()):return d.transaction((): ClaimedTask | null => {sweepPool(now);const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;- const mine = (d.prepare(`SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY rank_at`).all(fresh.id, device) as TaskRow[]).find(- (t) => !running.includes(t.id),- );+ const held = d.prepare(`SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY ${LINE_ORDER}`).all(fresh.id, device) as TaskRow[];+ const mine = held.find((t) => !running.includes(t.id));if (mine) return claimed(mine, fresh, device, now);- if (!eligible(fresh, now)) return null;+ if (held.length || !eligible(fresh, now)) return null;const t = pick(fresh, now);return t ? claimed(t, fresh, device, now) : null;})();@@ -246,7 +270,10 @@ 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 c = takeTask(t, device, now, { worker_id: w.id });+ 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.+ const c = takeTask(t, device, now, { worker_id: w.id, ...(t.state !== "waiting" && t.device === device && t.claimed_at && { claimed_at: t.claimed_at }) });return {...c,lane: t.lane ?? undefined,@@ -297,7 +324,7 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {function pick(w: WorkerRow, now: number): TaskRow | null {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 rank_at LIMIT ?")+ .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));if (!ok.length) return null;@@ -323,8 +350,10 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): voiendTask(t.id, "failed", { error: o.why ?? "The GPUs couldn't finish this run. Press Retry.", requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);return;}+ if (t.worker_id) logWorkerJob("requeued", t, t.worker_id);// A live worker that let it go hears the stop in its beat answer; one that went silent finds its lease gone when it- // comes back (409), and takes the prompt off its own ComfyUI.+ // comes back (409), and takes the prompt off its own ComfyUI. It keeps its rank, so it keeps its place in line, and+ // its wait limit no longer applies (a worker took it once).setTask(t.id, {state: "waiting",lease_hash: null,@@ -341,8 +370,10 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): voi}/**- * The workers' clocks: a task whose worker went silent for 2 minutes (or was revoked), or whose ComfyUI was down for 2- * minutes, goes back in line; a task still waiting past its wait limit fails, not charged.+ * The workers' clocks: a task whose worker went silent for 2 minutes (or was revoked), whose ComfyUI was down for 2+ * minutes, or that is still sending its files 15 minutes after the claim goes back in line; a task no worker has taken+ * yet that is still waiting past its wait limit fails, not charged. (Once a worker took it, the wait limit is over: a+ * task back in line waits in its place until a worker runs it, or its attempts run out.)*/export function sweepPool(now = Date.now()): void {const d = db();@@ -355,15 +386,18 @@ export function sweepPool(now = Date.now()): void {for (const t of held) {const silent = !t.w_seen || now - t.w_seen > RELAY_TIMES.poolSilentMs || !!t.w_revoked;const down = !!t.down_at && now - t.down_at > RELAY_TIMES.poolComfyDownMs;- if (silent || down) backInLine(t, { blame: true, why: silent ? "The GPU running this stopped answering, three times. Press Retry." : "ComfyUI kept stopping on the GPUs. Press Retry." });+ const stuck = t.state === "sending" && !!t.claimed_at && now - t.claimed_at > SENDING_MS;+ if (silent || down || stuck) {+ backInLine(t, { blame: true, why: silent ? "The GPU running this stopped answering, three times. Press Retry." : down ? "ComfyUI kept stopping on the GPUs. Press Retry." : "The GPUs couldn't start this run. Press Retry." });+ }}- const late = d.prepare("SELECT id FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND not_after IS NOT NULL AND not_after < ?").all(now) as { id: string }[];+ const late = d.prepare("SELECT id FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND claimed_at IS NULL AND not_after IS NOT NULL AND not_after < ?").all(now) as { id: string }[];for (const t of late) endTask(t.id, "failed", { error: "The GPUs were busy. Not charged." });}setPoolClocks((t, now) => {sweepPool(now);- return getTask(t.principal, t.id) ?? t;+ return taskById(t.id) ?? t;});// ---------------------------------------------------------------------------diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 6f256a77..1c1e9265 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -22,7 +22,7 @@ import {type TaskInput,type WantedFile,} from "@/lib/relay";-import { DATA_DIR, db } from "../db";+import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";/*** "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a@@ -166,6 +166,90 @@ export function getTask(principal: Principal, id: string): TaskRow | null {return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ?").get(id, principal) as TaskRow | undefined) ?? null;}+/** A task as it is now, by its id: the server's own read of a task it already holds. */+export const taskById = (id: string): TaskRow | null => (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow | undefined) ?? null;++/** What the workers' log says happened to a task. */+export type WorkerJobEvent = "claimed" | "finished" | "requeued" | "done" | "failed" | "canceled";++declare global {+ var __fuobeWorkerJobsPruned: number | undefined;+}++/**+ * Add a row to the workers' log (worker_jobs): which worker took which task, when, and what became of it, with the run's+ * measured time and device when the worker said them. Only ids, times and those facts: never a prompt, a file or an+ * account's details. Rows are never changed; each is kept a year, as the admin API's log is, then removed.+ */+export function logWorkerJob(event: WorkerJobEvent, t: Pick<TaskRow, "id" | "generation_id" | "principal" | "lane">, workerId: string | null, now = Date.now(), run: { execMs?: number; device?: string } = {}): void {+ try {+ const name = workerId ? ((rdb().prepare("SELECT name FROM relay_workers WHERE id = ?").get(workerId) as { name: string } | undefined)?.name ?? null) : null;+ rdb()+ .prepare("INSERT INTO worker_jobs (at, event, worker_id, worker_name, task_id, generation_id, principal, lane, exec_ms, device) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")+ .run(now, event, workerId, name, t.id, t.generation_id, t.principal, t.lane ?? null, run.execMs ?? null, run.device ?? null);+ if (now - (globalThis.__fuobeWorkerJobsPruned ?? 0) > 24 * 60 * 60_000) {+ globalThis.__fuobeWorkerJobsPruned = now;+ rdb().prepare("DELETE FROM worker_jobs WHERE at < ?").run(Date.now() - WORKER_JOBS_KEEP_MS - 60_000);+ }+ } catch (e) {+ console.warn(`[fuobe] Couldn't write the workers' log: ${(e as Error).message}`);+ }+}++/** A row of the workers' log as the owner reads it. */+export interface WorkerJobRow {+ id: number;+ at: number;+ event: WorkerJobEvent;+ workerId: string | null;+ workerName: string | null;+ taskId: string;+ generationId: string;+ principal: string;+ lane: string | null;+ execMs: number | null;+ device: string | null;+}++export interface WorkerJobQuery {+ limit: number;+ before?: number;+ worker?: string;+ generation?: string;+}++/** The workers' log query from a URL: `before` (a row id), `limit` (1 to 200, 50), `worker`, `generation`. */+export function workerJobsQueryFrom(sp: URLSearchParams): WorkerJobQuery | { error: string } {+ const before = sp.get("before");+ if (before !== null && !/^\d{1,15}$/.test(before)) return { error: "before is a row id" };+ const raw = sp.get("limit");+ const limit = raw === null ? 50 : Math.trunc(Number(raw));+ if (!Number.isFinite(limit) || limit < 1 || limit > 200) return { error: "limit is 1 to 200" };+ const worker = sp.get("worker");+ if (worker !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(worker)) return { error: "worker is a worker id" };+ const generation = sp.get("generation");+ if (generation !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(generation)) return { error: "generation is a run id" };+ return { limit, ...(before !== null && { before: Number(before) }), ...(worker !== null && { worker }), ...(generation !== null && { generation }) };+}++/** The workers' log, newest first; `next` is the last row's id (pass it as `before`), null on the last page. */+export function listWorkerJobs(q: WorkerJobQuery): { items: WorkerJobRow[]; next: string | null } {+ const filters: [string, string | number | undefined][] = [+ ["id < ?", q.before],+ ["worker_id = ?", q.worker],+ ["generation_id = ?", q.generation],+ ];+ const used = filters.filter((f): f is [string, string | number] => f[1] !== undefined);+ const where = used.length ? `WHERE ${used.map((f) => f[0]).join(" AND ")}` : "";+ const rows = rdb()+ .prepare(`SELECT * FROM worker_jobs ${where} ORDER BY id DESC LIMIT ?`)+ .all(...used.map((f) => f[1]), q.limit) as { id: number; at: number; event: WorkerJobEvent; worker_id: string | null; worker_name: string | null; task_id: string; generation_id: string; principal: string; lane: string | null; exec_ms: number | null; device: string | null }[];+ return {+ items: rows.map((r) => ({ id: r.id, at: r.at, event: r.event, workerId: r.worker_id, workerName: r.worker_name, taskId: r.task_id, generationId: r.generation_id, principal: r.principal, lane: r.lane, execMs: r.exec_ms, device: r.device })),+ next: rows.length === q.limit ? String(rows[rows.length - 1].id) : null,+ };+}+/** The pools that may take a task (none: a browser computer's). */export const poolsOf = (t: Pick<TaskRow, "pools">): string[] => (t.pools ? t.pools.split(",").filter(Boolean) : []);@@ -479,9 +563,11 @@ export function inputFor(t: TaskRow, n: number): { path: string; size: number; c* computer's ComfyUI is taken off it there (the computer hears it at its next beat): a cancel, or a timeout.*/export function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {- const t = rdb().prepare("SELECT state, device FROM relay_tasks WHERE id = ?").get(id) as { state: RelayState; device: string | null } | undefined;+ const t = taskById(id);const stop = takeOff && t && t.device && (SENT_STATES as readonly string[]).includes(t.state) ? 1 : 0;setTask(id, { state, finished_at: Date.now(), down_at: null, down_why: null, ...(stop && { stop }), ...fields });+ // A task a worker held ends: the workers' log says how.+ if (t?.pools && t.worker_id && (ACTIVE_STATES as readonly string[]).includes(t.state)) logWorkerJob(state, t, t.worker_id);progressMap().delete(id);for (const i of rdb().prepare("SELECT name FROM relay_inputs WHERE task_id = ?").all(id) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });rdb().prepare("DELETE FROM relay_inputs WHERE task_id = ?").run(id);@@ -531,7 +617,7 @@ export interface ReportAnswer {*/export function report(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now = Date.now()): ReportAnswer {const a = reportOnce(t, e, plan, now);- return { ...a, state: getTask(t.principal, t.id)?.state ?? t.state };+ return { ...a, state: taskById(t.id)?.state ?? t.state };}function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now: number): ReportAnswer {@@ -598,7 +684,8 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike}case "gone":if (t.attempts < 2 && t.state !== "sending") {- setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null });+ // A worker's task sends its files again: its sending clock (pool.ts SENDING_MS) starts again too.+ setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null, ...(t.pools && { claimed_at: now }) });rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);return { ok: true };}@@ -677,7 +764,7 @@ export async function receivePart(const bytes = o.offset + got.bytes;const done = bytes === o.total;if (done) fs.renameSync(part, file);- const fresh = getTask(t.principal, t.id);+ const fresh = taskById(t.id);const list = json<Received[]>(fresh?.received_json ?? null, all).map((r) => (r.n === n ? { n, bytes, total: o.total, done, ...(contentType && { contentType }) } : r));setTask(t.id, { received_json: JSON.stringify(list), device_seen_at: Date.now() });if (list.every((r) => r.done)) endTask(t.id, "done");@@ -792,7 +879,7 @@ export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {if (t.device_seen_at && now - t.device_seen_at > RELAY_TIMES.silentMs) endTask(t.id, "failed", { error: "silent" }, true);else if (t.down_at && now - t.down_at > RELAY_TIMES.comfyDownMs) endTask(t.id, "failed", { error: "down" }, true);else return t;- return getTask(t.principal, t.id) ?? t;+ return taskById(t.id) ?? t;}/** A task for workers keeps the workers' clocks (pool.ts sets this, so this file needn't import it). */diff --git a/src/server/db.ts b/src/server/db.tsindex 26a7c25b..ade9b442 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -699,11 +699,15 @@ export const MIGRATIONS: string[] = [/** The place of the sign-in tables' migration in MIGRATIONS (27). */const AUTH_MIGRATION = MIGRATIONS.indexOf(AUTH_TABLES);+/** How long the workers' log keeps a row (as long as the admin API's log). */+export const WORKER_JOBS_KEEP_MS = 365 * 24 * 60 * 60_000;+/*** "Use the ComfyUI on this computer" (src/server/computer/tasks.ts). relay_runners: each principal's computer (the one* that runs its waiting jobs, until its lease lapses) and what its tab said about its ComfyUI. relay_tasks: one per* ComfyUI job of a run on someone's computer, with the graph as the server built it and where the job is. relay_inputs:- * the files staged for a job, under the names ComfyUI gets. Safe to run on every start.+ * the files staged for a job, under the names ComfyUI gets. worker_jobs: which worker took which task and when, and what+ * became of it (rows are only added; each is kept a year, like the admin API's log). Safe to run on every start.*/export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (principal TEXT PRIMARY KEY,@@ -807,7 +811,27 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (state TEXT NOT NULL DEFAULT 'waiting',principal TEXT,worker_id TEXT- );`;+ );+ CREATE TABLE IF NOT EXISTS worker_jobs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ at INTEGER NOT NULL,+ event TEXT NOT NULL,+ worker_id TEXT,+ worker_name TEXT,+ task_id TEXT NOT NULL,+ generation_id TEXT NOT NULL,+ principal TEXT NOT NULL,+ lane TEXT,+ exec_ms INTEGER,+ device TEXT+ );+ 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 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}+ BEGIN SELECT RAISE(ABORT, 'worker_jobs rows are kept a year'); END;`;/*** The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and releasediff --git a/tests/worker-queue.test.ts b/tests/worker-queue.test.tsnew file mode 100644index 00000000..a9fca99b--- /dev/null+++ b/tests/worker-queue.test.ts@@ -0,0 +1,256 @@+import crypto from "node:crypto";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";++/**+ * The workers' line keeps its own rules, whoever a job belongs to: a worker holds one job at a time; a job still sending+ * its files long after the claim goes back in line; a job back in line keeps its place, and its wait limit is over once+ * a worker took it; the beat says how many people's jobs a worker may take now. The workers' log keeps which worker ran+ * which job, and a run's report to the billing service carries the time the workers measured.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-worker-queue-");+process.env.FUOBE_DATA_DIR = dir;+// Nothing answers here: no test may reach a real ComfyUI on this machine.+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_BILLING_URL;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { setSetting } = await import("@/server/settings");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const { queueReports } = await import("@/server/billing-outbox");+const { loadManifest } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");++const HOST = "localhost:3000";+const MIN = 60_000;+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++let accountId = "";+let cookie = "";++beforeAll(() => {+ auth.setPassword("install password");+ accountId = auth.createAccount("[email protected]", "long enough").id;+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;+});+beforeEach(() => {+ setSetting("comfyWhere", "workers");+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+});++/** A worker the owner added and resumed, allowed every lane, able to run every workflow. */+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;+}++/** An account's job made straight in the line (no run route). */+let gens = 0;+function accountTask(o: { rankAt?: number; notAfter?: number } = {}) {+ const gid = `queue-gen-${++gens}`;+ const now = Date.now();+ 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({ account: accountId, place: "pool" }), now, now);+ const t = tasks.createTask({+ principal: `acct:${accountId}`,+ generationId: gid,+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },+ pool: { pools: ["pool"], account: accountId, rankAt: o.rankAt ?? now, lane: allLanes(loadIndex(), sha)[0]?.lane ?? "small", needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 }, notAfter: o.notAfter },+ });+ return { id: t.id, generationId: gid };+}++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 rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;+const beatAs = (w: { id: string }, now = Date.now(), local: { paused: boolean; why: string | null } = { paused: false, why: null }, running: { task: string }[] = []) =>+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { ...local, until: null }, gpu: {}, inventoryHash: null, running, stopped: [] }), now);+const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);++describe("one job at a time", () => {+ it("a stolen worker token holds at most one task; one stuck sending its files goes back in line", () => {+ const w = standInWorker();+ const a = accountTask({ rankAt: Date.now() - 2 * MIN });+ const b = accountTask({ rankAt: Date.now() - MIN });+ beatAs(w);+ expect(claimAs(w)?.id).toBe(a.id);+ // Asking again while it holds one: nothing new, whether or not it says it is running it.+ expect(claimAs(w, [a.id])).toBeNull();+ expect(claimAs(w, [])?.id).toBe(a.id);+ expect(rowOf(b.id).state).toBe("waiting");+ // Still sending its files 15 minutes after the claim: back in line (a lost attempt), and b goes next.+ const later = Date.now() + pool.SENDING_MS + MIN;+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(later, w.id);+ pool.sweepPool(later);+ expect(rowOf(a.id).state).toBe("waiting");+ expect(rowOf(a.id).requeues).toBe(1);+ });++ it("a worker that asks again for its own task never winds the sending clock back", () => {+ const w = standInWorker();+ const a = accountTask();+ const t0 = Date.now();+ beatAs(w, t0);+ expect(claimAs(w, [], t0)?.id).toBe(a.id);+ const first = rowOf(a.id).claimed_at;+ // Lost track of it a minute on: the same task, with its first claim's time.+ beatAs(w, t0 + MIN);+ expect(claimAs(w, [], t0 + MIN)?.id).toBe(a.id);+ expect(rowOf(a.id).claimed_at).toBe(first);+ // Still sending its files 15 minutes after that first claim, from a worker that beats on: back in line.+ const late = t0 + pool.SENDING_MS + MIN;+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(late, w.id);+ pool.sweepPool(late);+ expect(rowOf(a.id).state).toBe("waiting");+ expect(rowOf(a.id).requeues).toBe(1);+ });++ it("a job its ComfyUI lost while it ran sends again with a fresh sending clock", () => {+ const w = standInWorker();+ const a = accountTask();+ const t0 = Date.now();+ beatAs(w, t0);+ expect(claimAs(w, [], t0)?.id).toBe(a.id);+ tasks.setTask(a.id, { state: "running", sent_at: t0 + MIN, attempts: 1 });+ // Twenty minutes in, its ComfyUI restarted and lost the job: the worker sends it again.+ const gone = t0 + 20 * MIN;+ tasks.report(rowOf(a.id), { event: "gone" }, () => ({ error: "unused" }), gone);+ expect(rowOf(a.id).state).toBe("sending");+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(gone + MIN, w.id);+ pool.sweepPool(gone + MIN);+ expect(rowOf(a.id).state).toBe("sending");+ expect(rowOf(a.id).requeues).toBe(0);+ });+});++describe("back in line", () => {+ it("a requeue keeps the job's place (rank_at), and once a worker took it, its wait limit is over", () => {+ const w = standInWorker();+ const first = accountTask({ rankAt: Date.now() - 5 * MIN, notAfter: Date.now() + MIN });+ const later = accountTask({ rankAt: Date.now() });+ const rank = rowOf(first.id).rank_at;+ beatAs(w);+ expect(claimAs(w)?.id).toBe(first.id);+ // The worker pauses at once (another program on the GPU): the job goes back in line at no cost.+ beatAs(w, Date.now(), { paused: true, why: "gpu-busy:game.exe" }, [{ task: first.id }]);+ const back = rowOf(first.id);+ expect(back.state).toBe("waiting");+ expect(back.rank_at).toBe(rank);+ expect(back.requeues).toBe(0);+ // First in line again, ahead of the later job, and past its wait limit it still waits.+ expect(pool.queueOfGeneration(first.generationId)?.place).toBe(1);+ expect(pool.queueOfGeneration(later.generationId)?.place).toBe(2);+ pool.sweepPool(Date.now() + 10 * MIN);+ expect(rowOf(first.id).state).toBe("waiting");+ // A job no worker has taken yet still fails at its wait limit, not charged.+ const never = accountTask({ notAfter: Date.now() + MIN });+ pool.sweepPool(Date.now() + 2 * MIN);+ expect(rowOf(never.id).state).toBe("failed");+ });+});++describe("the beat", () => {+ it("says how many people's tasks this worker may claim now (never the owner's own)", () => {+ const w = standInWorker();+ accountTask();+ accountTask();+ const owner = accountTask();+ db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL WHERE id = ?").run(owner.id);+ expect(beatAs(w).claimableNow).toBe(2);+ pool.patchWorker(w.id, { paused: true });+ expect(beatAs(w).claimableNow).toBe(0);+ });+});++describe("the workers' measured run reaches the billing service", () => {+ it("settle carries the time the worker's ComfyUI spent on the run and its GPU's name", () => {+ const now = Date.now();+ const t = accountTask();+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${t.id}` }), t.generationId);+ tasks.logWorkerJob("finished", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-1", now, { execMs: 12_345, device: "Test GPU 24GB" });+ queueReports(now);+ const row = db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").get(t.generationId) as { payload_json: string };+ const report = JSON.parse(row.payload_json) as { gpuMs: number; device: string };+ expect(report.gpuMs).toBe(12_345);+ expect(report.device).toBe("Test GPU 24GB");+ });++ it("a job that went back in line after its result was made counts once: the attempt whose result was kept", () => {+ const now = Date.now();+ const t = accountTask();+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${t.id}` }), t.generationId);+ const row = { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}` as const, lane: "small" };+ tasks.logWorkerJob("finished", row, "w-1", now - 5 * MIN, { execMs: 50_000, device: "Test GPU A" });+ tasks.logWorkerJob("requeued", row, "w-1", now - 4 * MIN);+ tasks.logWorkerJob("finished", row, "w-2", now - MIN, { execMs: 40_000, device: "Test GPU B" });+ // A second job of the same run adds its own time.+ tasks.logWorkerJob("finished", { ...row, id: "second-job-0001x" }, "w-2", now, { execMs: 2_000, device: "Test GPU B" });+ queueReports(now);+ const report = JSON.parse((db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").get(t.generationId) as { payload_json: string }).payload_json) as { gpuMs: number; device: string };+ expect(report.gpuMs).toBe(42_000);+ expect(report.device).toBe("Test GPU B");+ });+});++describe("the workers' log", () => {+ it("only grows", () => {+ const t = accountTask();+ tasks.logWorkerJob("claimed", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: null }, "w-2");+ expect(() => db().prepare("UPDATE worker_jobs SET event = 'done' WHERE task_id = ?").run(t.id)).toThrow(/only grows/);+ expect(() => db().prepare("DELETE FROM worker_jobs WHERE task_id = ?").run(t.id)).toThrow(/kept a year/);+ });++ it("keeps a claim, a requeue and how the job ended, by worker", () => {+ const w = standInWorker("logged");+ const a = accountTask();+ beatAs(w);+ expect(claimAs(w)?.id).toBe(a.id);+ beatAs(w, Date.now(), { paused: true, why: "here-now" }, [{ task: a.id }]);+ pool.patchWorker(w.id, { paused: false });+ beatAs(w);+ expect(claimAs(w)?.id).toBe(a.id);+ tasks.endTask(a.id, "canceled", { error: "Stopped" });+ const log = db().prepare("SELECT event, worker_id, worker_name, principal FROM worker_jobs WHERE task_id = ? ORDER BY id").all(a.id) as { event: string; worker_id: string; worker_name: string; principal: string }[];+ expect(log.map((x) => x.event)).toEqual(["claimed", "requeued", "claimed", "canceled"]);+ expect(log.every((x) => x.worker_id === w.id && x.worker_name === "logged" && x.principal === `acct:${accountId}`)).toBe(true);+ });++ it("lists who took which job, newest first, for the owner or a token that may read the workers", async () => {+ const jobsRoute = await import("@/app/api/admin/workers/jobs/route");+ const { createAdminToken } = await import("@/server/admin-tokens");+ const t = accountTask();+ tasks.logWorkerJob("claimed", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-log-1");+ tasks.logWorkerJob("finished", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-log-1", Date.now(), { execMs: 4321, device: "Test GPU" });+ const get = (qs: string, headers: Record<string, string>) => jobsRoute.GET(new Request(`http://${HOST}/api/admin/workers/jobs${qs}`, { headers: { host: HOST, ...headers } }));+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const res = await get(`?generation=${t.generationId}`, { cookie: owner });+ expect(res.status).toBe(200);+ const page = (await res.json()) as { items: { event: string; workerId: string; execMs: number | null; device: string | null }[]; next: string | null };+ expect(page.items.map((x) => x.event)).toEqual(["finished", "claimed"]);+ expect(page.items[0]).toMatchObject({ workerId: "w-log-1", execMs: 4321, device: "Test GPU" });+ expect(JSON.stringify(page)).not.toContain("example.com");+ // An account's session, or a token that may not read the workers: no.+ expect((await get("", { cookie })).status).toBeGreaterThanOrEqual(401);+ const reader = createAdminToken({ name: "workers reader", scopes: ["workers:read"] });+ expect((await get("?limit=1", { authorization: `Bearer ${reader.token}` })).status).toBe(200);+ const other = createAdminToken({ name: "queue reader", scopes: ["queue:read"] });+ expect((await get("", { authorization: `Bearer ${other.token}` })).status).toBe(403);+ expect((await get("?limit=0", { cookie: owner })).status).toBe(400);+ });+});