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 preview picture shows only with hosted runs on, and one the studio can't keep never fails a report

Adarshb298e2ab9b32
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 0af1c1cd..409520b4 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -583,16 +583,17 @@ its target), at most once an hour each.
and at most the time since the job was sent to its ComfyUI (plus a minute, because ComfyUI starts a job a moment
before the studio hears that it was sent).
- `running` can carry `preview`: the latest preview picture of the job, a JPEG of at most 64 KB as base64, at most
- one every 2 seconds. A claim says `reportPreview: true` when the run shows one. The worker keeps the latest
+ one every 2 seconds. A claim says `reportPreview: true` when the run shows one: only with hosted runs on
+ (`FUOBE_HOSTED_RUNS=1`; without them, no job shows one, as before). The worker keeps the latest
preview its ComfyUI sends on its socket and adds it to a `running` report. A PNG preview, or a JPEG over 64 KB, is
made a smaller JPEG with ffmpeg first (at most 512 pixels on its long side); a worker without ffmpeg sends only
ComfyUI's own small JPEGs. The studio keeps only the latest one for the job, shows it in the run's tile while the
run works, and serves it only to the run's own account (`GET /api/generations/<id>/preview`, never cached). It
drops the picture when the job ends, goes back in line or is claimed again. A picture that is not a JPEG, is too
big, comes too soon or comes from an attempt that no longer holds the job is dropped, and the rest of the report
- still counts. A run whose outputs the moderation service checks first shows no preview
- ([moderation-hook.md](moderation-hook.md)). Progress from reports and beats is kept in the database, so every app
- process sees the same step.
+ still counts. A picture that the studio cannot keep (a full disk, a file open elsewhere) is dropped too. A run
+ whose outputs the moderation service checks first shows no preview ([moderation-hook.md](moderation-hook.md)).
+ Progress from reports and beats is kept in the database, so every app process sees the same step.
- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and
counts as an attempt. Only a worker's job can be given back.
- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 279d08d9..9f027550 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -26,6 +26,7 @@ import {
} from "@/lib/relay";
import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";
import { runCeilingMs } from "../queue-settings";
+import { hostedRunsOn } from "../hosted-switch";
/**
* "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a
@@ -518,10 +519,12 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
const STILL_HELD = `state IN (${SENT_STATES.map((x) => `'${x}'`).join(",")}) AND lease_hash IS ?`;
/**
- * Does this run show a preview picture while it works? Not when the moderation service asked to see its outputs before
- * they show (its stamp's `checkOutputs`): a preview would show what the check holds back.
+ * Does this run show a preview picture while it works? Only with hosted runs on (an install without them shows what it
+ * showed before), and not when the moderation service asked to see its outputs before they show (its stamp's
+ * `checkOutputs`): a preview would show what the check holds back.
*/
export function previewShown(generationId: string): boolean {
+ if (!hostedRunsOn()) return false;
const g = rdb().prepare("SELECT request_json FROM generations WHERE id = ?").get(generationId) as { request_json: string } | undefined;
if (!g) return false;
try {
@@ -534,6 +537,9 @@ export function previewShown(generationId: string): boolean {
/** Is this a JPEG picture (its first bytes)? */
const isJpeg = (b: Buffer) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;
+/** A preview picture that couldn't be kept is logged once per app process. */
+let previewWarned = false;
+
/**
* Keep a worker's preview picture of its job (a JPEG of at most 64 KB, sent as base64 with a "running" report), in
* place of the one before. One every 2 s at most: one that comes sooner is dropped, as is anything that isn't a JPEG
@@ -548,12 +554,12 @@ export function notePreview(t: Pick<TaskRow, "id" | "pools" | "preview" | "previ
const data = Buffer.from(base64, "base64");
if (data.length > PREVIEW_LIMITS.bytes || !isJpeg(data) || !previewShown(t.generation_id)) return false;
const file = previewFile(t.id);
- fs.mkdirSync(path.dirname(file), { recursive: true });
const part = `${file}.${process.pid}.part`;
- fs.writeFileSync(part, data, { mode: 0o600 });
const d = rdb();
let kept = false;
try {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(part, data, { mode: 0o600 });
// The row and the file change together: dropProgress in another process waits for this, then removes both.
kept = d
.transaction((): boolean => {
@@ -562,8 +568,18 @@ export function notePreview(t: Pick<TaskRow, "id" | "pools" | "preview" | "previ
return changed;
})
.immediate();
+ } catch (e) {
+ // A picture that can't be kept (a full disk, a file a reader has open) is only a picture: the report it came with
+ // is taken all the same, and the next picture tries again.
+ if (!previewWarned) console.warn(`[fuobe] a preview picture couldn't be kept: ${(e as Error).message}`);
+ previewWarned = true;
+ kept = false;
} finally {
- if (!kept) fs.rmSync(part, { force: true });
+ if (!kept) {
+ try {
+ fs.rmSync(part, { force: true });
+ } catch {}
+ }
}
return kept;
}
@@ -571,7 +587,10 @@ export function notePreview(t: Pick<TaskRow, "id" | "pools" | "preview" | "previ
/** Forget a task's progress and its preview picture (it ended, or went back in line, or its ComfyUI starts it again). */
export function dropProgress(id: string): void {
rdb().prepare("UPDATE relay_tasks SET progress_json = NULL, preview_at = NULL WHERE id = ?").run(id);
- fs.rmSync(previewFile(id), { force: true });
+ // (A picture a reader has open stays until the task's folder goes; nothing serves it once preview_at is gone.)
+ try {
+ fs.rmSync(previewFile(id), { force: true });
+ } catch {}
}
/**
diff --git a/src/server/generations.ts b/src/server/generations.ts
index ffa25a8d..8232c089 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -106,6 +106,7 @@ import { accountSend } from "./account-send";
import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";
import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
import { placeInLine, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";
+import { hostedRunsOn } from "./hosted-switch";
import { poolLane, queueOfGeneration } from "./computer/pool";
import { runPreviewAt } from "./computer/tasks";
import { runCeilingMs } from "./queue-settings";
@@ -242,7 +243,8 @@ function workerQueue(id: string): { queue: { place: number; etaSeconds: number |
/** A run's latest preview picture from the workers, as the address its tile loads (it changes with each picture). */
function livePreview(id: string): { preview: string } | Record<string, never> {
- const at = runPreviewAt(id);
+ // (Only with hosted runs on: computer/tasks.ts previewShown.)
+ const at = hostedRunsOn() ? runPreviewAt(id) : null;
return at ? { preview: `/api/generations/${encodeURIComponent(id)}/preview?at=${at}` } : {};
}
diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.ts
index ee2659cf..87b9e48b 100644
--- a/tests/recovery-server.test.ts
+++ b/tests/recovery-server.test.ts
@@ -751,9 +751,75 @@ describe("a run's preview picture while it works", () => {
expect(previews.every((p) => p === undefined)).toBe(true);
await expectOnce(id, watch, { prompts: 1, place: 1 });
});
+
+ it("a picture the studio can't keep (its file is open elsewhere, or the disk is full) never fails the worker's report: the run goes on and its output arrives", async () => {
+ const w = standInWorker();
+ const { id } = await pressRun();
+ const watch = watchOf(id);
+ const d = driver(w);
+ let n = 0;
+ d.previews(() => jpegBase64(++n));
+ const realRename = fs.renameSync.bind(fs);
+ const spy = vi.spyOn(fs, "renameSync").mockImplementation((from, to) => {
+ if (String(to).endsWith("preview.jpg")) throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" });
+ return realRename(from, to);
+ });
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ // What the task's folder holds while it runs: no picture kept, and nothing half-written left beside it.
+ const left: string[][] = [];
+ d.onStep(async (step) => {
+ await tick();
+ await watch.look();
+ const dir = path.dirname(tasks.outputFile(taskOf(id)!.id, 0));
+ if (step === "running" && fs.existsSync(dir)) left.push(fs.readdirSync(dir).filter((f) => f.startsWith("preview")));
+ });
+ try {
+ await workAll(d);
+ expect(d.steps).toContain("running");
+ expect(spy.mock.calls.some(([, to]) => String(to).endsWith("preview.jpg")), "a picture was sent and couldn't be kept").toBe(true);
+ expect(left.length).toBeGreaterThan(0);
+ expect(left.flat()).toEqual([]);
+ } finally {
+ spy.mockRestore();
+ warn.mockRestore();
+ }
+ await expectOnce(id, watch, { prompts: 1, place: 1 });
+ });
});
describe("the owner's own job on the workers", () => {
+ it("with hosted runs off, it shows no preview picture, as before: its worker is never asked for one, and one sent anyway is dropped", async () => {
+ delete process.env.FUOBE_HOSTED_RUNS;
+ delete process.env.FUOBE_BILLING_URL;
+ try {
+ const w = standInWorker();
+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ const { id } = await pressRun(IMAGE, owner);
+ expect(taskOf(id)!.principal).toBe("owner");
+ comfy.inner.opts.steps = 6;
+ comfy.inner.opts.stepMs = 100;
+ const d = driver(w);
+ let n = 0;
+ d.previews(() => jpegBase64(++n));
+ const asked: number[] = [];
+ const shown: (string | undefined)[] = [];
+ d.onStep(async (step) => {
+ await tick();
+ if (step !== "running") return;
+ asked.push((d.runner as unknown as { previewed: Map<string, unknown> }).previewed.size);
+ shown.push(((await sessionRead(owner)(id)) as RunLike & { preview?: string }).preview);
+ });
+ await workAll(d);
+ expect(shown.length).toBeGreaterThan(0);
+ expect(asked.every((x) => x === 0), "the claim asks for no picture").toBe(true);
+ expect(shown.every((p) => p === undefined), "no picture shows").toBe(true);
+ expect(taskOf(id)!.preview_at).toBeNull();
+ await until(() => getGeneration(id)?.status === "succeeded");
+ } finally {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ }
+ });
+
it("waiting, it carries its place in their line in the list as after a refresh", async () => {
const w = standInWorker();
const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;