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.

Worker: retry a dropped claim and log only trouble that lasts

Adarsh02342bcf2845
diff --git a/bin/lib/worker/retry.mjs b/bin/lib/worker/retry.mjs
index e311c35e..4a056ddf 100644
--- a/bin/lib/worker/retry.mjs
+++ b/bin/lib/worker/retry.mjs
@@ -3,8 +3,11 @@
// (429 with Retry-After) or a network that drops for a moment are waited out with a growing pause (1 s, 2 s, 4 s … at
// most 30 s at a time): up to 2 minutes for a call, and up to an hour for a part of a result. A beat is never waited
// out: the next one comes soon anyway. A call that may have reached the studio is sent again only when sending it twice
-// is safe (a read, or a part of a result, which the studio takes only at its own offset). A proxy's page in place of an
-// answer (a 403 that isn't the studio's JSON) never stops the worker: it counts as no answer.
+// is safe (a read; a part of a result, which the studio takes only at its own offset; or a claim, since a job the studio
+// gave out on a claim whose answer was lost comes back on the next one). A proxy's page in place of an answer (a 403
+// that isn't the studio's JSON) never stops the worker: it counts as no answer. A call that gets through on its second
+// try (a second without the studio while it deploys, one dropped connection) says nothing: only trouble that lasts
+// longer is logged, with the network's own reason (failure).
export const RETRY = { callMs: 2 * 60_000, uploadMs: 60 * 60_000, maxPauseMs: 30_000 };
@@ -16,10 +19,39 @@ const NOT_REACHED = new Set([502, 503, 521, 522, 523, 525, 526, 530]);
const MAYBE_REACHED = new Set([500, 504, 520, 524, 527]);
const codeOf = (e) => e?.cause?.code ?? e?.code;
+
+/** What went wrong with a call, for the log: the error and, for a network failure ("fetch failed"), its reason. */
+export function failure(e) {
+ const said = String(e?.message ?? e);
+ const why = codeOf(e) ?? (e?.cause && e.cause !== e ? e.cause.message : undefined);
+ return why && !said.includes(String(why)) ? `${said} (${why})` : said;
+}
const isJson = (res) => /json/i.test(res.headers.get("content-type") ?? "");
/** A proxy's page in place of the studio's answer. */
const notTheStudio = (res) => res.status === 403 && !isJson(res);
+/**
+ * The worker's beats, for its log. A beat is never waited out, and the next one comes a few seconds later, so one beat
+ * that didn't get through says nothing. The second in a row says the studio can't be reached, and why; the first beat
+ * that gets through after that says it answers again.
+ */
+export class Reach {
+ constructor(log) {
+ this.log = log;
+ this.missed = 0;
+ }
+
+ miss(e) {
+ this.missed += 1;
+ if (this.missed === 2) this.log(`Can't reach the studio: ${failure(e)}`);
+ }
+
+ back() {
+ if (this.missed >= 2) this.log("The studio answers again.");
+ this.missed = 0;
+ }
+}
+
/** Is this answer worth waiting out? `safe`: the call can be sent twice. */
export function passing(res, safe) {
if (NOT_REACHED.has(res.status)) return true;
@@ -36,7 +68,8 @@ export function retrying(fetchFn, o = {}) {
const method = String(init.method ?? "GET").toUpperCase();
const upload = method === "PUT" && /\/outputs\/\d+/.test(String(url));
const beat = /\/api\/gpu\/computer\/beat$/.test(String(url));
- const safe = method === "GET" || upload;
+ const claim = method === "POST" && /\/api\/gpu\/computer\/claim$/.test(String(url));
+ const safe = method === "GET" || upload || claim;
const until = now() + (beat ? 0 : upload ? RETRY.uploadMs : RETRY.callMs);
for (let i = 0; ; i++) {
let res = null;
@@ -58,7 +91,7 @@ export function retrying(fetchFn, o = {}) {
const after = res ? Number(res.headers.get("retry-after")) : NaN;
res?.body?.cancel().catch(() => {});
const pause = Math.min(RETRY.maxPauseMs, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** Math.min(i, 5), Math.max(0, until - now()));
- if (i === 0) o.log?.(`The studio didn't answer${res ? ` (HTTP ${res.status})` : ""}: trying again.`);
+ if (i === 1) o.log?.(`The studio didn't answer${res ? ` (HTTP ${res.status})` : ` (${failure(err)})`}: trying again.`);
await sleep(pause);
}
};
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index c3aea241..8df5969a 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -35,7 +35,7 @@ import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media
import { canCleanPictures, cleanPicture, isPicture } from "./picture.mjs";
import { previewShrinker } from "./preview.mjs";
import { withPlainResults } from "./results.mjs";
-import { retrying } from "./retry.mjs";
+import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
import { SiteTurns, writeSite } from "./turns.mjs";
import { CodeWatch } from "./update.mjs";
@@ -709,7 +709,8 @@ async function work(saved, deps, owner) {
.then((had) => {
cpuMissedAt = had ? -Infinity : now();
})
- .catch((e) => log(`A CPU slot job stopped: ${e.message}`))
+ // A claim the studio never answered (the retry policy gave up on it) had no job: none stopped.
+ .catch((e) => log(cpuComfy.task ? `A CPU slot job stopped: ${failure(e)}` : `Its CPU slot can't ask the studio for a job: ${failure(e)}`))
.finally(() => {
busyCpu = false;
cpuComfy.task = null;
@@ -747,7 +748,7 @@ async function work(saved, deps, owner) {
.then((had) => {
if (!o?.onlyHeld) gpuMissedAt = had ? -Infinity : now();
})
- .catch((e) => log(`A job stopped: ${e.message}`))
+ .catch((e) => log(comfy.task ? `A job stopped: ${failure(e)}` : `It can't ask the studio for a job: ${failure(e)}`))
.finally(() => {
busyJob = false;
jobUsesGpu = false;
@@ -782,6 +783,8 @@ async function work(saved, deps, owner) {
}
let beatAt = 0;
+ // A lone missed beat says nothing; two in a row say the studio can't be reached (retry.mjs).
+ const reach = new Reach(log);
let lastState = "";
try {
while (!deps.signal?.aborted) {
@@ -866,6 +869,7 @@ async function work(saved, deps, owner) {
beaten = true;
try {
const a = await runner.beat();
+ reach.back();
if (runner.view.stopped) {
log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");
break;
@@ -878,7 +882,7 @@ async function work(saved, deps, owner) {
}
}
} catch (e) {
- log(`Can't reach the studio: ${e.message}`);
+ reach.miss(e);
}
}
// Its model folders, again every 10 minutes (in the background: beats go on while it hashes a new file).
@@ -904,7 +908,7 @@ async function work(saved, deps, owner) {
serverInterrupt: false,
});
if (turn.waitForYield && !was.waitForYield) log("Local ComfyUI work holds the GPU: asking it to make room for the studio's jobs.");
- if (turn.late && !was.late) log("Local ComfyUI work hasn't made room after 3 minutes: still waiting, with the jobs kept in line.");
+ if (turn.late && !was.late) log("Local ComfyUI work hasn't answered for 3 minutes: still waiting, with the jobs kept in line.");
if (was.waitForYield && !turn.waitForYield && turn.siteWaiting > 0) log("Local ComfyUI work made room: starting.");
if (turn.ended === "idle") {
log("No studio job for a minute: its ComfyUI lets go of its memory for local work.");
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index f911705c..ca0bb3d7 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -334,8 +334,10 @@ local ComfyUI work counts as another program.
or in the last 15 seconds. The worker then starts at once.
When no studio job has come for a minute, the worker frees its own ComfyUI's memory (`/free`) and writes
-`siteWaiting: 0`, so your local work can go on. If no "yielded" comes within 3 minutes, the worker says so in its log
-and in its beat (`waiting-for-yield:no-answer`). It goes on waiting, with the jobs kept in line. While it waits,
+`siteWaiting: 0`, so your local work can go on. A fresh "yielding" (written in the last 15 seconds) counts as an
+answer: the helper is making room while local work finishes its job, however long that job takes. If 3 minutes go by
+with no "yielded" and no fresh "yielding", the worker says so in its log and in its beat
+(`waiting-for-yield:no-answer`). It goes on waiting, with the jobs kept in line. While it waits,
Settings → Workers shows "Waiting for local ComfyUI work to make room", with the helper's estimate of the start when
there is one, never "Ready".
@@ -716,8 +718,15 @@ The worker keeps its jobs going by itself:
- **One retry policy for the studio.** A studio that restarts, a proxy that answers 502, 503 or 52x, a network that
drops, or a busy studio that says when to come back is waited out. The pause grows from 1 second to at most 30
seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a call
- again only when that is safe. A proxy's page in place of the studio's answer (a 403 that is not JSON) never stops
- the worker.
+ again only when that is safe: a read, a part of a result, or a claim (a job that the studio gave out on a claim
+ whose answer was lost comes back on the next claim). A proxy's page in place of the studio's answer (a 403 that is
+ not JSON) never stops the worker.
+- **Its log shows trouble that lasts.** A call that gets through on its second try (a second without the studio while
+ it deploys, one dropped connection) writes nothing in the log. One missed beat writes nothing either, because the
+ next beat comes a few seconds later. Two missed beats in a row write "Can't reach the studio" with the network's
+ reason (for example `fetch failed (ECONNRESET)`), and the next beat that gets through writes "The studio answers
+ again". A claim that the studio never answered had no job, so the log says that the worker can't ask for a job,
+ not that a job stopped.
- **A job that stalls goes back to the line.** If a job makes no progress for its stall limit, or runs past the run
limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps its
place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and
diff --git a/tests/worker-parts.test.ts b/tests/worker-parts.test.ts
index 9b16f623..9d952837 100644
--- a/tests/worker-parts.test.ts
+++ b/tests/worker-parts.test.ts
@@ -10,7 +10,7 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import { helperCommand, StayAwake } from "../bin/lib/worker/awake.mjs";
import { encodeArgs, FIT, INPUT_FORMATS, MEDIA_LIMITS, mediaKind, outputCap, reencode } from "../bin/lib/worker/media.mjs";
-import { RETRY, retrying } from "../bin/lib/worker/retry.mjs";
+import { failure, Reach, RETRY, retrying } from "../bin/lib/worker/retry.mjs";
import { ffmpegOf } from "../bin/lib/worker/config.mjs";
import { takeLock, workerLives, WorkerRunning } from "../bin/lib/worker/lock.mjs";
import { privateHost, siteProblem, withoutOldPort } from "../bin/lib/worker/run.mjs";
@@ -109,6 +109,55 @@ describe("one retry policy for calls to the studio", () => {
expect(spent.calls).toHaveLength(1);
});
+ it("sends a claim again after a dropped connection: a job given out on a lost answer comes back on the next claim", async () => {
+ const c = clock();
+ const a = answers([netError("ECONNRESET"), json({ task: { id: "t1" } })]);
+ const res = await retrying(a.fetchFn, c)("https://studio.test/api/gpu/computer/claim", { method: "POST", body: "{}" });
+ expect(res.status).toBe(200);
+ expect(a.calls).toEqual(["POST https://studio.test/api/gpu/computer/claim", "POST https://studio.test/api/gpu/computer/claim"]);
+ // A beat is still never sent twice.
+ const beat = answers([netError("ECONNRESET"), json({})]);
+ await expect(retrying(beat.fetchFn, clock())("https://studio.test/api/gpu/computer/beat", { method: "POST" })).rejects.toThrow(/fetch failed/);
+ expect(beat.calls).toHaveLength(1);
+ });
+
+ it("logs only trouble that lasts past one more try, with the network's reason", async () => {
+ const quiet: string[] = [];
+ const once = answers([page(503), json({ ok: true })]);
+ expect((await retrying(once.fetchFn, { ...clock(), log: (l: string) => void quiet.push(l) })("https://studio.test/api/gpu/computer/claim", { method: "POST" })).status).toBe(200);
+ expect(quiet).toEqual([]);
+ const said: string[] = [];
+ const longer = answers([netError("ECONNRESET"), netError("ECONNRESET"), json({ ok: true })]);
+ expect((await retrying(longer.fetchFn, { ...clock(), log: (l: string) => void said.push(l) })("https://studio.test/api/gpu/computer/claim", { method: "POST" })).status).toBe(200);
+ expect(said).toEqual(["The studio didn't answer (fetch failed (ECONNRESET)): trying again."]);
+ const busy: string[] = [];
+ await retrying(answers([page(503), page(502), json({})]).fetchFn, { ...clock(), log: (l: string) => void busy.push(l) })("https://studio.test/api/gpu/computer/claim", { method: "POST" });
+ expect(busy).toEqual(["The studio didn't answer (HTTP 502): trying again."]);
+ });
+
+ it("says why a call failed: the network's code, or its cause's words", () => {
+ expect(failure(Object.assign(new TypeError("fetch failed"), { cause: { code: "UND_ERR_SOCKET", message: "other side closed" } }))).toBe("fetch failed (UND_ERR_SOCKET)");
+ expect(failure(Object.assign(new TypeError("fetch failed"), { cause: new Error("getaddrinfo failed") }))).toBe("fetch failed (getaddrinfo failed)");
+ expect(failure(new Error("The server took too long to answer. Please try again."))).toBe("The server took too long to answer. Please try again.");
+ expect(failure(Object.assign(new Error("connect ECONNREFUSED 1.2.3.4:443"), { code: "ECONNREFUSED" }))).toBe("connect ECONNREFUSED 1.2.3.4:443");
+ });
+
+ it("one missed beat says nothing; two in a row say the studio can't be reached, and the next beat that gets through says it answers again", () => {
+ const said: string[] = [];
+ const reach = new Reach((l: string) => void said.push(l));
+ const dropped = Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNRESET" } });
+ reach.miss(dropped);
+ reach.back();
+ expect(said).toEqual([]);
+ reach.miss(dropped);
+ reach.miss(dropped);
+ reach.miss(dropped);
+ expect(said).toEqual(["Can't reach the studio: fetch failed (ECONNRESET)"]);
+ reach.back();
+ reach.back();
+ expect(said).toEqual(["Can't reach the studio: fetch failed (ECONNRESET)", "The studio answers again."]);
+ });
+
it("stops waiting once the worker is stopping", async () => {
const ctrl = new AbortController();
ctrl.abort();
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index 5547b541..e004f2f8 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -544,6 +544,54 @@ http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/js
expect(p.logs.some((l) => /comfy-crashes/.test(l))).toBe(true);
});
+ it("dropped connections (a deploy, a proxy): no job is said to stop, a lone missed beat says nothing, and the job runs", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const dropped = () => Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNRESET" } });
+ const api = apiAs(routes, null);
+ let lost: string | null = null;
+ let beats = 0;
+ s.intercept = async (q, init) => {
+ // The studio gives out the job on its first claim, and the answer is lost on the way; its second beat doesn't
+ // get through either.
+ if (q === "/api/gpu/computer/claim" && !lost) {
+ const res = await api(q, init);
+ if (res.status !== 200) return res;
+ lost = ((await res.json()) as { task: { id: string } }).task.id;
+ throw dropped();
+ }
+ if (q === "/api/gpu/computer/beat" && ++beats === 2) throw dropped();
+ return undefined;
+ };
+ const { id } = addTask();
+ start(w, s, p);
+ const t = await ended(id);
+ expect(lost).toBe(id);
+ expect(t.state).toBe("done");
+ expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
+ // The claim sent again got the same job, and it ran once.
+ expect(prompts(p)).toBe(1);
+ await until(() => beats >= 3, 60_000);
+ expect(p.logs.filter((l) => /job stopped|Can't reach the studio|can't ask the studio|trying again/.test(l))).toEqual([]);
+ });
+
+ it("a studio it can't reach for longer: said once with the network's reason, and once when it answers again", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ let down = true;
+ s.intercept = (q) => {
+ if (down && q === "/api/gpu/computer/beat") throw Object.assign(new TypeError("fetch failed"), { cause: { code: "UND_ERR_SOCKET" } });
+ return undefined;
+ };
+ start(w, s, p);
+ await until(() => p.logs.some((l) => /Can't reach the studio/.test(l)), 60_000);
+ down = false;
+ await until(() => p.logs.some((l) => /The studio answers again/.test(l)), 60_000);
+ expect(p.logs.filter((l) => /Can't reach the studio|answers again/.test(l))).toEqual(["Can't reach the studio: fetch failed (UND_ERR_SOCKET)", "The studio answers again."]);
+ });
+
it("stops when the studio no longer knows its token, and says so", async () => {
const w = addWorker();
const s = studio();