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 job lost while the worker's PC slept counts no attempt

Adarsh374e8d88d4bf
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 0c86d02a..18e6cd3b 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -56,6 +56,12 @@ export const RESCAN_MS = 10 * 60_000;
*/
export const MODELS_CHECK_MS = 60_000;
+/**
+ * A one-second wait in the worker's loop that took longer than this means the PC slept (the process was stopped). The
+ * next beat says how long (`slept`), so a job the studio took back meanwhile counts against no one.
+ */
+export const SLEPT_MS = 60_000;
+
/** Kept results that the studio hasn't taken for this long are deleted (the studio drops its jobs after a day). */
export const HOLD_MAX_AGE_MS = 24 * HOUR;
@@ -226,6 +232,9 @@ async function work(saved, deps, owner) {
let lastTask = null;
let heldRetryAt = 0;
let holdCheckedAt = -Infinity;
+ // How long the PC slept since the studio last answered a beat (ms), and how much of it the beat in flight carries.
+ let slept = 0;
+ let sleptSent = 0;
// Its ComfyUI's start, while it goes on (beats go on meanwhile), and the signal that ends a start when the worker stops.
let starting = null;
const stopStarts = new AbortController();
@@ -373,17 +382,25 @@ async function work(saved, deps, owner) {
await cleanJob(f, comfy.base, own);
emptyCache();
},
- beatExtra: () => ({
- protocol: PROTOCOL,
- version: VERSION,
- local: pause,
- gpu: gpuInfo,
- inventoryHash: invHash,
- warmLane: null,
- // The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.
- held: hold.ids().slice(0, 16),
- }),
+ beatExtra: () => {
+ sleptSent = slept;
+ return {
+ protocol: PROTOCOL,
+ version: VERSION,
+ local: pause,
+ gpu: gpuInfo,
+ inventoryHash: invHash,
+ warmLane: null,
+ // The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.
+ held: hold.ids().slice(0, 16),
+ // The PC slept: a job taken back from it meanwhile goes on with no blame.
+ ...(slept > 0 && { slept }),
+ };
+ },
onBeat: (a) => {
+ // The studio heard about the sleep.
+ slept = Math.max(0, slept - sleptSent);
+ sleptSent = 0;
// A studio that takes jobs only from a newer worker program: say so once (it sends this worker none).
const min = Number(a?.worker?.minProtocol);
if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");
@@ -673,7 +690,14 @@ async function work(saved, deps, owner) {
log(s);
}
writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null });
+ const before = now();
await sleep(1000);
+ // A second that took over a minute: the PC slept (the whole process stopped). The next beat says so.
+ const gap = now() - before;
+ if (gap >= SLEPT_MS) {
+ slept += gap;
+ log(`The PC slept for about ${Math.max(1, Math.round(gap / 60_000))} min: the studio hears it, so a job taken back meanwhile counts against no one.`);
+ }
}
} finally {
// Every way out: the job in hand stops (its kept results stay for the next start), its ComfyUI stops, the PC may
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index fcccc6b7..cb47427b 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -328,7 +328,8 @@ If a worker stops answering for 2 minutes, its ComfyUI is down for 2 minutes, or
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.
+After the third lost attempt, the job fails. A job that is put back because of a pause does not count as an attempt,
+and neither does one lost while the worker's PC slept, once the worker says so (`slept` in its next beat).
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
@@ -461,6 +462,10 @@ The worker keeps its jobs going by itself:
- **The PC stays awake** while the worker holds a job, has results to send, or waits for work. A small helper asks the
system to stay awake (`SetThreadExecutionState` on Windows, `caffeinate` on macOS, `systemd-inhibit` on Linux). The
screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.
+- **A PC that slept anyway** (a lid closed, the power button) is noticed when it wakes: a one-second wait in the
+ worker's loop took over a minute. The next beat says how long the PC slept (`slept`, in ms). A job that the studio
+ took back from the worker for going quiet during that sleep then counts no attempt, and the worker may take it again
+ at once. This happens once per job at most.
- **Its model folders are read again** every 10 minutes, and whenever a job needs a model file that the worker has not
found yet. A drive that comes back after a restart is noticed, and the studio gets the new list.
- **A model folder that isn't there yet** (a drive that is still locked or not connected after a restart) pauses the
@@ -496,7 +501,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 }`. The answer adds `worker: { paused, pauseNow,
+ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept? }`. The answer adds `worker: { paused, pauseNow,
drain, autoResume, insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token,
above).
- `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUI
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 680bbbbd..b7cf4577 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -229,6 +229,11 @@ export interface WorkerBeat {
stopped: string[];
/** The tasks whose finished results the worker keeps on its disk (a stop-now leaves them its own, to send them up). */
held?: string[];
+ /**
+ * How long its PC slept (ms) since its last beat that the studio answered. A job the studio took back from it for
+ * going quiet during that sleep goes on with no blame: no attempt counted, and this worker may take it again.
+ */
+ slept?: number;
}
/** Task timings (DESIGN 5.5): the runner lease, how often the tab beats, when a computer counts as gone. */
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 85b38948..24080560 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -159,6 +159,7 @@ export function cleanBeat(b: unknown): WorkerBeat {
running: Array.isArray(o.running) ? (o.running.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],
stopped: Array.isArray(o.stopped) ? o.stopped.filter((x): x is string => typeof x === "string").slice(0, 64) : [],
held: Array.isArray(o.held) ? o.held.filter((x): x is string => typeof x === "string").slice(0, 16) : [],
+ ...((num(o.slept) ?? 0) > 0 && { slept: Math.min(num(o.slept)!, MAX_SLEPT_MS) }),
};
}
@@ -177,6 +178,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,
warm_lane = ?, facts_json = COALESCE(?, facts_json) WHERE id = ?`,
).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, w.id);
+ // Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.
+ if (b.slept) forgiveSleep(w, b.slept, now);
for (const r of b.running) {
const t = typeof r?.task === "string" ? (d.prepare("SELECT * FROM relay_tasks WHERE id = ? AND worker_id = ?").get(r.task, w.id) as TaskRow | undefined) : undefined;
if (!t || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
@@ -449,7 +452,7 @@ export function lineOrder(rows: TaskRow[], fairShare: boolean): TaskRow[] {
* its ComfyUI down: the worker is noted in tried_json and it counts as an attempt). The third lost attempt fails it.
* The old worker's lease stops working, so its late calls get 409.
*/
-export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; last?: boolean }): void {
+export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; last?: boolean; lostAt?: number }): void {
const tried = json<string[]>(t.tried_json, []);
const requeues = t.requeues + (o.blame ? 1 : 0);
if (o.blame && (requeues >= MAX_ATTEMPTS || o.last)) {
@@ -471,6 +474,8 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; last?:
down_why: null,
note: "resent",
...(o.blame && t.worker_id && { tried_json: JSON.stringify([...new Set([...tried, t.worker_id])]) }),
+ // Lost because its worker went quiet: noted, so a sleep the worker reports later takes the blame back (forgiveSleep).
+ ...(o.lostAt && t.worker_id && { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), lost: { worker: t.worker_id, at: o.lostAt } }) }),
});
db().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
}
@@ -494,13 +499,41 @@ export function sweepPool(now = Date.now()): void {
const down = !!t.down_at && now - t.down_at > RELAY_TIMES.poolComfyDownMs;
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." });
+ 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.", ...(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: "The GPUs were busy. Not charged." });
}
+/** The longest sleep a worker's beat may report (a week). */
+const MAX_SLEPT_MS = 7 * 24 * 60 * 60_000;
+/** A job lost this long before the reported sleep began still counts as lost to it (beats come every few seconds). */
+const SLEEP_SLACK_MS = 2 * 60_000;
+
+/**
+ * A worker's PC slept for `sleptMs` until about now: each job the studio took back from it for going quiet during that
+ * sleep goes on with no blame. The attempt it counted is taken back, and the worker is off the job's tried list, so it
+ * may take the job again at once. Once a job at most: a worker can't keep a job going forever by saying it slept.
+ */
+export function forgiveSleep(w: Pick<WorkerRow, "id">, sleptMs: number, now = Date.now()): string[] {
+ const since = now - Math.min(sleptMs, MAX_SLEPT_MS) - SLEEP_SLACK_MS;
+ const rows = db().prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state IN ('waiting','sending','queued','running','collecting') AND INSTR(extra_json, '\"lost\"') > 0").all() as TaskRow[];
+ const forgiven: string[] = [];
+ for (const t of rows) {
+ const { lost, ...extra } = json<{ lost?: { worker?: string; at?: number }; sleptOnce?: boolean } & Record<string, unknown>>(t.extra_json, {});
+ if (lost?.worker !== w.id || typeof lost.at !== "number" || lost.at < since || lost.at > now) continue;
+ if (extra.sleptOnce || t.requeues <= 0) {
+ setTask(t.id, { extra_json: JSON.stringify(extra) });
+ continue;
+ }
+ const tried = json<string[]>(t.tried_json, []).filter((x) => x !== w.id);
+ setTask(t.id, { requeues: t.requeues - 1, tried_json: tried.length ? JSON.stringify(tried) : null, extra_json: JSON.stringify({ ...extra, sleptOnce: true }) });
+ forgiven.push(t.id);
+ }
+ return forgiven;
+}
+
setPoolClocks((t, now) => {
sweepPool(now);
return taskById(t.id) ?? t;
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index bf0695b2..72a5d991 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -12,6 +12,8 @@
* - A request to its ComfyUI with another Host or without the key is refused.
* - A clip is made again by ffmpeg before its ComfyUI sees it; without ffmpeg, the job goes back to the line.
* - A model file that turns up later is reported within one look at its folders.
+ * - Its PC sleeps mid-run and the studio takes the job back: the next beat says how long it slept, the attempt is taken
+ * back, and the output arrives once.
* - A model folder that isn't there yet (a drive still locked after a restart): the worker waits for it, says so, and
* sends no list of files meanwhile; once the folder is there, the waiting job is taken within one look.
*/
@@ -156,7 +158,7 @@ function start(
w: W,
s: Studio,
p: Pc,
- o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number } = {},
+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void> } = {},
) {
const ctrl = new AbortController();
const cfg = {
@@ -189,7 +191,8 @@ function start(
...(o.gpuEveryMs && { gpuEveryMs: o.gpuEveryMs }),
...(o.ffmpeg === undefined || o.ffmpeg === null ? { ffmpegVersion: async () => null } : {}),
awake: { set: (on: boolean) => void (p.awake.at(-1) !== on && p.awake.push(on)) },
- sleep: (ms: number) => sleep(Math.min(ms, 50)),
+ sleep: o.sleep ?? ((ms: number) => sleep(Math.min(ms, 50))),
+ ...(o.now && { now: o.now }),
log: (line: string) => {
p.logs.push(line);
p.logAt.push(Date.now());
@@ -625,4 +628,55 @@ describe("its model folders", () => {
expect(s.inventories.length).toBeGreaterThan(0);
expect(p.logs.some((l) => /model folders are all there/.test(l))).toBe(true);
});
+
+ it("its PC sleeps mid-run and the studio takes the job back: no attempt counted, and the output arrives once", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const beats: Record<string, unknown>[] = [];
+ s.intercept = (q, init) => {
+ if (q === "/api/gpu/computer/beat") beats.push(JSON.parse(String(init.body)));
+ return undefined;
+ };
+ // The worker's clock: the PC's. A sleep moves it on by 5 minutes at the end of one of the worker's one-second waits.
+ let offset = 0;
+ let sleepNext = 0;
+ const { id } = addTask();
+ start(w, s, p, {
+ steps: 40,
+ stepMs: 100,
+ now: () => Date.now() + offset,
+ sleep: async (ms) => {
+ await sleep(Math.min(ms, 50));
+ if (ms === 1000 && sleepNext) {
+ offset += sleepNext;
+ sleepNext = 0;
+ }
+ },
+ });
+ await until(async () => {
+ const c = comfyOf(p);
+ return c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2;
+ });
+ // The PC sleeps: the studio hears nothing for 3 minutes and takes the job back, blamed on the worker.
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 3 * 60_000, w.id);
+ pool.sweepPool(Date.now());
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ // It wakes: its loop sees the time jump, and its next beat says how long it slept.
+ await until(async () => {
+ if (p.logs.some((l) => /The PC slept for about 5 min/.test(l))) return true;
+ if (!sleepNext) sleepNext = 5 * 60_000;
+ await sleep(300);
+ return false;
+ }, 30_000);
+ await until(() => beats.some((b) => typeof b.slept === "number" && (b.slept as number) >= 5 * 60_000));
+ const done = await ended(id);
+ expect(done.state).toBe("done");
+ // The attempt lost to the sleep was taken back: no blame on the worker.
+ expect(done.requeues).toBe(0);
+ expect(done.tried_json).toBeNull();
+ // Once heard, the sleep isn't said again.
+ const last = beats.at(-1)!;
+ expect(last.slept).toBeUndefined();
+ });
});
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index e54afd71..5b44f5d5 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -205,6 +205,68 @@ describe("losing a worker (checks 3, 4, 5)", () => {
expect(claim(b)?.id).toBe(id2);
});
+ it("a worker whose PC slept: the job taken back from it meanwhile counts no attempt, and it may take the job again", () => {
+ const id = task();
+ const a = worker("sleeper");
+ const b = worker("awake");
+ expect(claim(a)?.id).toBe(id);
+ // The PC sleeps for 10 minutes: the studio takes the job back after 2 (blamed: the worker went quiet).
+ const asleep = clock;
+ clock += 3 * MIN;
+ beat(b);
+ pool.sweepPool(clock);
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ expect(JSON.parse(state(id).tried_json!)).toEqual([a.id]);
+ clock = asleep + 10 * MIN;
+ // It wakes and says how long it slept: the attempt is taken back, and it is off the tried list.
+ const woke = pool.workerBeat(row(a), pool.cleanBeat({ device: `wkr-${a.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], slept: 10 * MIN }), clock);
+ expect(woke.runner).toBe(true);
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 0, tried_json: null });
+ // So it takes the job again at once, though another worker is about (no retry rule against it).
+ beat(b);
+ expect(claim(a)?.id).toBe(id);
+ expect(claim(a)!.attempt).toBe(1);
+ });
+
+ it("a sleep is forgiven once a job, only for a job lost while it slept, and never for another worker's or another loss", () => {
+ const a = worker("sleeps-twice");
+ const lose = (id: string) => {
+ expect(claim(a)?.id).toBe(id);
+ clock += 3 * MIN;
+ pool.sweepPool(clock);
+ };
+ const id = task();
+ lose(id);
+ expect(pool.forgiveSleep(row(a), 5 * MIN, clock)).toEqual([id]);
+ beat(a);
+ lose(id);
+ // A second sleep on the same job: the attempt stands.
+ expect(pool.forgiveSleep(row(a), 5 * MIN, clock)).toEqual([]);
+ expect(state(id).requeues).toBe(1);
+ // A loss well before the reported sleep began is not the sleep's.
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(id);
+ const old = task();
+ beat(a);
+ lose(old);
+ clock += 60 * MIN;
+ expect(pool.forgiveSleep(row(a), 5 * MIN, clock)).toEqual([]);
+ expect(state(old).requeues).toBe(1);
+ // Another worker's sleep, or a job given back (not lost to silence): nothing changes.
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(old);
+ const other = worker("other");
+ const mine = task();
+ beat(a);
+ lose(mine);
+ expect(pool.forgiveSleep(row(other), 5 * MIN, clock)).toEqual([]);
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(mine);
+ const given = task();
+ beat(a);
+ expect(claim(a)?.id).toBe(given);
+ pool.backInLine(state(given), { blame: true });
+ expect(pool.forgiveSleep(row(a), 5 * MIN, clock)).toEqual([]);
+ expect(state(given).requeues).toBe(1);
+ });
+
it("the third lost attempt fails the row", () => {
const id = task();
for (let i = 0; i < 3; i++) {