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 check their face detector before face jobs

Adarsh852abe451b3c
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 53779fab..4058f84a 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -39,6 +39,7 @@ import { modelAgain, modelFormat } from "./model-file.mjs";
import { canCleanPictures, cleanPicture, isPicture } from "./picture.mjs";
import { previewShrinker } from "./preview.mjs";
import { withPlainResults } from "./results.mjs";
+import { detectsFaces, runSelfCheck } from "./self-check.mjs";
import { LogRing } from "./log-ring.mjs";
import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
@@ -316,6 +317,9 @@ async function work(saved, deps, owner) {
);
let comfyTrouble = null;
let troubleAt = 0;
+ // Its ComfyUI lists the nodes of its face detector's self-check (self-check.mjs), and how many checks it ran.
+ let faceNodes = false;
+ let faceChecks = 0;
let answer = null;
let inv = { files: [], nodePacks: [], media: ffmpeg ? ["image", "video", "audio"] : ["image"] };
let packs = [];
@@ -473,6 +477,7 @@ async function work(saved, deps, owner) {
return;
}
if (!info || typeof info !== "object" || !Object.keys(info).length) return;
+ faceNodes = !!info.H3FaceTrackCrop && !!info.PreviewAny;
const fresh = loadedPacks(packs, index, info);
for (const [name, l] of Object.entries(fresh)) {
if (!l.missing.length || JSON.stringify(loaded[name]) === JSON.stringify(l)) continue;
@@ -486,6 +491,44 @@ async function work(saved, deps, owner) {
inv = { ...inv, nodePacks: packsAsSeen(packs, loaded) };
invHash = inventoryHash(inv);
}
+ /**
+ * Its face detector's self-check (self-check.mjs) on its GPU ComfyUI, while that ComfyUI has the face nodes. A failure
+ * starts its ComfyUI again and checks once more; a second failure pauses the worker ("self-check") for an hour. True
+ * when it passed, or when there is nothing to check.
+ */
+ async function checkFaces(when) {
+ if (!faceNodes || !comfy.ready) return true;
+ const once = () => runSelfCheck((url, init) => comfy.fetch(url, init), comfy.base, { n: ++faceChecks, now, sleep });
+ const first = await once();
+ if (first.ok) return true;
+ log(`Its face check ${when} read ${first.height === null ? "no face" : `${Math.round(first.height)} px`} (${first.why}): starting its ComfyUI again.`);
+ // While it starts again, the loop starts no ComfyUI of its own (a start under way already holds `starting`).
+ const mine = !starting;
+ const again = (async () => {
+ await comfy.stop();
+ try {
+ await comfy.start(
+ packs.map((p) => p.folder),
+ { signal: stopStarts.signal },
+ );
+ await readLoadedNodes();
+ } catch (e) {
+ log(`ComfyUI didn't start: ${e.message}`);
+ }
+ })();
+ if (mine) starting = again;
+ await again;
+ if (mine && starting === again) starting = null;
+ const second = comfy.ready ? await once() : { ok: false, height: null, why: "no-comfy" };
+ if (second.ok) {
+ log(`Its face check passed after the restart (${Math.round(second.height)} px).`);
+ return true;
+ }
+ comfyTrouble = "self-check";
+ troubleAt = now();
+ log(`Its face check failed again after the restart (${second.why}): face jobs go back in line, and it pauses for an hour.`);
+ return false;
+ }
// One look at a time; the next beat carries a changed hash, and the studio then asks for the list.
let scanning = null;
let scannedAt = now();
@@ -596,8 +639,11 @@ async function work(saved, deps, owner) {
return { refused: r.reason };
}
- /** The worker's own checks of a job's graph before its ComfyUI sees it (checks.mjs): the reason it refuses it, or null. */
- async function vetJob(t) {
+ /**
+ * The worker's own checks of a job's graph before its ComfyUI sees it (checks.mjs): the reason it refuses it, or null.
+ * With `o.faces` (its GPU runner), a job that detects faces first passes the face self-check, or goes back in line.
+ */
+ async function vetJob(t, o = {}) {
const check = () => graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
let problem = check();
// A model file it doesn't have yet (a drive that came back after a restart): look again once before refusing.
@@ -607,8 +653,12 @@ async function work(saved, deps, owner) {
problem = check();
}
// Which node and input, for the PC's owner (never a value: those are someone's prompt or file).
- if (problem) log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
- return problem?.reason ?? null;
+ if (problem) {
+ log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
+ return problem.reason;
+ }
+ if (o.faces && detectsFaces(t.graph) && !(await checkFaces("before a face job"))) return { giveBack: "self-check" };
+ return null;
}
// The CPU slot (worker.json `cpuSlot: true`): its own ComfyUI on the CPU only (its own folders, port, key and kept
@@ -678,7 +728,7 @@ async function work(saved, deps, owner) {
socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
now,
sleep,
- vet: vetJob,
+ vet: (t) => vetJob(t, { faces: true }),
ended: async (t, phase, why) => {
log(endedLine("Job", t, phase, why));
// Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is,
@@ -1149,6 +1199,7 @@ async function work(saved, deps, owner) {
{ signal: stopStarts.signal },
)
.then(() => readLoadedNodes())
+ .then(() => checkFaces("after its start"))
.catch((e) => {
if (stopStarts.signal.aborted) return;
if (e instanceof PortBusy) {
@@ -1225,6 +1276,8 @@ async function work(saved, deps, owner) {
awake.set(!!answer?.worker && (busyJob || busyCpu || hold.ids().length > 0 || !!mayWork()));
// A taken port is tried again (a bind test, never a connection) once a minute.
if (comfyTrouble === "port-busy" && t - troubleAt >= 60_000) comfyTrouble = null;
+ // A failed face self-check: an hour later its ComfyUI starts again, and checks again first.
+ if (comfyTrouble === "self-check" && t - troubleAt >= HOUR) comfyTrouble = null;
const s = state();
if (s !== lastState) {
lastState = s;
diff --git a/bin/lib/worker/self-check-face.jpg b/bin/lib/worker/self-check-face.jpg
new file mode 100644
index 00000000..6c9ad843
Binary files /dev/null and b/bin/lib/worker/self-check-face.jpg differ
diff --git a/bin/lib/worker/self-check.mjs b/bin/lib/worker/self-check.mjs
new file mode 100644
index 00000000..c9733dbb
--- /dev/null
+++ b/bin/lib/worker/self-check.mjs
@@ -0,0 +1,116 @@
+// The worker's self-check of its face detector (docs/gpu-workers.md). Fix faces and the other face jobs find faces with
+// H3-FaceRefine's YOLO detector. If that detector gives wrong boxes in a running ComfyUI, its face jobs finish and
+// change nothing. So the worker runs the detector on one fixed photo (its face is about 168 px tall): after each start
+// of its ComfyUI, and before each job that detects faces. It takes about a second. A reading outside FACE_RANGE starts
+// its ComfyUI again, then checks once more; a second failure gives the job back to the line, and the worker pauses
+// itself ("self-check") for an hour.
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+/** The fixed photo: one face, about 168 px tall in the detector's boxes. */
+export const SELF_CHECK_PHOTO = path.join(here, "self-check-face.jpg");
+/** The photo's name in its ComfyUI's input folder. */
+export const SELF_CHECK_INPUT = "fuobe-self-check.jpg";
+/** The face heights (px) that pass. */
+export const FACE_RANGE = { min: 150, max: 190 };
+/** The pack whose detector it checks, by its folder name. */
+export const FACE_PACK = "ComfyUI-H3-FaceRefine";
+/** The nodes that run that detector: a job with one of them is a face job. */
+export const FACE_NODES = new Set(["H3FaceTrackCrop", "H3FaceSelect"]);
+/** The detector, as the Fix faces graph names it. */
+export const FACE_DETECTOR = "bbox\\face_yolov8m.pt";
+/** How long one check may take, at most. */
+export const SELF_CHECK_MS = 60_000;
+
+/** Does this graph detect faces with the checked detector? */
+export function detectsFaces(graph) {
+ return Object.values(graph ?? {}).some((n) => FACE_NODES.has(n?.class_type));
+}
+
+/**
+ * The check's graph: the photo, the detector's tracking node on it, and its report as text. `n` changes with each check:
+ * fallback_head_frac only matters with a body detector (none here), and a new value makes ComfyUI run the detector
+ * again, not answer from its cache of the last check.
+ */
+export function selfCheckGraph(n = 0) {
+ return {
+ "1": { class_type: "LoadImage", inputs: { image: SELF_CHECK_INPUT } },
+ "2": {
+ class_type: "H3FaceTrackCrop",
+ inputs: {
+ images: ["1", 0],
+ detector: FACE_DETECTOR,
+ confidence: 0.35,
+ fallback_detector: "none",
+ fallback_head_frac: 0.5 + (Math.abs(Math.trunc(n)) % 1000) / 100_000,
+ crop_factor: 2.5,
+ canvas_width: 512,
+ canvas_height: 512,
+ canvas_mode: "manual",
+ smooth_window: 21,
+ size_smooth_window: 51,
+ smooth_method: "gaussian",
+ size_mode: "per_frame",
+ identity_track: false,
+ identity_threshold: 0.28,
+ select: "largest_face",
+ },
+ },
+ "3": { class_type: "PreviewAny", inputs: { source: ["2", 3] } },
+ };
+}
+
+/** The face heights in the tracking node's report ("face height min=168px mean=168px max=168px"), or null. */
+export function faceHeight(report) {
+ const m = /face height\s+min=(-?\d+(?:\.\d+)?)px\s+mean=(-?\d+(?:\.\d+)?)px\s+max=(-?\d+(?:\.\d+)?)px/.exec(String(report ?? ""));
+ return m ? { min: Number(m[1]), mean: Number(m[2]), max: Number(m[3]) } : null;
+}
+
+/** Does this reading pass? Every frame's height (one frame here) has to be inside FACE_RANGE. */
+export const facePasses = (h) => !!h && h.min >= FACE_RANGE.min && h.max <= FACE_RANGE.max;
+
+/**
+ * One check on its ComfyUI. `fetchFn(url, init)`: a request to its own ComfyUI (its key goes with it); `base`: its
+ * address. Returns { ok, height (px, the mean; null when there was no reading), why (when not ok) }:
+ * "upload", "refused", "failed", "timeout", "no-report", "height".
+ */
+export async function runSelfCheck(fetchFn, base, o = {}) {
+ const now = o.now ?? Date.now;
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ const photo = o.photo ?? fs.readFileSync(SELF_CHECK_PHOTO);
+ const json = (body) => ({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const form = new FormData();
+ form.append("image", new Blob([photo], { type: "image/jpeg" }), SELF_CHECK_INPUT);
+ form.append("overwrite", "true");
+ form.append("type", "input");
+ const up = await fetchFn(`${base}/upload/image`, { method: "POST", body: form }).catch(() => null);
+ if (!up?.ok) return { ok: false, height: null, why: "upload" };
+ const sent = await fetchFn(`${base}/prompt`, json({ prompt: selfCheckGraph(o.n ?? 0), client_id: o.clientId ?? "fuobe-self-check" })).catch(() => null);
+ const id = sent?.ok ? (await sent.json().catch(() => ({})))?.prompt_id : null;
+ if (typeof id !== "string" || !id) return { ok: false, height: null, why: "refused" };
+ const until = now() + (o.timeoutMs ?? SELF_CHECK_MS);
+ let entry = null;
+ while (now() < until) {
+ const r = await fetchFn(`${base}/history/${encodeURIComponent(id)}`).catch(() => null);
+ const h = r?.ok ? await r.json().catch(() => null) : null;
+ if (h?.[id]) {
+ entry = h[id];
+ break;
+ }
+ await sleep(o.pollMs ?? 250);
+ }
+ // Nothing of the check stays in its history.
+ await fetchFn(`${base}/history`, json({ delete: [id] })).catch(() => null);
+ if (!entry) {
+ await fetchFn(`${base}/interrupt`, json({ prompt_id: id })).catch(() => null);
+ return { ok: false, height: null, why: "timeout" };
+ }
+ if (entry.status?.status_str === "error") return { ok: false, height: null, why: "failed" };
+ const text = entry.outputs?.["3"]?.text;
+ const h = faceHeight(Array.isArray(text) ? text.join("\n") : text);
+ if (!h) return { ok: false, height: null, why: "no-report" };
+ return facePasses(h) ? { ok: true, height: h.mean } : { ok: false, height: h.mean, why: "height" };
+}
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 6bda9c3f..d50bc3af 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -695,6 +695,21 @@ The worker checks the copy that its ComfyUI loads:
count for `diffusion_models` and `text_encoders`), or in a folder that ComfyUI's own `extra_model_paths.yaml` adds,
must be the same file too. If it is not, the file is not reported.
+#### The face self-check
+
+Fix faces and the other face jobs find faces with H3-FaceRefine's face detector (`H3FaceTrackCrop`). If that detector
+gives wrong boxes in a running ComfyUI, these jobs finish and change nothing. So the worker checks the detector itself
+(`bin/lib/worker/self-check.mjs`). It runs the detector on one fixed photo (`bin/lib/worker/self-check-face.jpg`, a
+face about 168 px tall) and reads the face height from the node's report. A height from 150 to 190 px passes. One check
+takes about a second.
+
+- The worker checks after each start of its ComfyUI, and before each job that has `H3FaceTrackCrop` or
+ `H3FaceSelect`. It checks only when its ComfyUI lists `H3FaceTrackCrop` and `PreviewAny`.
+- When a check fails, the worker starts its ComfyUI again and checks once more.
+- When the second check fails too, the job goes back in line with its place kept, and the try does not count against
+ it (give-back `self-check`). The worker pauses itself (`local.why: "self-check"`), and Settings → Workers shows that
+ its face check didn't pass. After an hour, the worker starts its ComfyUI again, and the check runs again first.
+
After each job, however it ended, nothing of it stays in its ComfyUI: the worker empties the queue, stops a prompt that
still runs, and clears the whole history (a meta-batch's passes too). It also deletes the job's inputs and results from
its folders, and its copies of the inputs. At start, and whenever it stops, it empties these folders too. Before it
@@ -1019,6 +1034,8 @@ its target), at most once an hour each.
and waits as a job no worker took (its wait limit holds, unless a worker ran it before). Refused later on (a worker
that started again after an update and took its own job back), it counts as an attempt, and the job keeps its
claim's time.
+ With `self-check` (the worker's face self-check failed twice, and it paused itself), the job goes back in line with
+ its place kept, and the try costs no attempt.
- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
`input-crashed` (its ComfyUI stopped twice on the job), `input-unreadable` (ffmpeg could not read a clip or a
sound), `bad-ticket` (a ticket it can't use, or a graph where a ticket belongs), `unsafe-model` (a 3D model that
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index 775bb5e5..977a1939 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -67,9 +67,10 @@ export interface RunnerDeps {
sleep?: (ms: number) => Promise<void>;
/**
* A worker program's own checks (docs/gpu-workers.md) before a graph goes to its ComfyUI: its node allowlist, path
- * strings, verified models. The failure, or null. (A browser tab has none: graphProblem is its check.)
+ * strings, verified models, and its own self-checks. The failure, a give-back (the job goes back in line: the worker
+ * can't run it now), or null. (A browser tab has none: graphProblem is its check.)
*/
- vet?: (t: ClaimedTask) => TabFailure | null | Promise<TabFailure | null>;
+ vet?: (t: ClaimedTask) => VetAnswer | Promise<VetAnswer>;
/**
* A job ended here, done or not: a worker deletes its files. `why`: a failed job's reason in one short line (ComfyUI's
* own, src/lib/comfy-reason.ts, or why it stopped here), for the worker's log.
@@ -126,6 +127,9 @@ export async function previewForReport(preview: Blob | undefined, lastSentAt: nu
return btoa(bin);
}
+/** A worker's own checks of a job: why it fails it, why it gives it back, or null when it may run. */
+export type VetAnswer = TabFailure | { giveBack: GiveBackWhy } | null;
+
/** Why a worker refuses a job ticket: another catalog, more than its PC allows, or a ticket it can't use (or a graph where a ticket belongs). */
export type TicketRefused = "update-worker" | "outside-ceiling" | "bad-ticket";
@@ -794,6 +798,10 @@ export class ComputerRunner {
return this.job(t, { phase: "failed" });
}
const refused = await this.deps.vet?.(t);
+ if (refused && typeof refused === "object") {
+ await this.giveBack(t, refused.giveBack);
+ return this.job(t, { phase: "failed" });
+ }
if (refused) {
await this.report(t, { event: "failed", reason: refused });
return this.job(t, { phase: "failed" });
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 1eb35538..5ac40697 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -41,9 +41,11 @@ export type TabFailure = (typeof TAB_FAILURES)[number];
* Why a worker gives a task back to the line (another worker, or this one later, runs it): it made no progress for too
* long ("stalled"), it ran past its run limit ("run-limit"), or it takes clips or sound and this worker can't make them
* again ("media"). Two more cost the task nothing (it never ran there): its job ticket was made for another catalog
- * than the worker's ("update-worker"), or the job is more than its PC allows ("outside-ceiling").
+ * than the worker's ("update-worker"), or the job is more than its PC allows ("outside-ceiling"). One more costs it
+ * nothing too: the worker's own check before the run failed ("self-check": its face detector read the fixed photo wrong,
+ * bin/lib/worker/self-check.mjs), and the worker pauses itself.
*/
-export const GIVE_BACK = ["stalled", "run-limit", "media", "update-worker", "outside-ceiling"] as const;
+export const GIVE_BACK = ["stalled", "run-limit", "media", "update-worker", "outside-ceiling", "self-check"] as const;
export type GiveBackWhy = (typeof GIVE_BACK)[number];
/** What the tab reports about one task. */
@@ -269,8 +271,9 @@ export interface WorkerBeat {
why: string | null;
/**
* Its own pause switch: by hand ("here", "here-until:<ms>", "here-now"), by itself ("gpu-busy:<process>",
- * "comfy-crashes", "port-busy", "models-not-ready": a model folder isn't there yet). Not paused, `why` may say that it
- * waits for local ComfyUI work to make room ("waiting-for-yield", "waiting-for-yield:no-answer").
+ * "comfy-crashes", "port-busy", "models-not-ready": a model folder isn't there yet, "self-check": its face detector's
+ * check failed twice). Not paused, `why` may say that it waits for local ComfyUI work to make room
+ * ("waiting-for-yield", "waiting-for-yield:no-answer").
*/
local: { paused: boolean; why: string | null; until: number | null };
gpu: { otherApps: { pid: number; name: string; vramBytes: number }[]; tempC: number | null };
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 29ef6e7d..51df5848 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -215,6 +215,7 @@ export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerStat
if (why.startsWith("gpu-busy")) return { state: "gpu-busy", words: `Your GPU is busy${why.includes(":") ? ` (${why.split(":").slice(1).join(":")})` : ""}` };
if (why === "comfy-crashes") return { state: "comfy-down", words: "ComfyUI keeps stopping" };
if (why === "port-busy") return { state: "comfy-down", words: "Its ComfyUI port is taken by another program" };
+ if (why === "self-check") return { state: "comfy-down", words: "Its face check didn't pass after a restart: it starts its ComfyUI again within the hour" };
// A model folder isn't there yet (a drive still locked after a restart): it waits for it, with its lanes as they were.
if (why === MODELS_NOT_READY) return { state: "models-not-ready", words: "Waiting for its model folders" };
return { state: "paused", words: w.local_until ? `Paused here until ${clock(w.local_until, tz)}` : "Paused here" };
@@ -1129,6 +1130,8 @@ setPoolGiveBack((t, why) => {
return;
}
const sentBack = GIVE_BACK_WORDS[why] ?? "the worker gave it back";
+ // The worker's own check failed before the run (it pauses itself): back in line with its place kept, at no cost.
+ if (why === "self-check") return void backInLine(t, { blame: false, sentBack });
if (why === "run-limit") {
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 }) });
@@ -1147,6 +1150,7 @@ 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",
+ "self-check": "the worker's check before the run didn't pass",
};
// ---------------------------------------------------------------------------
diff --git a/tests/worker-runner.test.ts b/tests/worker-runner.test.ts
index f06f12dd..822c980d 100644
--- a/tests/worker-runner.test.ts
+++ b/tests/worker-runner.test.ts
@@ -356,6 +356,24 @@ describe("a worker's runner", () => {
expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "media" });
});
+
+ it("a failed self-check gives the job back at no cost, nothing goes to its ComfyUI, and the paused worker says why", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ const before = fake.posts();
+ const r = new ComputerRunner(
+ { api: s.call, local: (url, init) => realFetch(url, init), sha256, origin: SITE, sleep: (ms) => sleep(Math.min(ms, 30)), worker: hooks(), vet: async () => ({ giveBack: "self-check" }) },
+ { device: "worker", port: fake.port, clientId: "client-worker-01" },
+ );
+ await r.claimAndRun();
+ expect(fake.posts()).toBe(before);
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "self-check" });
+ // Back in line with its place kept: the try costs no attempt.
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 0 });
+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: true, why: "self-check", until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
+ expect(pool.workerState(row(w))).toEqual({ state: "comfy-down", words: expect.stringMatching(/face check/) });
+ });
});
describe("results kept until the studio has them", () => {
diff --git a/tests/worker-self-check.test.ts b/tests/worker-self-check.test.ts
new file mode 100644
index 00000000..34d5f329
--- /dev/null
+++ b/tests/worker-self-check.test.ts
@@ -0,0 +1,115 @@
+/**
+ * The worker's face self-check (bin/lib/worker/self-check.mjs): which jobs need it, the graph it sends (every input the
+ * tracking node needs, a new cache key each time), how it reads the report, and one check against a stand-in ComfyUI
+ * (a pass, a collapsed detector, a failed or silent prompt, an upload that didn't go). Never a real ComfyUI.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { detectsFaces, FACE_DETECTOR, FACE_RANGE, faceHeight, facePasses, runSelfCheck, SELF_CHECK_INPUT, SELF_CHECK_PHOTO, selfCheckGraph } from "../bin/lib/worker/self-check.mjs";
+
+const ROOT = path.resolve(__dirname, "..");
+const report = (min: number, mean: number, max: number) =>
+ `subject: select=largest_face index=0, locked on at frame 0 of 1\nfaces: max 1 in one frame\nface height min=${min}px mean=${mean}px max=${max}px\nface fills ~40% of every crop (crop_factor=2.5)`;
+
+type Call = { url: string; init?: RequestInit };
+
+/** A stand-in for its ComfyUI: answers upload, prompt and history the way ComfyUI does. */
+function standIn(o: { text?: string | null; status?: string; uploadOk?: boolean; never?: boolean } = {}) {
+ const calls: Call[] = [];
+ const ok = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
+ const fetchFn = async (url: string, init?: RequestInit) => {
+ calls.push({ url, init });
+ const p = new URL(url).pathname;
+ if (p === "/upload/image") return o.uploadOk === false ? new Response("no", { status: 500 }) : ok({ name: SELF_CHECK_INPUT, subfolder: "", type: "input" });
+ if (p === "/prompt") return ok({ prompt_id: "check-1", number: 0, node_errors: {} });
+ if (p === "/history/check-1") {
+ if (o.never) return ok({});
+ const outputs = o.text === null ? {} : { "3": { text: [o.text ?? report(168, 168, 168)] } };
+ return ok({ "check-1": { status: { status_str: o.status ?? "success", completed: true }, outputs } });
+ }
+ return ok({});
+ };
+ return { fetchFn, calls };
+}
+
+describe("which jobs need the face self-check", () => {
+ it("a graph with the tracking node or the select node does; others don't", () => {
+ expect(detectsFaces({ "6": { class_type: "H3FaceTrackCrop", inputs: {} } })).toBe(true);
+ expect(detectsFaces({ "1": { class_type: "H3FaceSelect", inputs: {} } })).toBe(true);
+ expect(detectsFaces({ "1": { class_type: "LoadImage", inputs: {} }, "2": { class_type: "KSampler", inputs: {} } })).toBe(false);
+ expect(detectsFaces(undefined)).toBe(false);
+ });
+});
+
+describe("the check's graph", () => {
+ it("sets every required input of the tracking node, with the Fix faces graph's detector and confidence", () => {
+ const info = JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/object_info.subset.json"), "utf8"));
+ const required = Object.keys(info.H3FaceTrackCrop.input.required);
+ const g = selfCheckGraph(1);
+ for (const name of required) expect(g["2"].inputs, name).toHaveProperty(name);
+ const fixFaces = JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/video-fix-faces-h3.json"), "utf8"));
+ const track = Object.values(fixFaces as Record<string, { class_type: string; inputs: Record<string, unknown> }>).find((n) => n.class_type === "H3FaceTrackCrop")!;
+ expect(g["2"].inputs.detector).toBe(track.inputs.detector);
+ expect(g["2"].inputs.detector).toBe(FACE_DETECTOR);
+ expect(g["2"].inputs.confidence).toBe(track.inputs.confidence);
+ // The report is the tracking node's fourth output, shown as text.
+ expect(info.H3FaceTrackCrop.output_name[3]).toBe("report");
+ expect(g["3"]).toEqual({ class_type: "PreviewAny", inputs: { source: ["2", 3] } });
+ expect(g["1"].inputs.image).toBe(SELF_CHECK_INPUT);
+ });
+
+ it("changes with each check, so its ComfyUI runs the detector again instead of answering from its cache", () => {
+ expect(JSON.stringify(selfCheckGraph(1))).not.toBe(JSON.stringify(selfCheckGraph(2)));
+ expect(selfCheckGraph(7)["2"].inputs.fallback_detector).toBe("none");
+ });
+
+ it("the fixed photo is there", () => {
+ expect(fs.statSync(SELF_CHECK_PHOTO).size).toBeGreaterThan(10_000);
+ });
+});
+
+describe("reading the report", () => {
+ it("reads the face heights, and passes only inside the range", () => {
+ expect(faceHeight(report(168, 168, 168))).toEqual({ min: 168, mean: 168, max: 168 });
+ expect(faceHeight(report(0, 1, 5))).toEqual({ min: 0, mean: 1, max: 5 });
+ expect(faceHeight("face height min=-0px mean=0px max=4px")).toEqual({ min: -0, mean: 0, max: 4 });
+ expect(faceHeight("No face detected")).toBeNull();
+ expect(facePasses({ min: 168, mean: 168, max: 168 })).toBe(true);
+ expect(facePasses({ min: FACE_RANGE.min, mean: 160, max: FACE_RANGE.max })).toBe(true);
+ expect(facePasses({ min: 3, mean: 3, max: 3 })).toBe(false);
+ expect(facePasses({ min: 120, mean: 140, max: 160 })).toBe(false);
+ expect(facePasses(null)).toBe(false);
+ });
+});
+
+describe("one check against its ComfyUI", () => {
+ const base = "http://127.0.0.1:41234";
+ const fast = { sleep: async () => {}, photo: Buffer.from("jpeg") };
+
+ it("passes on the photo's face, uploads the photo first, and leaves nothing in its history", async () => {
+ const c = standIn();
+ expect(await runSelfCheck(c.fetchFn, base, fast)).toEqual({ ok: true, height: 168 });
+ const paths = c.calls.map((x) => `${x.init?.method ?? "GET"} ${new URL(x.url).pathname}`);
+ expect(paths[0]).toBe("POST /upload/image");
+ expect(paths[1]).toBe("POST /prompt");
+ const del = c.calls.find((x) => new URL(x.url).pathname === "/history" && x.init?.method === "POST");
+ expect(JSON.parse(String(del?.init?.body))).toEqual({ delete: ["check-1"] });
+ expect(c.calls.every((x) => x.url.startsWith(base))).toBe(true);
+ });
+
+ it("fails on a collapsed detector (dozens of 0-5 px boxes)", async () => {
+ expect(await runSelfCheck(standIn({ text: report(0, 1, 5) }).fetchFn, base, fast)).toEqual({ ok: false, height: 1, why: "height" });
+ });
+
+ it("fails when the prompt failed, when there is no report, when the upload didn't go, and when it never finishes", async () => {
+ expect(await runSelfCheck(standIn({ status: "error" }).fetchFn, base, fast)).toMatchObject({ ok: false, why: "failed" });
+ expect(await runSelfCheck(standIn({ text: null }).fetchFn, base, fast)).toMatchObject({ ok: false, why: "no-report" });
+ expect(await runSelfCheck(standIn({ uploadOk: false }).fetchFn, base, fast)).toMatchObject({ ok: false, why: "upload" });
+ let t = 0;
+ const silent = standIn({ never: true });
+ const r = await runSelfCheck(silent.fetchFn, base, { ...fast, now: () => (t += 1000), timeoutMs: 10_000 });
+ expect(r).toMatchObject({ ok: false, why: "timeout" });
+ expect(silent.calls.some((x) => new URL(x.url).pathname === "/interrupt")).toBe(true);
+ });
+});