Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Workers: a timeline of each worker's state changes, handoffs, stages and log lines

Adarshafebbe836db9
diff --git a/docs/admin-api.md b/docs/admin-api.md
index e8f5686b..a739886f 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 only with `accounts:read`) |
-| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs` |
+| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/events` |
| `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`, `GET /api/admin/queue/settings` |
@@ -117,10 +117,11 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000), `pausedBudgetS` (seconds, 0 to 604800) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane |
| `GET /api/admin/site/uploads` | | `{ switches: { soundConvert, soundTrim, videoTrim, photoConvert, photoCrop } }`: what a browser may do to a file that doesn't fit a tool before it is uploaded (convert a sound to MP3, offer a part of a sound or clip, convert or shrink a photo, offer a crop). All `true` by default. Every visitor reads the same values at `GET /api/site/uploads` |
| `PATCH /api/admin/site/uploads` | any of the five, each `true` or `false` | `{ switches }`; 400 with the reason for an unknown switch or a value that isn't a boolean. A switch that is off leaves that kind of file as it is: the tool says why it can't take it, and the server's checks apply. Browsers pick it up when they next load a page |
-| `GET /api/admin/workers` | | `{ workers, lanes }` |
+| `GET /api/admin/workers` | | `{ workers, lanes }`. Each worker adds `asked: { at, words }` or null, `jobs` (each job it holds: `{ taskId, generationId, slot, lane, laneLabel, stage, state, claimedAt, startedAt, progress, progressAt, typicalMs, etaS, owners, feature?, modelName? }`) and `lastEvent: { at, kind, event, words }` or null |
| `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/events` | `worker`, `kinds` (a comma list of `state`, `job`, `stage`, `looking`, `admin`, `version`, `log`; all when not given), `before`, `after`, `generation`, `limit` (1 to 500, 100) | `{ items, next, latest }`: the workers' timeline, newest first. Each item: `{ id, at, workerId, workerName, kind, event, words, taskId, generationId, lane, laneLabel, state, detail }`. `next` pages back (as `before`); `latest` is the newest row id (as `after`, for new rows only) ([gpu-workers.md](gpu-workers.md)) |
| `GET /api/admin/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner`, `token` or `system`), `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/gpu-workers.md b/docs/gpu-workers.md
index 762c4414..5ccaf090 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -469,6 +469,14 @@ median of the workers' measured runs). The billing service's line facts (`QueueF
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)).
+**The workers' timeline.** `worker_events` keeps what each worker did, one row per change: `state` (its state changed;
+`detail.from` is the one before, and `offline` comes when it went silent), `job` (beside each row of the workers' log,
+in words: "Took a … run", "Sent back in line: went silent", "Delivered after 42 s"), `stage` (its job's stage:
+`sending`, `queued`, `loading`, `running`, `saving`), `looking` (the answer to its claims changed: `found`, `nothing` or
+`blocked`), `admin` (an action from the admin API, with who in `detail.by`), `version` (its program was updated) and
+`log` (its own log lines, from its beat). Log lines are kept 7 days, the rest 30 days. The owner reads it at
+`GET /api/admin/workers/events` ([admin-api.md](admin-api.md)).
+
### Job tickets and the PC's ceiling
An account's run reaches a worker as a job ticket, never as a graph. The ticket names a workflow of the catalog, the
@@ -824,7 +832,7 @@ within 10 minutes of each other, each write an alert to the admin log (`worker.a
its target), at most once an hour each.
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,
- until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling?, holding? }`. The answer
+ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling?, holding?, log? }`. The answer
adds `worker: { paused, pauseNow, drain, autoResume, insideHours, nextChangeAt, lanes, lanesInside, minProtocol,
sendInventory, token?, tokenExpiresAt?, catalogVersion? }` (`token`: the next token, above; `tokenExpiresAt`: when
the token ends, for a token with a lifetime; `lanesInside`: the allowed lanes inside the PC's ceiling;
@@ -833,6 +841,11 @@ its target), at most once an hour each.
waits that it could take: `starting-comfy`, `waiting-for-yield`, `local-work` (the owner's job waits for local
ComfyUI work to finish), `gpu-check`, `updating` (it restarts on new code after its job) or `sending-kept`;
`task` names a job it took that waits. A beat without it clears it. Older workers don't send it.
+ - `log: [{ at, level, line }]` (optional): the worker's own log lines since the last beat the studio answered with a
+ 2xx, oldest first, at most 40 lines of 300 characters (`level`: `info`, `warn` or `error`). The worker keeps the last
+ 200 lines and drops them once a beat that carried them gets a 2xx. Both sides mask each line: no tokens, keys,
+ bearer strings or emails, no full file paths (a model file keeps its name, anything else reads `[file]`), and URLs
+ without their query. Older studios ignore it.
- `catalogVersion` and `ceiling` say the catalog its build composes job tickets for and what its PC may ever run
(see "Job tickets and the PC's ceiling"). The facts it sends with its ComfyUI's add `gpuGen`, its GPU's
generation (compute capability), when nvidia-smi can say.
@@ -917,7 +930,10 @@ Each worker counts against its own rate limits, so three workers that beat every
- `GET /api/admin/workers` and `POST /api/admin/workers` (`{ name, pool? }`; the answer shows the token once). Each
worker shows its PC's `ceiling`, the allowed lanes inside it (`lanesInside`), its `catalogVersion` and whether that
is the studio's (`catalogCurrent`). Its state is `update-worker` while it is built from another catalog and accounts'
- runs may come to the install's GPUs.
+ runs may come to the install's GPUs. `asked` is its last claim for its GPU and the answer in words, `jobs` every job it
+ holds now in either slot (stage, progress, typical run and ETA; `current` stays its GPU's job), and `lastEvent` the
+ newest row of its timeline other than a log line.
+- `GET /api/admin/workers/events`: the workers' timeline (above), newest first, by worker, kinds and run, in pages.
- `PATCH /api/admin/workers/<id>`: `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs,
rotate, revoke }`. Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.
A window can go past midnight.
diff --git a/src/app/api/admin/workers/[id]/route.ts b/src/app/api/admin/workers/[id]/route.ts
index b4f47a29..a4b535fe 100644
--- a/src/app/api/admin/workers/[id]/route.ts
+++ b/src/app/api/admin/workers/[id]/route.ts
@@ -25,7 +25,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/work
const action = body.revoke ? "worker.revoke" : body.rotate ? "worker.rotate" : "worker.change";
const keys = KEYS.filter((k) => k in body);
try {
- const r = patchWorker(id, body);
+ const r = patchWorker(id, body, Date.now(), access.actor.kind === "token" ? access.actor.name : "owner");
if (!r.view && !body.revoke) {
audit(access.actor, action, id, { keys }, 404);
return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
diff --git a/src/app/api/admin/workers/events/route.ts b/src/app/api/admin/workers/events/route.ts
new file mode 100644
index 00000000..7cb13d19
--- /dev/null
+++ b/src/app/api/admin/workers/events/route.ts
@@ -0,0 +1,23 @@
+import { connection } from "next/server";
+import { adminAccess } from "@/server/admin-tokens";
+import { noteSilentWorkers } from "@/server/computer/pool";
+import { listWorkerEvents, workerEventsQueryFrom } from "@/server/computer/worker-events";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * The workers' timeline, newest first (owner only, or an admin token with workers:read; docs/gpu-workers.md): state
+ * changes, jobs taken, sent back and delivered, stages, answers to claims, admin actions, version changes and each
+ * worker's own log lines. `worker=<id>`, `kinds=state,job,stage,looking,admin,version,log` (any of them; all when not
+ * given), `before=<id>` (older rows: the `next` of the last page), `after=<id>` (only newer rows: the `latest` of the
+ * last answer), `generation=<run id>`, `limit` (1 to 500, 100 when not given).
+ */
+export async function GET(request: Request) {
+ await connection();
+ const access = adminAccess(request, "workers:read", "Only the studio's owner sees the workers' timeline");
+ if (access instanceof Response) return access;
+ const q = workerEventsQueryFrom(new URL(request.url).searchParams);
+ if ("error" in q) return Response.json({ error: q.error }, { status: 400, headers: NO_STORE });
+ noteSilentWorkers();
+ return Response.json(listWorkerEvents(q), { headers: NO_STORE });
+}
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 7ecfb5dd..0d1d4704 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -288,8 +288,23 @@ export interface WorkerBeat {
* is an older worker program): one of HOLDING_WHY's keys, since when, and the task it took, if it holds one.
*/
holding?: WorkerHolding | null;
+ /**
+ * Its own log lines since the last beat the studio answered with a 2xx, oldest first, masked on the PC and again by the
+ * studio (src/server/computer/worker-events.ts). At most WORKER_LOG_LIMITS.perBeat lines of lineChars characters.
+ */
+ log?: WorkerLogLine[];
}
+/** A worker's log line in its beat. */
+export interface WorkerLogLine {
+ at: number;
+ level: "info" | "warn" | "error";
+ line: string;
+}
+
+/** The caps on a beat's `log`: lines per beat, characters per line. */
+export const WORKER_LOG_LIMITS = { perBeat: 40, lineChars: 300 } as const;
+
/** A worker's `holding` in its beat. */
export interface WorkerHolding {
why: string;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index ee22bc4c..2b3aa99e 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -12,9 +12,11 @@ import { loadIndex } from "../gpu/index-file";
import { hostedRunsOn } from "../hosted-switch";
import { heldView } from "../pool-holds";
import { catalogVersion } from "./catalog-version";
-import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, taskCold, type TaskRow } from "./tasks";
+import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, noteStage, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, stageOf, takeTask, taskById, taskCold, taskProgress, type TaskRow } from "./tasks";
import { queueSettings, runCeilingMs } from "../queue-settings";
import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
+import { modelLabel } from "./queue-live";
+import { cleanLogLines, lastEventOf, lastOfKind, logWorkerEvent, logWorkerEvents, setEventNames, type NewWorkerEvent, type WorkerEventKind } from "./worker-events";
/**
* Workers (docs/gpu-workers.md): the owner's GPUs on other machines, each running `fuobe worker`, which pulls jobs from
@@ -258,6 +260,8 @@ export function cleanBeat(b: unknown): WorkerBeat {
cpuSlot: cleanCpuSlot(o.cpuSlot),
cpuRunning: Array.isArray(o.cpuRunning) ? (o.cpuRunning.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],
...(cleanHolding(o.holding) && { holding: cleanHolding(o.holding) }),
+ // Its own log lines, masked again here (worker-events.ts); an older worker sends none.
+ ...(Array.isArray(o.log) && o.log.length > 0 && { log: cleanLogLines(o.log) }),
};
}
@@ -284,6 +288,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
return d.transaction(() => {
// A worker back after going silent finds its task back in line first (its lease no longer works).
sweepPool(now);
+ // Its saved state and version before this beat: a timeline row only when either changes.
+ const before = d.prepare("SELECT state, version FROM relay_workers WHERE id = ?").get(w.id) as Pick<WorkerRow, "state" | "version"> | undefined;
const facts = b.facts ? { ...b.facts, loras: undefined } : undefined;
d.prepare(
`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,
@@ -330,18 +336,28 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
const held = new Set(b.held ?? []);
// Another program on its GPU stops only its GPU's job: its CPU slot's task needs no GPU, and goes on.
const gpuOnly = !fresh.stop_now && b.local.why !== "here-now";
+ const sentBack = fresh.stop_now ? "paused now on the website" : b.local.why === "here-now" ? "paused now on its PC" : "another program took its GPU";
for (const t of d.prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(w.id) as TaskRow[]) {
if (gpuOnly && t.device === slotDevice(w, "cpu")) continue;
// Its result is being saved, or the worker keeps the finished results on its disk (the studio may not have heard
// that it finished): let it send them, which needs no GPU, instead of running the job again.
if (t.state === "collecting" || held.has(t.id)) continue;
- backInLine(t, { blame: false });
+ backInLine(t, { blame: false, sentBack });
stops.push({ task: t.id, promptId: t.prompt_id, ...(t.prefix && { prefix: t.prefix }) });
}
d.prepare("UPDATE relay_workers SET stop_now = 0 WHERE id = ?").run(w.id);
}
const state = workerState(fresh, now);
- d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(state.state, w.id);
+ if (state.state !== before?.state) {
+ d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(state.state, w.id);
+ logWorkerEvent({ kind: "state", event: state.state, workerId: w.id, words: state.words, state: state.state, detail: { from: before?.state ?? null } }, now);
+ }
+ // Best-effort from here: the timeline never fails a beat.
+ const rows: NewWorkerEvent[] = [];
+ if (before?.version && b.version && before.version !== b.version) rows.push({ kind: "version", event: "updated", workerId: w.id, words: `Worker program updated to ${b.version}`, detail: { from: before.version, to: b.version } });
+ // Its PC's clock may run ahead of the studio's: never later than now.
+ for (const l of b.log ?? []) rows.push({ kind: "log", event: l.level, workerId: w.id, words: l.line, at: Math.min(l.at, now) });
+ logWorkerEvents(rows, now);
// A worker that says it saves a new token (`canRotateToken` in its beat) gets its next one when half its token's life
// is gone. (Not by its protocol number: a worker may speak a newer protocol without saving tokens.)
const nextToken = b.canRotateToken ? offerNextToken(fresh, now) : null;
@@ -506,12 +522,43 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), s
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 (held.length || !eligible(fresh, now)) return null;
- const t = pick(fresh, now, slot);
+ if (held.length) return null;
+ if (!eligible(fresh, now)) {
+ if (slot === "gpu") noteAsked(fresh, "blocked", `Asked for work: not taking work (${blockedWhy(fresh, now)})`, now);
+ return null;
+ }
+ const { task: t, looked } = pick(fresh, now, slot);
+ const many = `${looked}${looked >= LOOK_AT ? "+" : ""}`;
+ if (slot === "gpu") noteAsked(fresh, t ? "found" : "nothing", t ? `Asked for work: took 1 of ${many} waiting` : looked ? `Asked for work: ${many} waiting, none it can run now` : "Asked for work: nothing waiting", now, { waiting: looked });
return t ? claimed(t, fresh, device, now) : null;
}).immediate();
}
+/** Why a worker may not take work now, in a few words (its claim's answer). */
+function blockedWhy(w: WorkerRow, now: number): string {
+ if (w.revoked_at || (w.expires_at && w.expires_at <= now)) return "its token no longer works";
+ if (w.paused_server) return "paused on the website";
+ if (w.paused_local) return "paused on its PC";
+ if (w.drain) return "draining";
+ if ((w.protocol ?? 0) < MIN_PROTOCOL) return "its worker program is too old";
+ if (!w.seen_at || now - w.seen_at > FRESH_BEAT_MS) return "no recent beat";
+ if (!hoursAt(hoursOf(w), now).inside) return "outside its hours";
+ return "not taking work";
+}
+
+/**
+ * A claim of its GPU's slot and its answer: saved on the worker (asked_at, asked_words) at every claim, and a `looking`
+ * row when the answer differs from its last one (found, nothing, or blocked for another reason). Best-effort.
+ */
+function noteAsked(w: WorkerRow, answer: "found" | "nothing" | "blocked", words: string, now: number, detail: Record<string, unknown> = {}): void {
+ try {
+ db().prepare("UPDATE relay_workers SET asked_at = ?, asked_words = ? WHERE id = ?").run(now, words, w.id);
+ const last = lastOfKind(w.id, "looking");
+ if (last && last.event === answer && (answer !== "blocked" || last.words === words)) return;
+ logWorkerEvent({ kind: "looking", event: answer, workerId: w.id, words, detail }, now);
+ } catch {}
+}
+
function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {
const needs = json<Needs | null>(t.needs_json, null);
const bench = t.lane ? benchOf(w)[t.lane] : undefined;
@@ -526,6 +573,7 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed
// A GPU job taken by a worker with another model loaded (or none) loads its model first: it is "getting ready" until
// its first step reports. A light CPU job and a finishing job load none.
if (t.state === "waiting" && t.pools && t.slot !== "cpu" && !t.finish_json && !!t.lane && w.warm_lane !== t.lane) noteCold(t.id, now);
+ if (t.state === "waiting") noteStage(t.id, now, { slot: device.endsWith("-cpu") ? "cpu" : "gpu" }, true);
// A job given back once for running past its limit gets the whole run ceiling on its next try (a lane's times may
// come from shorter jobs than this one); past that, it fails. Light CPU work has the same limits in either slot. A
// finishing job has its lane's run ceiling (queue-settings.ts, the owner's to set).
@@ -612,19 +660,20 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
* the best one, in the same class, while the best one has waited less than the pick allowance (the install's setting,
* capped by this worker's switch_after_ms; 0: strict order).
*/
-function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): TaskRow | null {
+function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: TaskRow | null; looked: number } {
const settings = queueSettings(now);
// Each slot looks only at its own tasks.
const rows = db()
.prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, slot)}ORDER BY ${LINE_ORDER} LIMIT ?`)
.all(`,${w.pool},`, LOOK_AT) as TaskRow[];
+ const looked = rows.length;
const ok = lineOrder(rows, settings.fairShare).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
- if (!ok.length) return null;
+ if (!ok.length) return { task: null, looked };
const best = ok[0];
const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
- if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return best;
+ if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return { task: best, looked };
const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === classRank(best));
- return warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best;
+ return { task: warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best, looked };
}
/**
@@ -705,7 +754,7 @@ const OWNER_STOP_WORDS = {
other: "The GPUs couldn't finish this run. Press Retry.",
};
-export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; whyKind?: "silent" | "down" | "stuck"; last?: boolean; lostAt?: number }): boolean {
+export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; whyKind?: "silent" | "down" | "stuck"; last?: boolean; lostAt?: number; sentBack?: string }): boolean {
const d = db();
return d.transaction((): boolean => {
const now = taskById(t.id);
@@ -716,7 +765,7 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; whyKin
endTask(t.id, "failed", { error: o.why ?? stoppedWords(o.whyKind ?? "other", requeues), requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);
return true;
}
- if (t.worker_id) logWorkerJob("requeued", t, t.worker_id);
+ if (t.worker_id) logWorkerJob("requeued", t, t.worker_id, Date.now(), {}, { ...(o.sentBack && { why: o.sentBack }), tries: requeues });
// 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. It keeps its rank, so it keeps its place in line, and
// its wait limit no longer applies (a worker took it once).
@@ -770,11 +819,32 @@ function sweepLine(d: ReturnType<typeof db>, now: number): void {
const sendingSince = t.sending_since ?? t.claimed_at;
const stuck = t.state === "sending" && !!sendingSince && now - sendingSince > SENDING_MS;
if (silent || down || stuck) {
- backInLine(t, { blame: true, whyKind: silent ? "silent" : down ? "down" : "stuck", ...(silent && !t.w_revoked && { lostAt: now }) });
+ const sentBack = t.w_revoked ? "its token was revoked" : silent ? "went silent" : down ? "its ComfyUI stopped answering" : "still sending its files after 15 min";
+ backInLine(t, { blame: true, whyKind: silent ? "silent" : down ? "down" : "stuck", sentBack, ...(silent && !t.w_revoked && { lostAt: now }) });
}
}
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: ENGINE_WORDS["long-wait"] });
+ noteSilentWorkers(now);
+}
+
+/**
+ * Workers silent past the silence limit whose saved state isn't "offline" yet: saved as offline, with a state row (at
+ * the moment the limit passed). A look at the few rows of relay_workers. Best-effort.
+ */
+export function noteSilentWorkers(now = Date.now()): void {
+ try {
+ const d = db();
+ const gone = d
+ .prepare("SELECT id, state, seen_at FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND seen_at IS NOT NULL AND seen_at < ? AND state != 'offline'")
+ .all(now - RELAY_TIMES.poolSilentMs) as Pick<WorkerRow, "id" | "state" | "seen_at">[];
+ for (const w of gone) {
+ if (d.prepare("UPDATE relay_workers SET state = 'offline' WHERE id = ? AND state = ?").run(w.id, w.state).changes === 0) continue;
+ logWorkerEvent({ kind: "state", event: "offline", workerId: w.id, words: "Offline", state: "offline", detail: { from: w.state, seenAt: w.seen_at }, at: Math.min(now, w.seen_at! + RELAY_TIMES.poolSilentMs) }, now);
+ }
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't note silent workers: ${(e as Error).message}`);
+ }
}
/** The longest sleep a worker's beat may report (a week). */
@@ -844,25 +914,34 @@ setPoolGiveBack((t, why) => {
const { claimedBefore, claimFor, ...rest } = json<Record<string, unknown>>(t.extra_json, {});
const extra = { ...rest, refusedBy: [...new Set([...refusedBy(t), ...(w ? [refusalKey(w)] : [])])].slice(-64) };
const untouched = typeof claimFor === "number" && claimFor === t.claimed_at && t.state === "sending" && !t.sent_at && !t.started_at;
- if (!backInLine(t, untouched ? { blame: false } : { blame: true, why: GAVE_BACK_WORDS })) return;
+ const sentBack = why === "update-worker" ? "its ticket is for another catalog than the worker's" : "more than its PC runs";
+ if (!backInLine(t, untouched ? { blame: false, sentBack } : { blame: true, why: GAVE_BACK_WORDS, sentBack })) return;
if (taskById(t.id)?.state !== "waiting") return;
setTask(t.id, { extra_json: JSON.stringify(extra), ...(untouched && { claimed_at: typeof claimedBefore === "number" ? claimedBefore : null }) });
})
.immediate();
return;
}
+ const sentBack = GIVE_BACK_WORDS[why] ?? "the worker gave it back";
if (why === "run-limit") {
- if (runLimitedOf(t)) return backInLine(t, { blame: true, why: GAVE_BACK_WORDS, last: true });
+ if (runLimitedOf(t)) return backInLine(t, { blame: true, why: GAVE_BACK_WORDS, last: true, sentBack });
setTask(t.id, { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), runLimited: true }) });
}
- backInLine(t, { blame: true, why: GAVE_BACK_WORDS });
+ backInLine(t, { blame: true, why: GAVE_BACK_WORDS, sentBack });
});
/**
* A worker's ComfyUI lost its task twice on one claim (each loss sends it again once): it goes back in line with its
* place kept, and counts as an attempt, so another worker is preferred and the third attempt fails it.
*/
-setPoolLost((t) => backInLine(t, { blame: true }));
+setPoolLost((t) => backInLine(t, { blame: true, sentBack: "its ComfyUI lost it twice" }));
+
+/** Why a worker gave a job back, in the timeline's words. */
+const GIVE_BACK_WORDS: Record<string, string> = {
+ stalled: "it stalled",
+ "run-limit": "it ran past its run limit",
+ media: "the worker can't make its clips or sound again",
+};
// ---------------------------------------------------------------------------
// Place in line and the wait (4.4)
@@ -1318,6 +1397,76 @@ export interface WorkerView {
lastCountry: string | null;
createdAt: number;
current: { taskId: string; generationId: string; lane: string | null; startedAt: number | null } | null;
+ /** Its last claim for its GPU's slot and the answer in words (null: none yet). */
+ asked: { at: number; words: string } | null;
+ /** Every task it holds now, in both slots, the oldest claim first. */
+ jobs: ActiveJob[];
+ /** Its timeline's newest row other than a log line (null: none). */
+ lastEvent: { at: number; kind: WorkerEventKind; event: string; words: string | null } | null;
+}
+
+/** A task a worker holds now: where it is, and how long it should take. No prompt, no account's details. */
+export interface ActiveJob {
+ taskId: string;
+ generationId: string;
+ slot: WorkerSlot;
+ lane: string | null;
+ laneLabel: string | null;
+ stage: string | null;
+ state: string;
+ claimedAt: number | null;
+ startedAt: number | null;
+ progress: { value?: number; max?: number; node?: string; nodesDone?: number; position?: number; cold?: boolean } | null;
+ progressAt: number | null;
+ /** How long a job like it takes on this worker (its lane's bench, the task's estimate, or the lane's typical run). */
+ typicalMs: number | null;
+ /** About how long until it is done, from typicalMs and its start (null: unknown). */
+ etaS: number | null;
+ owners: "owner" | "account";
+ feature?: string;
+ modelName?: string;
+}
+
+/** A lane's label from the catalog's lanes (worked out once per index). */
+export const laneLabelOf = (lane: string | null | undefined): string | null => {
+ if (!lane) return null;
+ return catalogLanes().lanes.find((l) => l.lane === lane)?.label ?? (lane === "small" ? "Small jobs" : lane);
+};
+
+setEventNames({
+ lane: laneLabelOf,
+ run: (generationId) => modelLabel((db().prepare("SELECT model_id FROM generations WHERE id = ?").get(generationId) as { model_id: string } | undefined)?.model_id),
+});
+
+type ActiveRow = Pick<TaskRow, "id" | "generation_id" | "lane" | "state" | "device" | "slot" | "finish_json" | "claimed_at" | "started_at" | "progress_json" | "account" | "est_ms">;
+
+function activeJobs(w: WorkerRow, rows: ActiveRow[], now: number, typical: (lane: string | null) => number | null): ActiveJob[] {
+ const gen = db().prepare("SELECT feature, model_id FROM generations WHERE id = ?");
+ return rows.map((t) => {
+ const p = taskProgress(t);
+ const typicalMs = estOn(t as TaskRow, w) ?? typical(t.lane);
+ const g = gen.get(t.generation_id) as { feature: string | null; model_id: string | null } | undefined;
+ const model = modelLabel(g?.model_id);
+ const progress = p ? Object.fromEntries((["value", "max", "node", "nodesDone", "position", "cold"] as const).filter((k) => p[k] !== undefined).map((k) => [k, p[k]])) : null;
+ return {
+ taskId: t.id,
+ generationId: t.generation_id,
+ slot: t.device?.endsWith("-cpu") ? "cpu" : "gpu",
+ lane: t.lane,
+ laneLabel: laneLabelOf(t.lane),
+ stage: stageOf(t),
+ state: t.state,
+ claimedAt: t.claimed_at,
+ startedAt: t.started_at,
+ progress,
+ progressAt: p?.at ?? null,
+ typicalMs,
+ etaS: typicalMs ? Math.max(0, Math.round(((t.started_at ?? now) + typicalMs - now) / 1000)) : null,
+ owners: t.account ? "account" : "owner",
+ ...(g?.feature && { feature: g.feature }),
+ ...(model && { modelName: model }),
+ };
+ });
}
/** The packs a worker said its ComfyUI didn't load, each with the workflows that need one of those classes. */
@@ -1336,11 +1485,13 @@ export function unloadedPacks(inv: Inventory): WorkerView["unloaded"] {
.sort((a, b) => a.pack.localeCompare(b.pack));
}
-export function workerView(w: WorkerRow, now = Date.now()): WorkerView {
+export function workerView(w: WorkerRow, now = Date.now(), typical: (lane: string | null) => number | null = memo(typicalPoolMs)): WorkerView {
const s = workerState(w, now);
- const cur = db().prepare("SELECT id, generation_id, lane, started_at FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting') LIMIT 1").get(w.id) as
- | { id: string; generation_id: string; lane: string | null; started_at: number | null }
- | undefined;
+ const held = db()
+ .prepare("SELECT id, generation_id, lane, state, device, slot, finish_json, claimed_at, started_at, progress_json, account, est_ms FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting') ORDER BY claimed_at, id")
+ .all(w.id) as ActiveRow[];
+ // `current` as before: its GPU's job (else its only job).
+ const cur = held.find((t) => !t.device?.endsWith("-cpu")) ?? held[0];
return {
id: w.id,
name: w.name,
@@ -1372,11 +1523,17 @@ export function workerView(w: WorkerRow, now = Date.now()): WorkerView {
lastCountry: w.last_country,
createdAt: w.created_at,
current: cur ? { taskId: cur.id, generationId: cur.generation_id, lane: cur.lane, startedAt: cur.started_at } : null,
+ asked: w.asked_at && w.asked_words ? { at: w.asked_at, words: w.asked_words } : null,
+ jobs: activeJobs(w, held, now, typical),
+ lastEvent: lastEventOf(w.id),
};
}
export function listWorkers(now = Date.now()): WorkerView[] {
- return (db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL ORDER BY created_at").all() as WorkerRow[]).map((w) => workerView(w, now));
+ // A worker that went silent shows as offline in its timeline too, even when nothing else swept the line since.
+ noteSilentWorkers(now);
+ const typical = memo(typicalPoolMs);
+ return (db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL ORDER BY created_at").all() as WorkerRow[]).map((w) => workerView(w, now, typical));
}
/** Add a worker: paused on the website, with no hours and no lanes. Its token is shown once. */
@@ -1405,7 +1562,7 @@ export interface WorkerPatch {
/** A worker's token stops at once, and its tasks go back in line at once (not the worker's fault). */
function revokePoolWorker(id: string, now: number): void {
revokeWorker(id, now);
- for (const t of db().prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(id) as TaskRow[]) backInLine(t, { blame: false });
+ for (const t of db().prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(id) as TaskRow[]) backInLine(t, { blame: false, sentBack: "its token was revoked" });
}
/**
@@ -1416,18 +1573,22 @@ export function revokeAllWorkers(now = Date.now()): number {
const d = db();
return d.transaction(() => {
const ids = (d.prepare("SELECT id FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as { id: string }[]).map((r) => r.id);
- for (const id of ids) revokePoolWorker(id, now);
+ for (const id of ids) {
+ revokePoolWorker(id, now);
+ noteAdmin(id, [["revoke", "Token revoked: everyone was signed out"]], "owner", now);
+ }
return ids.length;
})();
}
/** The owner changes a worker. Each change reaches it at its next beat. */
-export function patchWorker(id: string, p: WorkerPatch, now = Date.now()): { view: WorkerView | null; token?: string } {
+export function patchWorker(id: string, p: WorkerPatch, now = Date.now(), by = "owner"): { view: WorkerView | null; token?: string } {
const d = db();
const w = d.prepare("SELECT * FROM relay_workers WHERE id = ? AND kind = 'pool' AND revoked_at IS NULL").get(id) as WorkerRow | undefined;
if (!w) return { view: null };
if (p.revoke) {
revokePoolWorker(id, now);
+ noteAdmin(id, [["revoke", "Token revoked"]], by, now);
return { view: null };
}
const set: Record<string, unknown> = {};
@@ -1461,9 +1622,35 @@ export function patchWorker(id: string, p: WorkerPatch, now = Date.now()): { vie
if (keys.length) d.prepare(`UPDATE relay_workers SET ${keys.map((k) => `${k} = @${k}`).join(", ")} WHERE id = @id`).run({ ...set, id });
const token = p.rotate ? rotateWorker(id) ?? undefined : undefined;
const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as WorkerRow;
+ // The timeline: each action (an edit names its keys, never a value), then the state it leads to when it changed.
+ const actions: [string, string, Record<string, unknown>?][] = [];
+ if (p.pauseNow) actions.push(["pause-now", "Paused now on the website: its jobs go back in line"]);
+ else if (p.paused === true) actions.push(["pause", "Paused on the website"]);
+ if (p.paused === false) actions.push(["resume", "Resumed on the website"]);
+ if (p.drain === true) actions.push(["drain", "Set to finish its job, then pause"]);
+ else if (p.drain === false) actions.push(["undrain", "No longer pausing after its job"]);
+ const edited = (["autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs"] as const).filter((k) => p[k] !== undefined);
+ if (edited.length) actions.push(["edit", `Settings changed: ${edited.join(", ")}`, { keys: edited }]);
+ if (token) actions.push(["rotate", "New token made"]);
+ noteAdmin(id, actions, by, now);
+ try {
+ const s = workerState(fresh, now);
+ if (s.state !== fresh.state && fresh.seen_at) {
+ d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(s.state, id);
+ logWorkerEvent({ kind: "state", event: s.state, workerId: id, words: s.words, state: s.state, detail: { from: fresh.state, by } }, now);
+ }
+ } catch {}
return { view: workerView(fresh, now), ...(token && { token }) };
}
+/** Admin actions in a worker's timeline, with who did them ("owner" or the admin token's name). Best-effort. */
+function noteAdmin(id: string, actions: [string, string, Record<string, unknown>?][], by: string, now: number): void {
+ logWorkerEvents(
+ actions.map(([event, words, detail]) => ({ kind: "admin", event, workerId: id, words, detail: { by, ...detail } })),
+ now,
+ );
+}
+
/**
* The line for workers by lane: waiting, oldest, the estimate, and which workers have it warm. `held`: the runs made but
* waiting to enter the line (pool-holds.ts), by why they wait, and when the oldest was pressed: counts only (no prompt,
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 338b5792..bd896c63 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -30,6 +30,7 @@ import type { JobTicket } from "@/lib/job-ticket";
import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";
import { runCeilingMs } from "../queue-settings";
import { hostedRunsOn } from "../hosted-switch";
+import { jobWords, lastStage, logWorkerEvent, type JobStage } from "./worker-events";
/**
* "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a
@@ -220,7 +221,14 @@ declare global {
* 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 {
+export function logWorkerJob(
+ event: WorkerJobEvent,
+ t: Pick<TaskRow, "id" | "generation_id" | "principal" | "lane"> & Partial<Pick<TaskRow, "claimed_at" | "finish_json">>,
+ workerId: string | null,
+ now = Date.now(),
+ run: { execMs?: number; device?: string } = {},
+ info: { why?: string; tries?: number } = {},
+): void {
try {
const name = workerId ? ((rdb().prepare("SELECT name FROM relay_workers WHERE id = ?").get(workerId) as { name: string } | undefined)?.name ?? null) : null;
rdb()
@@ -233,8 +241,70 @@ export function logWorkerJob(event: WorkerJobEvent, t: Pick<TaskRow, "id" | "gen
} catch (e) {
console.warn(`[fuobe] Couldn't write the workers' log: ${(e as Error).message}`);
}
+ // The same handoff in the worker's timeline, in words (best-effort, as above).
+ const detail = { ...(run.execMs !== undefined && { execMs: run.execMs }), ...(run.device && { device: run.device }), ...(info.why && { why: info.why }), ...(info.tries !== undefined && { tries: info.tries }) };
+ logWorkerEvent(
+ { kind: "job", event, workerId, words: jobWords(event, t, { execMs: run.execMs, why: info.why, now }), taskId: t.id, generationId: t.generation_id, lane: t.lane ?? null, detail },
+ now,
+ );
}
+/** The stage of a worker's job, from its state and progress (null: it isn't with a worker now). */
+export function stageOf(t: Pick<TaskRow, "state" | "progress_json">): JobStage | null {
+ switch (t.state) {
+ case "sending":
+ return "sending";
+ case "queued":
+ return "queued";
+ case "running":
+ return taskCold(t) ? "loading" : "running";
+ case "collecting":
+ return "saving";
+ default:
+ return null;
+ }
+}
+
+/**
+ * A worker's task may have moved to another stage (a report, its first step): a stage row when it differs from the
+ * task's last one on this attempt (`fresh`: a new attempt, always a row). Called at state changes only, never on every
+ * progress report. Best-effort.
+ */
+export function noteStage(id: string, now = Date.now(), detail: Record<string, unknown> = {}, fresh = false): void {
+ try {
+ const t = rdb().prepare("SELECT id, generation_id, lane, state, progress_json, pools, worker_id, claimed_at FROM relay_tasks WHERE id = ?").get(id) as
+ | Pick<TaskRow, "id" | "generation_id" | "lane" | "state" | "progress_json" | "pools" | "worker_id" | "claimed_at">
+ | undefined;
+ if (!t?.pools || !t.worker_id) return;
+ const stage = stageOf(t);
+ if (!stage) return;
+ const last = fresh ? null : lastStage(t.id);
+ if (last && last.event === stage && last.workerId === t.worker_id && last.at >= (t.claimed_at ?? 0)) return;
+ const p = taskProgress(t);
+ logWorkerEvent(
+ {
+ kind: "stage",
+ event: stage,
+ workerId: t.worker_id,
+ words: STAGE_WORDS[stage],
+ taskId: t.id,
+ generationId: t.generation_id,
+ lane: t.lane,
+ detail: { ...detail, ...(stage === "queued" && p?.position !== undefined && { position: p.position }) },
+ },
+ now,
+ );
+ } catch {}
+}
+
+const STAGE_WORDS: Record<JobStage, string> = {
+ sending: "Sending its files to its ComfyUI",
+ queued: "In its ComfyUI's queue",
+ loading: "Loading the model",
+ running: "Running",
+ saving: "Saving the results",
+};
+
/** A row of the workers' log as the owner reads it. */
export interface WorkerJobRow {
id: number;
@@ -578,14 +648,18 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
const node = str(r.node, 64);
if (node) p.node = node;
const d = rdb();
- d.transaction(() => {
- const cur = d.prepare(`SELECT progress_json FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json"> | undefined;
- if (!cur) return;
+ const warmed = d.transaction((): boolean => {
+ const cur = d.prepare(`SELECT progress_json, state FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json" | "state"> | undefined;
+ if (!cur) return false;
const next = { ...taskProgress(cur), ...p };
// Its first step reported: its model is loaded (noteCold), so it is no longer getting ready.
+ const wasCold = next.cold === true;
if (p.value !== undefined) delete next.cold;
d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify(next), id, lease);
+ return wasCold && next.cold !== true && cur.state === "running";
}).immediate();
+ // Loading the model → running: a stage row.
+ if (warmed) noteStage(id, now);
}
/**
@@ -821,7 +895,7 @@ export function endTask(id: string, state: "done" | "failed" | "canceled", field
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);
+ if (t?.pools && t.worker_id && (ACTIVE_STATES as readonly string[]).includes(t.state)) logWorkerJob(state, t, t.worker_id, Date.now(), {}, typeof fields.error === "string" ? { why: fields.error } : {});
dropProgress(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);
@@ -888,6 +962,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
// Results a worker kept from an earlier try go up instead of a new render. Each send counts toward this claim's
// sends all the same, so a ComfyUI that "loses" a job twice on one claim (a resend after each) sends it back in line.
setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + 1 });
+ if (t.pools) noteStage(t.id, now);
return { ok: true };
}
case "refused":
@@ -904,11 +979,14 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
// A worker's live preview of the job: the tile shows the latest one while the run works. Kept only from a progress
// report of the attempt that holds the lease, for a run that shows them (notePreview, showsPreview).
if (e.preview) notePreview({ ...(taskById(t.id) ?? t), lease_hash: t.lease_hash }, e.preview, now);
+ // Its ComfyUI started it: loading its model (taken cold) or running. Later reports change no stage here.
+ if (t.pools && t.state !== "running") noteStage(t.id, now);
return { ok: true };
case "finished":
case "passes": {
if (e.event === "passes" && e.running) {
setTask(t.id, { ...seen, state: "running" });
+ if (t.pools && t.state !== "running") noteStage(t.id, now);
return { ok: true };
}
const entries = e.event === "finished" ? [e.entry] : e.entries;
@@ -944,6 +1022,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
received_json: JSON.stringify(received),
extra_json: JSON.stringify({ ...extraOf(t), budget: p.budget }),
});
+ if (t.pools) noteStage(t.id, now, { files: p.wanted.length });
return { ok: true, wanted: p.wanted };
}
case "give-back":
@@ -958,6 +1037,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null, ...(t.pools && { sending_since: now }) });
dropProgress(t.id);
rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ if (t.pools) noteStage(t.id, now, { resent: true });
return { ok: true };
}
if (t.state === "sending") return { ok: true };
diff --git a/src/server/computer/worker-events.ts b/src/server/computer/worker-events.ts
new file mode 100644
index 00000000..026cfd1b
--- /dev/null
+++ b/src/server/computer/worker-events.ts
@@ -0,0 +1,375 @@
+import "server-only";
+import { WORKER_LOG_LIMITS, type WorkerLogLine } from "@/lib/relay";
+import { db } from "../db";
+
+/**
+ * Each worker's timeline (worker_events, GET /api/admin/workers/events): its state changes, the jobs it took, sent back
+ * and delivered, the stages of its active job, the answers to its claims, admin actions, its program's version and its
+ * own log lines. Rows are only added, each on a change (never once per beat). Ids, times, plain words and small facts:
+ * never a prompt, a token or an account's details. Every write is best-effort: a failure never fails a beat, a claim or
+ * a report.
+ */
+
+export const EVENT_KINDS = ["state", "job", "stage", "looking", "admin", "version", "log"] as const;
+export type WorkerEventKind = (typeof EVENT_KINDS)[number];
+
+/** How long rows are kept: log lines a week, everything else 30 days. */
+export const EVENTS_KEEP_MS = 30 * 24 * 60 * 60_000;
+export const LOG_KEEP_MS = 7 * 24 * 60 * 60_000;
+
+/** The stage of a worker's active job. */
+export type JobStage = "sending" | "queued" | "loading" | "running" | "saving";
+
+export interface NewWorkerEvent {
+ kind: WorkerEventKind;
+ event: string;
+ workerId: string | null;
+ words?: string | null;
+ taskId?: string | null;
+ generationId?: string | null;
+ lane?: string | null;
+ /** The worker's state then (default: its saved state). */
+ state?: string | null;
+ detail?: Record<string, unknown> | null;
+ at?: number;
+}
+
+/** A row as the admin API answers it. */
+export interface WorkerEvent {
+ id: number;
+ at: number;
+ workerId: string | null;
+ workerName: string | null;
+ kind: WorkerEventKind;
+ event: string;
+ words: string | null;
+ taskId: string | null;
+ generationId: string | null;
+ lane: string | null;
+ laneLabel: string | null;
+ state: string | null;
+ detail: Record<string, unknown> | null;
+}
+
+/** Names for a lane and for a run's model, set by pool.ts (which knows the catalog). */
+let names: { lane: (lane: string) => string | null; run: (generationId: string) => string | null } = { lane: () => null, run: () => null };
+export const setEventNames = (n: typeof names) => (names = n);
+export const laneName = (lane: string | null | undefined): string | null => {
+ if (!lane) return null;
+ try {
+ return names.lane(lane);
+ } catch {
+ return null;
+ }
+};
+const runName = (generationId: string | null | undefined): string | null => {
+ if (!generationId) return null;
+ try {
+ return names.run(generationId);
+ } catch {
+ return null;
+ }
+};
+
+declare global {
+ var __fuobeWorkerEventsPruned: number | undefined;
+}
+
+const cap = (s: string | null | undefined, n: number) => (typeof s === "string" && s ? (s.length > n ? `${s.slice(0, n - 1)}…` : s) : null);
+
+/** Add rows to worker_events (best-effort). Each row's worker name and state are read once per worker. Returns the last id. */
+export function logWorkerEvents(rows: NewWorkerEvent[], now = Date.now()): number | null {
+ if (!rows.length) return null;
+ try {
+ const d = db();
+ const ins = d.prepare("INSERT INTO worker_events (at, worker_id, worker_name, kind, event, words, task_id, generation_id, lane, state, detail_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ const seen = new Map<string, { name: string | null; state: string | null }>();
+ const who = (id: string) => {
+ let w = seen.get(id);
+ if (!w) {
+ const r = d.prepare("SELECT name, state FROM relay_workers WHERE id = ?").get(id) as { name: string; state: string } | undefined;
+ w = { name: r?.name ?? null, state: r?.state ?? null };
+ seen.set(id, w);
+ }
+ return w;
+ };
+ let last: number | null = null;
+ for (const e of rows) {
+ const w = e.workerId ? who(e.workerId) : { name: null, state: null };
+ const detail = e.detail && Object.keys(e.detail).length ? JSON.stringify(e.detail) : null;
+ last = Number(
+ ins.run(
+ e.at ?? now,
+ e.workerId,
+ w.name,
+ e.kind,
+ e.event.slice(0, 32),
+ cap(e.words, e.kind === "log" ? WORKER_LOG_LIMITS.lineChars : 500),
+ e.taskId ?? null,
+ e.generationId ?? null,
+ e.lane ?? null,
+ e.state === undefined ? w.state : e.state,
+ detail && detail.length <= 2000 ? detail : null,
+ ).lastInsertRowid,
+ );
+ }
+ if (now - (globalThis.__fuobeWorkerEventsPruned ?? 0) > 24 * 60 * 60_000) {
+ globalThis.__fuobeWorkerEventsPruned = now;
+ pruneWorkerEvents(now);
+ }
+ return last;
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't write a worker's timeline: ${(e as Error).message}`);
+ return null;
+ }
+}
+
+export const logWorkerEvent = (e: NewWorkerEvent, now = Date.now()) => logWorkerEvents([e], now);
+
+/** Remove log lines older than a week and every other row older than 30 days. */
+export function pruneWorkerEvents(now = Date.now()): void {
+ try {
+ const d = db();
+ d.prepare("DELETE FROM worker_events WHERE at < ?").run(now - EVENTS_KEEP_MS);
+ d.prepare("DELETE FROM worker_events WHERE kind = 'log' AND at < ?").run(now - LOG_KEEP_MS);
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't prune the workers' timeline: ${(e as Error).message}`);
+ }
+}
+
+/** The last row of one kind for a worker (an indexed read), or null. */
+export function lastOfKind(workerId: string, kind: WorkerEventKind): { event: string; words: string | null; at: number } | null {
+ try {
+ return (db().prepare("SELECT event, words, at FROM worker_events WHERE worker_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(workerId, kind) as { event: string; words: string | null; at: number } | undefined) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** The last stage row of a task, or null. */
+export function lastStage(taskId: string): { event: string; workerId: string | null; at: number } | null {
+ try {
+ const r = db().prepare("SELECT event, worker_id, at FROM worker_events WHERE task_id = ? AND kind = 'stage' ORDER BY id DESC LIMIT 1").get(taskId) as { event: string; worker_id: string | null; at: number } | undefined;
+ return r ? { event: r.event, workerId: r.worker_id, at: r.at } : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A worker's latest row other than a log line (the newest of each kind's last row), or null. */
+export function lastEventOf(workerId: string): { at: number; kind: WorkerEventKind; event: string; words: string | null } | null {
+ try {
+ const q = db().prepare("SELECT id, at, kind, event, words FROM worker_events WHERE worker_id = ? AND kind = ? ORDER BY id DESC LIMIT 1");
+ let best: { id: number; at: number; kind: WorkerEventKind; event: string; words: string | null } | undefined;
+ for (const k of EVENT_KINDS) {
+ if (k === "log") continue;
+ const r = q.get(workerId, k) as typeof best;
+ if (r && (!best || r.id > best.id)) best = r;
+ }
+ return best ? { at: best.at, kind: best.kind, event: best.event, words: best.words } : null;
+ } catch {
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Job rows: the words beside each worker_jobs row
+
+const secs = (ms: number) => (ms < 90_000 ? `${Math.max(1, Math.round(ms / 1000))} s` : `${Math.round(ms / 60_000)} min`);
+
+/** A job row's words: "Took a Flux 2 run", "Sent back in line: went silent", "Delivered after 42 s". */
+export function jobWords(
+ event: string,
+ t: { generation_id?: string | null; lane?: string | null; claimed_at?: number | null; finish_json?: string | null },
+ o: { execMs?: number; why?: string; now: number },
+): string {
+ const what = t.finish_json ? "finishing job" : `${runName(t.generation_id) ?? laneName(t.lane) ?? "job"} run`.replace(/^job run$/, "job");
+ switch (event) {
+ case "claimed":
+ return `Took a ${what}`;
+ case "requeued":
+ return `Sent back in line${o.why ? `: ${o.why}` : ""}`;
+ case "finished":
+ return o.execMs ? `Finished on its ComfyUI in ${secs(o.execMs)}` : "Finished on its ComfyUI";
+ case "done":
+ return t.claimed_at ? `Delivered after ${secs(Math.max(0, o.now - t.claimed_at))}` : "Delivered";
+ case "failed":
+ return `Failed${o.why ? `: ${o.why}` : ""}`;
+ case "canceled":
+ return "Stopped";
+ default:
+ return event;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Log lines: masked again here, whatever the worker did
+
+const MODEL_FILE = /\.(safetensors|sft|ckpt|pt|pth|bin|gguf|onnx|pkl)$/i;
+const MODEL_NAME = /[\w.-]+\.(safetensors|sft|ckpt|pt|pth|bin|gguf|onnx|pkl)\b/gi;
+const fileWord = (p: string) => {
+ const base = p.split(/[\\/]/).filter(Boolean).pop() ?? "";
+ return MODEL_FILE.test(base) ? base : "[file]";
+};
+const LONG_TOKEN = /[A-Za-z0-9_-]{32,}/g;
+const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>()[\]\u0000]+/gi;
+const KEY_RE = /\b(token|api[_-]?key|key|secret|password|passwd|pwd|authorization|auth|cookie|session)(\s*[:=]\s*)(?!Bearer\b)("[^"]*"|'[^']*'|[^\s"',;]+)/gi;
+const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
+const WIN_PATH = /(?:\b[A-Za-z]:|\\\\[^\\\s\u0000]+)[\\/](?:[^\\/:*?"<>|\u0000\r\n]*[^\\/:*?"<>|\u0000\s][\\/])*[^\\/:*?"<>|()\s\u0000]*/g;
+const POSIX_PATH = /(^|[\s("'=,[])(~?\/(?:[^/\s"'<>()\u0000]+\/)*[^/\s"'<>()\u0000]+)/g;
+const JWT = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
+
+function cleanUrl(u: string): string {
+ try {
+ const x = new URL(u);
+ return `${x.protocol}//${x.host}${x.pathname.replace(LONG_TOKEN, "[hidden]")}${x.search || x.hash ? "?[hidden]" : ""}`;
+ } catch {
+ return "[url]";
+ }
+}
+
+/**
+ * A log line as it may be kept: no tokens, keys or bearer strings, no emails, no full file paths (a model file keeps
+ * its base name, anything else is "[file]"), URLs without their query, long quoted text hidden, one line of at most
+ * `max` characters. The worker program does the same (bin/lib/worker/log-ring.mjs maskLine).
+ */
+export function maskLogLine(raw: unknown, max: number = WORKER_LOG_LIMITS.lineChars): string {
+ if (typeof raw !== "string") return "";
+ let s = raw.slice(0, 2000).replace(/\x1b\[[0-9;]*[A-Za-z]/g, "").replace(/[\x00-\x1f\x7f]/g, " ");
+ // What is already safe (a cleaned URL, a file's word, a model file's name) waits aside, so later rules leave it.
+ const kept: string[] = [];
+ const keep = (v: string) => `\u0000${kept.push(v) - 1}\u0000`;
+ s = s.replace(URL_RE, (u) => keep(cleanUrl(u)));
+ s = s.replace(/\bBearer\s+[^\s"',;]+/gi, "Bearer [hidden]");
+ s = s.replace(KEY_RE, "$1$2[hidden]");
+ s = s.replace(EMAIL_RE, "[email]");
+ s = s.replace(WIN_PATH, (p) => keep(fileWord(p)));
+ s = s.replace(POSIX_PATH, (_m, pre: string, p: string) => pre + keep(fileWord(p)));
+ s = s.replace(MODEL_NAME, (m) => keep(m));
+ s = s.replace(JWT, "[hidden]");
+ s = s.replace(LONG_TOKEN, "[hidden]");
+ s = s.replace(/"[^"]{60,}"/g, '"[text]"');
+ s = s.replace(/\u0000(\d+)\u0000/g, (_m, i: string) => kept[Number(i)] ?? "[hidden]");
+ s = s.replace(/\s+/g, " ").trim();
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
+}
+
+const LEVELS = new Set(["info", "warn", "error"]);
+
+/** A beat's `log` as it may be kept: at most perBeat lines, each masked, its time never later than `now`. */
+export function cleanLogLines(v: unknown, now = Infinity): WorkerLogLine[] {
+ if (!Array.isArray(v)) return [];
+ const out: WorkerLogLine[] = [];
+ for (const x of v.slice(0, WORKER_LOG_LIMITS.perBeat)) {
+ const o = (x && typeof x === "object" ? x : {}) as Record<string, unknown>;
+ const line = maskLogLine(o.line);
+ if (!line) continue;
+ const at = typeof o.at === "number" && Number.isFinite(o.at) && o.at > 0 ? Math.min(o.at, now) : Math.min(Date.now(), now);
+ out.push({ at, level: (LEVELS.has(o.level as string) ? o.level : "info") as WorkerLogLine["level"], line });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// GET /api/admin/workers/events
+
+export interface WorkerEventQuery {
+ limit: number;
+ before?: number;
+ after?: number;
+ worker?: string;
+ generation?: string;
+ kinds?: WorkerEventKind[];
+}
+
+/**
+ * The timeline query from a URL: `worker`, `kinds` (a comma list of EVENT_KINDS; all when not given), `before` and
+ * `after` (row ids), `generation` (a run id), `limit` (1 to 500, 100 when not given).
+ */
+export function workerEventsQueryFrom(sp: URLSearchParams): WorkerEventQuery | { error: string } {
+ const id = (k: string) => {
+ const v = sp.get(k);
+ return v === null ? undefined : /^\d{1,15}$/.test(v) ? Number(v) : null;
+ };
+ const before = id("before");
+ if (before === null) return { error: "before is a row id" };
+ const after = id("after");
+ if (after === null) return { error: "after is a row id" };
+ const raw = sp.get("limit");
+ const limit = raw === null ? 100 : Math.trunc(Number(raw));
+ if (!Number.isFinite(limit) || limit < 1 || limit > 500) return { error: "limit is 1 to 500" };
+ 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" };
+ const k = sp.get("kinds");
+ let kinds: WorkerEventKind[] | undefined;
+ if (k !== null && k.trim() !== "") {
+ const list = [...new Set(k.split(",").map((x) => x.trim()).filter(Boolean))];
+ const bad = list.find((x) => !(EVENT_KINDS as readonly string[]).includes(x));
+ if (bad) return { error: `kinds are ${EVENT_KINDS.join(", ")}` };
+ kinds = list as WorkerEventKind[];
+ }
+ return {
+ limit,
+ ...(before !== undefined && { before }),
+ ...(after !== undefined && { after }),
+ ...(worker !== null && { worker }),
+ ...(generation !== null && { generation }),
+ ...(kinds && { kinds }),
+ };
+}
+
+type EventRowDb = { id: number; at: number; worker_id: string | null; worker_name: string | null; kind: WorkerEventKind; event: string; words: string | null; task_id: string | null; generation_id: string | null; lane: string | null; state: string | null; detail_json: string | null };
+
+const parseDetail = (s: string | null): Record<string, unknown> | null => {
+ if (!s) return null;
+ try {
+ const v = JSON.parse(s) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * The timeline, newest first. `next`: the last row's id when the page is full (pass it as `before`; with `after` too, it
+ * fills the gap), else null. `latest`: the newest row id of the whole timeline (pass it as `after` to poll), 0 when empty.
+ */
+export function listWorkerEvents(q: WorkerEventQuery): { items: WorkerEvent[]; next: string | null; latest: number } {
+ const filters: [string, unknown[]][] = [];
+ if (q.before !== undefined) filters.push(["id < ?", [q.before]]);
+ if (q.after !== undefined) filters.push(["id > ?", [q.after]]);
+ if (q.worker !== undefined) filters.push(["worker_id = ?", [q.worker]]);
+ if (q.generation !== undefined) filters.push(["generation_id = ?", [q.generation]]);
+ if (q.kinds?.length && q.kinds.length < EVENT_KINDS.length) filters.push([`kind IN (${q.kinds.map(() => "?").join(",")})`, q.kinds]);
+ const where = filters.length ? `WHERE ${filters.map((f) => f[0]).join(" AND ")}` : "";
+ const d = db();
+ const rows = d.prepare(`SELECT * FROM worker_events ${where} ORDER BY id DESC LIMIT ?`).all(...filters.flatMap((f) => f[1]), q.limit) as EventRowDb[];
+ const latest = (d.prepare("SELECT MAX(id) AS id FROM worker_events").get() as { id: number | null }).id ?? 0;
+ const labels = new Map<string, string | null>();
+ const label = (lane: string | null) => {
+ if (!lane) return null;
+ if (!labels.has(lane)) labels.set(lane, laneName(lane));
+ return labels.get(lane)!;
+ };
+ return {
+ items: rows.map((r) => ({
+ id: r.id,
+ at: r.at,
+ workerId: r.worker_id,
+ workerName: r.worker_name,
+ kind: r.kind,
+ event: r.event,
+ words: r.words,
+ taskId: r.task_id,
+ generationId: r.generation_id,
+ lane: r.lane,
+ laneLabel: label(r.lane),
+ state: r.state,
+ detail: parseDetail(r.detail_json),
+ })),
+ next: rows.length === q.limit ? String(rows[rows.length - 1].id) : null,
+ latest,
+ };
+}
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index cc434203..06a4a404 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -78,6 +78,9 @@ export interface WorkerRow {
cpu_slot_json?: string | null;
/** Why it doesn't start the line's work now (src/lib/relay.ts WorkerHolding), as its last beat said. NULL: none. */
holding_json?: string | null;
+ /** Its last claim for its GPU's slot, and the answer in words (pool.ts workerClaim). */
+ asked_at?: number | null;
+ asked_words?: string | null;
}
const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
diff --git a/src/server/db.ts b/src/server/db.ts
index a2ec54c0..4b50c822 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -717,7 +717,9 @@ export const WORKER_JOBS_KEEP_MS = 365 * 24 * 60 * 60_000;
* 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. 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.
+ * became of it (rows are only added; each is kept a year, like the admin API's log). worker_events: each worker's state
+ * changes, handoffs, stages, claims, admin actions and its own log lines (worker-events.ts; pruned after 7 or 30 days).
+ * Safe to run on every start.
*/
export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
principal TEXT PRIMARY KEY,
@@ -846,7 +848,27 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
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;`;
+ BEGIN SELECT RAISE(ABORT, 'worker_jobs rows are kept a year'); END;
+ CREATE TABLE IF NOT EXISTS worker_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ at INTEGER NOT NULL,
+ worker_id TEXT,
+ worker_name TEXT,
+ kind TEXT NOT NULL,
+ event TEXT NOT NULL,
+ words TEXT,
+ task_id TEXT,
+ generation_id TEXT,
+ lane TEXT,
+ state TEXT,
+ detail_json TEXT
+ );
+ CREATE INDEX IF NOT EXISTS worker_events_at ON worker_events(at);
+ CREATE INDEX IF NOT EXISTS worker_events_kind_at ON worker_events(kind, at);
+ CREATE INDEX IF NOT EXISTS worker_events_worker ON worker_events(worker_id, id);
+ CREATE INDEX IF NOT EXISTS worker_events_worker_kind ON worker_events(worker_id, kind, id);
+ CREATE INDEX IF NOT EXISTS worker_events_task ON worker_events(task_id);
+ CREATE INDEX IF NOT EXISTS worker_events_generation ON worker_events(generation_id);`;
/**
* The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and release
@@ -1088,6 +1110,9 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_workers", "cpu_slot_json", "TEXT"],
// Why a worker that may work doesn't start the line's work now, as its last beat said (WorkerBeat.holding; NULL: none).
["relay_workers", "holding_json", "TEXT"],
+ // A worker's last claim for its GPU's slot, and the answer in words (pool.ts workerClaim).
+ ["relay_workers", "asked_at", "INTEGER"],
+ ["relay_workers", "asked_words", "TEXT"],
];
declare global {
diff --git a/tests/worker-events.test.ts b/tests/worker-events.test.ts
new file mode 100644
index 00000000..6776d904
--- /dev/null
+++ b/tests/worker-events.test.ts
@@ -0,0 +1,414 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { LogRing, maskLine } from "../bin/lib/worker/log-ring.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Each worker's timeline (worker_events) and its admin route: a row for each change of state, handoff, stage, claim
+ * answer, admin action and version, never one per beat; the worker's own log lines from its beat, masked on both sides;
+ * pages by id; old rows pruned. Every write is best-effort.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-worker-events-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+
+const auth = await import("@/server/auth");
+const { db, RELAY_TABLES } = 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 events = await import("@/server/computer/worker-events");
+const eventsRoute = await import("@/app/api/admin/workers/events/route");
+const { createAdminToken } = await import("@/server/admin-tokens");
+const { RELAY_TIMES } = await import("@/lib/relay");
+
+const HOST = "localhost:3000";
+const MIN = 60_000;
+const LANE = "aaaaaaaaaaaa";
+let clock = Date.now();
+
+type W = { id: string; token: string };
+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 taskRow = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+
+function worker(name: string): W {
+ const w = pool.addWorker(name);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { [LANE]: { delayMs: 0 } }, claimAfterMs: 0 }, clock);
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: [LANE], workflows: ["wf-a"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ return w;
+}
+
+function beat(w: W, o: { now?: number; local?: { paused: boolean; why: string | null }; running?: { task: string; value?: number; max?: number }[]; version?: string; log?: unknown } = {}) {
+ return pool.workerBeat(
+ workerRow(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: o.version ?? "1.0.0", local: { ...(o.local ?? { paused: false, why: null }), until: null }, gpu: {}, inventoryHash: null, running: o.running ?? [], stopped: [], ...(o.log !== undefined && { log: o.log }) }),
+ o.now ?? clock,
+ );
+}
+const claim = (w: W, running: string[] = [], now = clock) => pool.workerClaim(workerRow(w), running, now);
+
+let gens = 0;
+function task(o: { lane?: string } = {}) {
+ const gid = `ev-gen-${++gens}`;
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")
+ .run(gid, clock, clock);
+ const t = tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], rankAt: clock - MIN, lane: o.lane ?? LANE, needs: { workflowId: "wf-a", files: [], packs: [], minVramBytes: 0 } },
+ });
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock - MIN, t.id);
+ return { id: t.id, generationId: gid };
+}
+
+type Ev = { id: number; at: number; kind: string; event: string; words: string | null; task_id: string | null; worker_id: string | null; state: string | null; detail_json: string | null };
+const rowsOf = (w: { id: string }, kind?: string) =>
+ db()
+ .prepare(`SELECT * FROM worker_events WHERE worker_id = ? ${kind ? "AND kind = ?" : ""} ORDER BY id`)
+ .all(...(kind ? [w.id, kind] : [w.id])) as Ev[];
+const detail = (e: Ev) => JSON.parse(e.detail_json ?? "{}") as Record<string, unknown>;
+
+beforeAll(() => {
+ auth.setPassword("install password");
+});
+beforeEach(() => {
+ setSetting("comfyWhere", "workers");
+ clock += 60 * MIN;
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE relay_workers SET revoked_at = 1 WHERE revoked_at IS NULL").run();
+});
+
+describe("state and version rows", () => {
+ it("a state row only when its state changes, never once per beat", () => {
+ const w = worker("steady");
+ for (let i = 0; i < 5; i++) beat(w, { now: clock + i * 5000 });
+ expect(rowsOf(w, "state").map((e) => e.event)).toEqual(["idle"]);
+ expect(detail(rowsOf(w, "state")[0])).toMatchObject({ from: "new" });
+ beat(w, { now: clock + 30_000, local: { paused: true, why: "gpu-busy:blender.exe" } });
+ beat(w, { now: clock + 35_000, local: { paused: true, why: "gpu-busy:blender.exe" } });
+ beat(w, { now: clock + 40_000 });
+ const s = rowsOf(w, "state");
+ expect(s.map((e) => e.event)).toEqual(["idle", "gpu-busy", "idle"]);
+ expect(s[1].words).toBe("Your GPU is busy (blender.exe)");
+ expect(detail(s[2])).toMatchObject({ from: "gpu-busy" });
+ });
+
+ it("silent past the limit: one offline row, then back with a row from offline", () => {
+ const w = worker("quiet");
+ beat(w);
+ const later = clock + RELAY_TIMES.poolSilentMs + MIN;
+ pool.noteSilentWorkers(later);
+ pool.noteSilentWorkers(later + 5000);
+ pool.sweepPool(later + 6000);
+ const off = rowsOf(w, "state").filter((e) => e.event === "offline");
+ expect(off).toHaveLength(1);
+ expect(off[0].at).toBe(clock + RELAY_TIMES.poolSilentMs);
+ expect(detail(off[0])).toMatchObject({ from: "idle", seenAt: clock });
+ beat(w, { now: later + 10_000 });
+ expect(rowsOf(w, "state").map((e) => e.event)).toEqual(["idle", "offline", "idle"]);
+ });
+
+ it("a version row when its worker program's version changes", () => {
+ const w = worker("updated");
+ beat(w, { version: "1.0.0" });
+ beat(w, { version: "1.0.0", now: clock + 5000 });
+ beat(w, { version: "1.1.0", now: clock + 10_000 });
+ const v = rowsOf(w, "version");
+ expect(v).toHaveLength(1);
+ expect(detail(v[0])).toEqual({ from: "1.0.0", to: "1.1.0" });
+ });
+});
+
+describe("looking rows", () => {
+ it("only when the answer to its claims changes; asked_at and asked_words at every claim", () => {
+ const w = worker("looker");
+ beat(w);
+ expect(claim(w)).toBeNull();
+ expect(claim(w, [], clock + 1000)).toBeNull();
+ expect(workerRow(w).asked_at).toBe(clock + 1000);
+ expect(workerRow(w).asked_words).toBe("Asked for work: nothing waiting");
+ // Waiting work in another lane: still "nothing", and no new row.
+ task({ lane: "bbbbbbbbbbbb" });
+ expect(claim(w, [], clock + 2000)).toBeNull();
+ expect(workerRow(w).asked_words).toBe("Asked for work: 1 waiting, none it can run now");
+ const a = task();
+ expect(claim(w, [], clock + 3000)?.id).toBe(a.id);
+ // Holding a job: no answer to note.
+ expect(claim(w, [a.id], clock + 4000)).toBeNull();
+ tasks.endTask(a.id, "canceled", { error: "Stopped" });
+ expect(claim(w, [], clock + 5000)).toBeNull();
+ pool.patchWorker(w.id, { paused: true }, clock + 6000);
+ beat(w, { now: clock + 6000 });
+ expect(claim(w, [], clock + 7000)).toBeNull();
+ expect(claim(w, [], clock + 8000)).toBeNull();
+ const l = rowsOf(w, "looking");
+ expect(l.map((e) => e.event)).toEqual(["nothing", "found", "nothing", "blocked"]);
+ expect(l[3].words).toBe("Asked for work: not taking work (paused on the website)");
+ expect(pool.listWorkers(clock + 8000).find((x) => x.id === w.id)?.asked).toEqual({ at: clock + 8000, words: l[3].words });
+ });
+});
+
+describe("job and stage rows", () => {
+ const plan = () => ({ wanted: [{ n: 0, filename: "x.png", subfolder: "", type: "output" as const, kind: "image" as const, maxBytes: 1e6 }], outputs: [], budget: 1 });
+
+ it("job rows mirror worker_jobs, in words; stage rows only when the stage changes", () => {
+ const w = worker("runner");
+ beat(w);
+ const a = task();
+ const c = claim(w)!;
+ expect(c.id).toBe(a.id);
+ const rep = (e: Parameters<typeof tasks.report>[1], now: number) => tasks.report(taskRow(a.id), e, plan, now);
+ rep({ event: "sent", promptId: "11111111-2222-3333-4444-555555555555" }, clock + 1000);
+ rep({ event: "queued", position: 2 }, clock + 1500);
+ rep({ event: "running" } as never, clock + 2000);
+ rep({ event: "running", value: 1, max: 20 } as never, clock + 3000);
+ rep({ event: "running", value: 2, max: 20 } as never, clock + 4000);
+ beat(w, { now: clock + 5000, running: [{ task: a.id, value: 3, max: 20 }] });
+ rep({ event: "finished", entry: { outputs: {} } } as never, clock + 6000);
+ tasks.endTask(a.id, "done");
+ const stages = rowsOf(w, "stage").filter((e) => e.task_id === a.id);
+ // Taken cold (no lane warm): loading until its first step, then running.
+ expect(stages.map((e) => e.event)).toEqual(["sending", "queued", "loading", "running", "saving"]);
+ const jobs = rowsOf(w, "job").filter((e) => e.task_id === a.id);
+ const log = db().prepare("SELECT event FROM worker_jobs WHERE task_id = ? ORDER BY id").all(a.id) as { event: string }[];
+ expect(jobs.map((e) => e.event)).toEqual(log.map((x) => x.event));
+ expect(jobs.map((e) => e.event)).toEqual(["claimed", "finished", "done"]);
+ expect(jobs[0].words).toMatch(/^Took a .+ run$/);
+ expect(jobs[2].words).toMatch(/^Delivered after \d+/);
+ });
+
+ it("a job sent back says why and how many tries; claimed again, it starts at sending", () => {
+ const w = worker("lost");
+ beat(w);
+ const a = task();
+ expect(claim(w)?.id).toBe(a.id);
+ const later = clock + RELAY_TIMES.poolSilentMs + MIN;
+ pool.sweepPool(later);
+ beat(w, { now: later + 1000 });
+ expect(claim(w, [], later + 1000)?.id).toBe(a.id);
+ const jobs = rowsOf(w, "job").filter((e) => e.task_id === a.id);
+ expect(jobs.map((e) => e.event)).toEqual(["claimed", "requeued", "claimed"]);
+ expect(jobs[1].words).toBe("Sent back in line: went silent");
+ expect(detail(jobs[1])).toMatchObject({ why: "went silent", tries: 1 });
+ expect(rowsOf(w, "stage").filter((e) => e.task_id === a.id).map((e) => e.event)).toEqual(["sending", "sending"]);
+ });
+
+ it("the worker view lists each job it holds, the stage, and its last event", () => {
+ const w = worker("viewed");
+ beat(w);
+ const a = task();
+ claim(w);
+ const v = pool.listWorkers(clock).find((x) => x.id === w.id)!;
+ expect(v.jobs).toHaveLength(1);
+ expect(v.jobs[0]).toMatchObject({ taskId: a.id, generationId: a.generationId, slot: "gpu", lane: LANE, stage: "sending", state: "sending", owners: "owner", feature: "image", modelName: "m" });
+ expect(v.current?.taskId).toBe(a.id);
+ expect(v.lastEvent?.kind).toBe("stage");
+ expect(JSON.stringify(v.jobs)).not.toContain("SaveImage");
+ });
+});
+
+describe("admin rows", () => {
+ it("each admin action with who did it; an edit names its keys, never their values", () => {
+ const w = worker("managed");
+ beat(w);
+ pool.patchWorker(w.id, { pauseNow: true }, clock + 1000, "panel token");
+ pool.patchWorker(w.id, { paused: false, hours: { always: true } }, clock + 2000);
+ pool.patchWorker(w.id, { drain: true }, clock + 3000);
+ const a = rowsOf(w, "admin").filter((e) => e.at >= clock + 1000);
+ expect(a.map((e) => e.event)).toEqual(["pause-now", "resume", "edit", "drain"]);
+ expect(detail(a[0])).toEqual({ by: "panel token" });
+ expect(detail(a[2])).toEqual({ by: "owner", keys: ["hours"] });
+ expect(a[2].detail_json).not.toContain("always");
+ // The state it leads to, at once.
+ expect(rowsOf(w, "state").filter((e) => e.at >= clock + 1000).map((e) => e.event)).toEqual(["paused", "idle", "paused"]);
+ });
+});
+
+describe("log lines in the beat", () => {
+ it("kept as log rows, masked again here, at most 40 a beat, never later than now", () => {
+ const w = worker("talker");
+ beat(w);
+ const lines = Array.from({ length: 50 }, (_, i) => ({ at: clock - 1000 + i, level: i === 0 ? "error" : "info", line: `line ${i}` }));
+ lines[1].line = "Saved its next token fuobe_wkr_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ0123 in C:\\Users\\me\\worker.json";
+ lines[2] = { at: clock + 10 * MIN, level: "loud", line: "Bearer abc.def from [email protected] at https://studio.example/api?key=1" };
+ beat(w, { now: clock + 1000, log: lines });
+ const l = rowsOf(w, "log");
+ expect(l).toHaveLength(40);
+ expect(l[0]).toMatchObject({ event: "error", words: "line 0", at: clock - 1000 });
+ expect(l[1].words).toBe("Saved its next token [hidden] in [file]");
+ expect(l[2]).toMatchObject({ event: "info", at: clock + 1000, words: "Bearer [hidden] from [email] at https://studio.example/api?[hidden]" });
+ });
+
+ it("a beat without log, or with a log that isn't a list of lines, works as before", () => {
+ const w = worker("quiet-log");
+ expect(beat(w).runner).toBe(true);
+ expect(beat(w, { log: "not a list", now: clock + 1000 }).runner).toBe(true);
+ expect(beat(w, { log: [null, 3, { line: 7 }, { line: "" }], now: clock + 2000 }).runner).toBe(true);
+ expect(rowsOf(w, "log")).toHaveLength(0);
+ });
+
+ it("the worker and the site mask a line the same way", () => {
+ const samples = [
+ "No working ffmpeg at C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe: it takes pictures only.",
+ "Loaded D:\\models\\checkpoints\\flux2-dev-fp8.safetensors and /home/me/models/wan2.2_i2v.gguf",
+ "ComfyUI didn't start: spawn /usr/bin/python3 ENOENT (see ~/fuobe/comfyui.log)",
+ "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.e30.abc token=s3cret api_key: 'k-123' password=\"p w\"",
+ "Reach https://user:[email protected]/api/gpu/computer/beat?x=1#y and http://10.0.0.2:8188/prompt",
+ "mail [email protected] about \\\\nas\\share\\models\\vae.pt",
+ `prompt "${"a long prompt about a person on a beach at sunset, ".repeat(2)}" sent`,
+ "a\u0007b\u001b[31mred\u001b[0m\tc\nd",
+ "word ".repeat(100),
+ "Loading Wan2_1-I2V-14B-480P_fp8_e4m3fn_scaled_KJ.safetensors with prompt id 11111111-2222-3333-4444-555555555555",
+ "Job AbCdEfGhIjKlMnOp done.",
+ ];
+ for (const s of samples) expect(maskLine(s)).toBe(events.maskLogLine(s));
+ expect(events.maskLogLine(samples[0])).toBe("No working ffmpeg at [file]: it takes pictures only.");
+ expect(events.maskLogLine(samples[1])).toBe("Loaded flux2-dev-fp8.safetensors and wan2.2_i2v.gguf");
+ expect(events.maskLogLine(samples[2])).toBe("ComfyUI didn't start: spawn [file] ENOENT (see [file])");
+ expect(events.maskLogLine(samples[3])).toBe("Authorization: Bearer [hidden] token=[hidden] api_key: [hidden] password=[hidden]");
+ expect(events.maskLogLine(samples[4])).toBe("Reach https://studio.example/api/gpu/computer/beat?[hidden] and http://10.0.0.2:8188/prompt");
+ expect(events.maskLogLine(samples[5])).toBe("mail [email] about vae.pt");
+ expect(events.maskLogLine(samples[6])).toBe('prompt "[text]" sent');
+ expect(events.maskLogLine(samples[7])).toBe("a bred c d");
+ expect(events.maskLogLine(samples[8])).toHaveLength(300);
+ expect(events.maskLogLine(samples[9])).toBe("Loading Wan2_1-I2V-14B-480P_fp8_e4m3fn_scaled_KJ.safetensors with prompt id [hidden]");
+ expect(events.maskLogLine(samples[10])).toBe("Job AbCdEfGhIjKlMnOp done.");
+ });
+});
+
+describe("the worker's log ring", () => {
+ it("sends at most 40 lines a beat, drops them only after a 2xx, and keeps the lines that came since", () => {
+ let t = 1000;
+ const ring = new LogRing({ now: () => t++ });
+ for (let i = 0; i < 50; i++) ring.add(`line ${i}`);
+ const first = ring.take();
+ expect(first).toHaveLength(40);
+ expect(first[0]).toEqual({ at: 1000, level: "info", line: "line 0" });
+ // That beat failed (no ack): the same lines go again.
+ expect(ring.take().map((l) => l.line)).toEqual(first.map((l) => l.line));
+ ring.add("Job x failed.");
+ ring.ack();
+ expect(ring.size).toBe(11);
+ const next = ring.take();
+ expect(next.map((l) => l.line)).toEqual([...Array.from({ length: 10 }, (_, i) => `line ${40 + i}`), "Job x failed."]);
+ expect(next.at(-1)?.level).toBe("error");
+ ring.ack();
+ expect(ring.take()).toEqual([]);
+ // An ack with nothing in flight changes nothing.
+ ring.add("one more");
+ ring.ack();
+ expect(ring.size).toBe(1);
+ });
+
+ it("never holds more than 200 lines, masks each one, and never throws", () => {
+ const ring = new LogRing();
+ for (let i = 0; i < 1000; i++) ring.add(`line ${i} at C:\\secret\\folder\\file.txt`);
+ expect(ring.size).toBe(200);
+ expect(ring.take()[0].line).toBe("line 800 at [file]");
+ const odd = { toString: () => { throw new Error("no"); } };
+ expect(() => ring.add(odd)).not.toThrow();
+ expect(() => ring.add(undefined)).not.toThrow();
+ expect(() => ring.add(Symbol("s") as never)).not.toThrow();
+ const broken = new LogRing({ now: () => { throw new Error("clock"); } });
+ expect(() => broken.add("x")).not.toThrow();
+ expect(() => broken.take()).not.toThrow();
+ expect(() => broken.ack()).not.toThrow();
+ });
+});
+
+describe("GET /api/admin/workers/events", () => {
+ const get = (qs: string, headers: Record<string, string>) => eventsRoute.GET(new Request(`http://${HOST}/api/admin/workers/events${qs}`, { headers: { host: HOST, ...headers } }));
+ let owner = "";
+ beforeAll(() => {
+ owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ });
+ type Page = { items: { id: number; kind: string; event: string; workerId: string; generationId: string | null; laneLabel: string | null; detail: unknown }[]; next: string | null; latest: number };
+
+ it("pages newest first by worker, kinds, run, before and after", async () => {
+ const w = worker("paged");
+ const other = worker("other");
+ beat(w);
+ beat(other);
+ const a = task();
+ claim(w);
+ beat(w, { now: clock + 1000, log: [{ at: clock, level: "info", line: "hello" }] });
+ const all = (await (await get(`?worker=${w.id}`, { cookie: owner })).json()) as Page;
+ expect(all.items.length).toBeGreaterThan(3);
+ expect(all.items.every((e) => e.workerId === w.id)).toBe(true);
+ expect(all.items.map((e) => e.id)).toEqual([...all.items.map((e) => e.id)].sort((x, y) => y - x));
+ expect(all.next).toBeNull();
+ expect(all.latest).toBeGreaterThanOrEqual(all.items[0].id);
+ const jobs = (await (await get(`?worker=${w.id}&kinds=job,stage`, { cookie: owner })).json()) as Page;
+ expect(new Set(jobs.items.map((e) => e.kind))).toEqual(new Set(["job", "stage"]));
+ expect(jobs.items.find((e) => e.kind === "job")?.laneLabel).toBeTruthy();
+ const byRun = (await (await get(`?generation=${a.generationId}`, { cookie: owner })).json()) as Page;
+ expect(byRun.items.length).toBeGreaterThan(0);
+ expect(byRun.items.every((e) => e.generationId === a.generationId)).toBe(true);
+ // Pages of 2, back to the start.
+ const seen: number[] = [];
+ let before = "";
+ for (;;) {
+ const p = (await (await get(`?worker=${w.id}&limit=2${before}`, { cookie: owner })).json()) as Page;
+ seen.push(...p.items.map((e) => e.id));
+ if (!p.next) break;
+ before = `&before=${p.next}`;
+ }
+ expect(seen).toEqual(all.items.map((e) => e.id));
+ // Live: only the rows after the latest one seen.
+ const latest = all.latest;
+ const none = (await (await get(`?after=${latest}`, { cookie: owner })).json()) as Page;
+ expect(none.items).toEqual([]);
+ beat(w, { now: clock + 2000, log: [{ at: clock + 2000, level: "warn", line: "news" }] });
+ const fresh = (await (await get(`?after=${latest}&kinds=log`, { cookie: owner })).json()) as Page;
+ expect(fresh.items.map((e) => e.event)).toEqual(["warn"]);
+ });
+
+ it("for the owner or a token that may read the workers; bad queries are 400", async () => {
+ expect((await get("", { cookie: owner })).status).toBe(200);
+ expect((await get("", {})).status).toBeGreaterThanOrEqual(401);
+ const reader = createAdminToken({ name: "events reader", scopes: ["workers:read"] });
+ expect((await get("?limit=1", { authorization: `Bearer ${reader.token}` })).status).toBe(200);
+ const other = createAdminToken({ name: "queue only", scopes: ["queue:read"] });
+ expect((await get("", { authorization: `Bearer ${other.token}` })).status).toBe(403);
+ for (const qs of ["?limit=0", "?limit=501", "?kinds=state,nope", "?before=x", "?after=-1", "?worker=a%20b", "?generation=%2F"]) expect((await get(qs, { cookie: owner })).status).toBe(400);
+ expect((await get("", { cookie: owner })).headers.get("cache-control")).toBe("no-store");
+ });
+});
+
+describe("retention and best-effort writes", () => {
+ it("log lines go after 7 days, other rows after 30", () => {
+ const now = clock;
+ const add = (kind: "log" | "state", ageDays: number) => events.logWorkerEvent({ kind, event: kind === "log" ? "info" : "idle", workerId: "w-prune", words: `${kind} ${ageDays}`, at: now - ageDays * 24 * 60 * MIN }, now);
+ add("log", 8);
+ add("log", 6);
+ add("state", 31);
+ add("state", 8);
+ events.pruneWorkerEvents(now);
+ const left = (db().prepare("SELECT words FROM worker_events WHERE worker_id = 'w-prune' ORDER BY id").all() as { words: string }[]).map((r) => r.words);
+ expect(left).toEqual(["log 6", "state 8"]);
+ });
+
+ it("a timeline that can't be written never fails a beat, a claim, a report or an admin change", () => {
+ const w = worker("sturdy");
+ db().exec("DROP TABLE worker_events");
+ try {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(beat(w, { log: [{ at: clock, level: "info", line: "x" }] }).runner).toBe(true);
+ const a = task();
+ expect(claim(w)?.id).toBe(a.id);
+ tasks.report(taskRow(a.id), { event: "sent", promptId: "11111111-2222-3333-4444-555555555555" }, () => ({ error: "x" }), clock);
+ expect(pool.patchWorker(w.id, { drain: true }, clock).view?.drain).toBe(true);
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)?.lastEvent).toBeNull();
+ warn.mockRestore();
+ } finally {
+ db().exec(RELAY_TABLES);
+ }
+ });
+});
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index 987e1cdf..b5e6e79d 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -610,6 +610,40 @@ http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/js
});
});
+describe("the worker's timeline", () => {
+ it("its log lines reach the studio masked, each in one beat; its job's handoffs and stages are rows in order", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const beats: { lines: { at: number; level: string; line: string }[] }[] = [];
+ s.intercept = (path, init) => {
+ if (path === "/api/gpu/computer/beat") beats.push({ lines: (JSON.parse(String(init.body)) as { log?: { at: number; level: string; line: string }[] }).log ?? [] });
+ return undefined;
+ };
+ const { id } = addTask();
+ start(w, s, p, { steps: 4, stepMs: 100 });
+ expect((await ended(id)).state).toBe("done");
+ await until(() => p.logs.some((l) => l.includes(`Job ${id} done`)));
+ await until(() => beats.some((b) => b.lines.some((l) => l.line.includes(`Job ${id} done`))));
+ // Each line went in one beat only (each beat got a 2xx), oldest first, never more than 40 a beat.
+ const sent = beats.flatMap((b) => b.lines);
+ expect(beats.every((b) => b.lines.length <= 40)).toBe(true);
+ expect(new Set(sent.map((l) => `${l.at} ${l.line}`)).size).toBe(sent.length);
+ const rows = db().prepare("SELECT kind, event, words, task_id FROM worker_events WHERE worker_id = ? ORDER BY id").all(w.id) as { kind: string; event: string; words: string; task_id: string | null }[];
+ const logs = rows.filter((r) => r.kind === "log").map((r) => r.words);
+ expect(logs).toContain(`Job ${id} done.`);
+ // No folder of this PC leaves it.
+ for (const folder of [p.workDir, p.comfyDir, p.home]) expect(JSON.stringify({ sent, logs })).not.toContain(folder.replace(/\\/g, "\\\\"));
+ expect(rows.filter((r) => r.kind === "job" && r.task_id === id).map((r) => r.event)).toEqual(["claimed", "finished", "done"]);
+ const stages = rows.filter((r) => r.kind === "stage" && r.task_id === id).map((r) => r.event);
+ expect(stages[0]).toBe("sending");
+ expect(stages.at(-1)).toBe("saving");
+ // Started on its ComfyUI: loading its model (taken cold) until a step reports, then running.
+ expect(stages.slice(1, -1).filter((x) => x === "loading" || x === "running").length).toBeGreaterThan(0);
+ expect(stages).toContain("queued");
+ });
+});
+
describe("new worker code", () => {
/** A watch on a checkout of its own (its parts taken as whole) and the PC's home folder, looked at every turn. */
function watch(p: Pc) {