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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: the owner's jobs run when local ComfyUI work is idle
Adarsh8e9a0acb9c20
diff --git a/bin/lib/worker/local-work.mjs b/bin/lib/worker/local-work.mjsindex 3f73d495..3d50761d 100644--- a/bin/lib/worker/local-work.mjs+++ b/bin/lib/worker/local-work.mjs@@ -1,5 +1,5 @@-// Telling local ComfyUI work apart from other programs (docs/gpu-workers.md, "Studio jobs first"). The worker never-// connects to another ComfyUI. It reads three things only:+// Telling local ComfyUI work apart from other programs (docs/gpu-workers.md, "Studio jobs first"). To tell them apart,+// the worker never connects to another ComfyUI. It reads three things only://// - Windows' table of listening ports (Get-NetTCPConnection -State Listen). Reading the table never connects to a port.// A python process that listens on a port in the local range (worker.json) is local ComfyUI work. The worker's own@@ -11,6 +11,11 @@//// Others = the GPU's total used memory, minus the worker's own ComfyUI, minus local ComfyUI work, minus the desktop's// usual share (measured at setup).+//+// One exception, for the owner's own jobs, which ask local ComfyUI work for no turn: local ComfyUI work that holds the+// GPU's memory is asked whether it runs anything (its /queue, read only). When it runs nothing and has nothing queued,+// it is asked to free its memory (its /free: models unloaded, caches emptied; nothing stops, and it loads them again+// for its next job). Never anything else, and never while it works.import { execFile } from "node:child_process";import fs from "node:fs";import path from "node:path";@@ -159,7 +164,7 @@ export function unknownHolder(counters, listing, ownPid, minMb) {}/**- * Split the GPU's used memory: { ownMb, workMb, othersMb, who, work: { pids, port }, source }.+ * Split the GPU's used memory: { ownMb, workMb, othersMb, who, work: { pids, port (the first), ports (all of them) }, source }.* `who` names the biggest other program (for the busy pause). `source`: "counters", "lock" (the counters failed, the* lock decided) or "total" (neither: everything that isn't the worker's own counts as another program, which fails* safe). `o`: { usedMb, apps (nvidia-smi's, for names), counters, listing, own: { pid, port, running, mb }, ports,@@ -182,7 +187,7 @@ export function splitMemory(o) {const top = others[0];const who = top ? (o.listing.names?.[top.pid] ?? o.apps?.find((a) => a.pid === top.pid)?.name ?? "another program") : "another program";const firstPort = [...work.values()][0] ?? null;- return { ownMb, workMb, othersMb, who, work: { pids: [...work.keys()], port: firstPort }, source: "counters" };+ return { ownMb, workMb, othersMb, who, work: { pids: [...work.keys()], port: firstPort, ports: [...new Set(work.values())] }, source: "counters" };}const rest = Math.max(0, o.usedMb - torchOwn - base);const owners = (o.lockOwners ?? []).map((s) => String(s).toLowerCase()).filter(Boolean);@@ -193,6 +198,35 @@ export function splitMemory(o) {return { ownMb: torchOwn, workMb: 0, othersMb: rest, who: o.lock !== null && o.lock !== undefined ? "another program" : (named ?? "another program"), work: { pids: [], port: null }, source: o.lock !== null && o.lock !== undefined ? "lock" : "total" };}+/** How long a look at local ComfyUI work's /queue or a /free waits for its answer. */+export const LOCAL_ASK_MS = 2000;++/**+ * Local ComfyUI work on these ports runs nothing and has nothing queued: each one's /queue (read only) answers with+ * empty queue_running and queue_pending lists. False when any of them answers anything else or doesn't answer in time.+ */+export async function localIdle(fetchFn, ports, ms = LOCAL_ASK_MS) {+ if (!ports?.length) return false;+ for (const port of ports) {+ try {+ const r = await fetchFn(`http://127.0.0.1:${port}/queue`, { signal: AbortSignal.timeout(ms) });+ if (!r.ok) return false;+ const q = await r.json();+ if (!Array.isArray(q?.queue_running) || !Array.isArray(q?.queue_pending) || q.queue_running.length || q.queue_pending.length) return false;+ } catch {+ return false;+ }+ }+ return true;+}++/** Ask local ComfyUI work on these ports to free its memory (/free: models unloaded, caches emptied). */+export async function freeLocal(fetchFn, ports, ms = LOCAL_ASK_MS) {+ for (const port of ports ?? []) {+ await fetchFn(`http://127.0.0.1:${port}/free`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ unload_models: true, free_memory: true }), signal: AbortSignal.timeout(ms) }).catch(() => null);+ }+}+/** The most `fuobe worker baseline` saves: a desktop alone uses less, so more means another program was open. */export const BASELINE_CAP_MB = 4096;diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 1d905ce8..c3aea241 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -28,7 +28,7 @@ import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, wimport { GpuWatch, othersOf, readGpu, readGpuGen } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";-import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";+import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";import { takeLock, workerLives } from "./lock.mjs";import { finishers } from "./finish.mjs";import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";@@ -91,6 +91,15 @@ export const CLAIM_GAP_MS = 1500;*/export const claimDue = (t, missedAt, claimable = 0, idleMs = IDLE_CLAIM_MS) => t - missedAt >= (claimable > 0 ? Math.min(CLAIM_GAP_MS, idleMs) : idleMs);+/**+ * While the owner's own job waits for this worker and local ComfyUI work keeps the GPU's memory, the worker looks at+ * that work's /queue at most once in this long (ms).+ */+export const IDLE_LOOK_MS = 10_000;++/** After it asked idle local ComfyUI work to free its memory, the worker may take the owner's job for this long (ms). */+export const ROOM_MS = 30_000;+/** A worker token as the studio makes them. */const NEXT_TOKEN = /^fuobe_wkr_[A-Za-z0-9_-]{43}$/;@@ -168,11 +177,13 @@ const arrayBuffer = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + bconst count = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null);/**- * What the beat says for studio jobs first: { claimable }, the beat's claimableNow (people's jobs this worker may take- * now). It is null when the studio doesn't say, and then local ComfyUI work counts as another program, as before.+ * What the beat says for studio jobs first: { claimable, owner }. `claimable` is the beat's claimableNow (people's jobs+ * this worker may take now). It is null when the studio doesn't say, and then local ComfyUI work counts as another+ * program, as before. `owner` is the beat's ownerWaitingNow (the owner's own jobs it may take now; 0 when it doesn't+ * say): they ask for no turn, but idle local ComfyUI work is asked to free its memory for them.*/export function siteOf(answer) {- return { claimable: count(answer?.claimableNow) };+ return { claimable: count(answer?.claimableNow), owner: count(answer?.ownerWaitingNow) ?? 0 };}/**@@ -297,6 +308,13 @@ async function work(saved, deps, owner) {let listedAt = -Infinity;let split = null;let turn = { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null, waitForYield: false, late: false, startsAt: null, ended: null };+ // The owner's own job and local ComfyUI work that keeps memory: when its /queue was last looked at, when it was last+ // asked to free its memory (it may take the owner's job for ROOM_MS after), and whether the log said it waits.+ let idleLookAt = -Infinity;+ let roomAt = -Infinity;+ let ownerWaitSaid = false;+ // Local ComfyUI work is asked with the plain fetch, never the one that carries the worker's token to the studio.+ const localFetch = deps.localFetch ?? globalThis.fetch;let siteWritten = "";let siteAt = 0;let siteFailed = false;@@ -895,8 +913,31 @@ async function work(saved, deps, owner) {if (turns.folderOk() && (beaten || JSON.stringify([turn.siteWaiting, turn.interruptAt]) !== siteWritten || t - siteAt >= 5000)) {writeTurn(t, { siteWaiting: turn.siteWaiting, oldestWaitS: turn.oldestWaitS, interrupt: turn.interrupt, interruptAt: turn.interruptAt });}- // No new job while local ComfyUI work holds the GPU, unless a turn has begun and it made room.- holdBack = turn.waitForYield || (turnsReady(t) && workHolds && turn.siteWaiting === 0) || gpu.busyInARow > 0;+ // The owner's own job asks for no turn. Local ComfyUI work that runs nothing and only keeps its models loaded is+ // asked to free its memory (its /queue read first, then its /free), and the worker takes the job. Work that runs+ // a job, or that can't be asked (no port: the lock decided), is left alone, and the owner's job waits.+ const ownerOnly = turnsReady(t) && workHolds && turn.siteWaiting === 0 && !turn.waitForYield && s.owner > 0 && gpu.busyInARow === 0;+ let roomForOwner = false;+ if (ownerOnly && !busyJob && comfy.ready && mayWork() && !stopNow) {+ if (t - roomAt < ROOM_MS) roomForOwner = true;+ else if (t - idleLookAt >= IDLE_LOOK_MS) {+ idleLookAt = t;+ const ports = split?.work?.ports ?? [];+ if (ports.length && (await localIdle(localFetch, ports))) {+ log(`Local ComfyUI work on port ${ports.join(", ")} runs nothing and keeps its models loaded: asking it to free its memory for the owner's job.`);+ await freeLocal(localFetch, ports);+ roomAt = now();+ roomForOwner = true;+ ownerWaitSaid = false;+ } else if (!ownerWaitSaid) {+ log("The owner's job waits for local ComfyUI work to finish.");+ ownerWaitSaid = true;+ }+ }+ } else if (!ownerOnly) ownerWaitSaid = false;+ // No new job while local ComfyUI work holds the GPU, unless a turn has begun and it made room, or it was idle+ // and freed its memory for the owner's job.+ holdBack = turn.waitForYield || (turnsReady(t) && workHolds && turn.siteWaiting === 0 && !roomForOwner) || gpu.busyInARow > 0;}// Kept results go up before its ComfyUI starts (they need none, and a start can take minutes), unless the studio// said a moment ago that their job isn't this worker's now.diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 8f067a54..f911705c 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -288,7 +288,8 @@ A PC can also run ComfyUI work of its own: a ComfyUI that you use by hand, or aComfyUI work runs whenever no studio job waits. Any other program (a game, Blender, a video editor) still pauses theworker, as above.-The worker never connects to your other ComfyUIs. It reads three things only:+To tell local ComfyUI work apart, the worker never connects to your other ComfyUIs (the only exception is for the+owner's own jobs, below). It reads three things only:1. **Windows' table of listening ports** (`Get-NetTCPConnection -State Listen`). Reading the table connects tonothing. A python process that listens on a port in `localComfyPorts` (8188 to 8199) is local ComfyUI work. The@@ -338,6 +339,16 @@ and in its beat (`waiting-for-yield:no-answer`). It goes on waiting, with the joSettings → Workers shows "Waiting for local ComfyUI work to make room", with the helper's estimate of the start whenthere is one, never "Ready".+**The owner's own jobs.** They ask for no turn, and `siteWaiting` does not count them. While one of them waits for+this worker (the beat's `ownerWaitingNow`) and only local ComfyUI work holds the GPU, the worker reads that work's+`/queue` on its port (at most once in 10 seconds). It never does anything else to it:++- If it runs a job or has one queued, the worker leaves it alone, and the owner's job keeps its place in line.+- If it runs nothing and has nothing queued, it only keeps its models loaded. The worker asks it to free its memory+ (`POST /free` with `unload_models` and `free_memory`; nothing stops, and it loads its models again for its next+ job), and then takes the owner's job.+- With no port to ask (the GPU lock decided, because the counters can't be read), the owner's job waits.+**Limits that only the PC sets.** The studio can never change these:- `yieldMaxHoursPerDay` (20): the most hours of turns in one day, on the PC's clock. After that, local ComfyUI work@@ -802,7 +813,8 @@ its target), at most once an hour each.with no answer, `why` is `"waiting-for-yield:no-answer"`. The worker may still take jobs, and its jobs keep theirplace.- The answer also carries `claimableNow`, for studio jobs first: the number of people's jobs (never the owner's own)- that this worker may take now. It counts the jobs in the worker's pool that it can run (its lanes, files and VRAM)+ that this worker may take now. `ownerWaitingNow` is the same count for the owner's own jobs: they ask for no turn,+ but idle local ComfyUI work is asked to free its memory for them. It counts the jobs in the worker's pool that it can run (its lanes, files and VRAM)and that end before its hours do. It is 0 while the worker is paused on the website, drains, is outside its hoursor runs an older worker program. The worker's own pause on the PC does not change it. The answer has no wait timeand no request to interrupt local work: the worker measures `oldestWaitS` itself.diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex d399f468..e9a5380d 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -251,7 +251,7 @@ export function cleanBeat(b: unknown): WorkerBeat {* A worker says it is here: its own pause and why, its GPU, its facts, what it runs. The answer: whether it is paused on* the website, a stop-now, drain, its hours, the lanes it is allowed, and the prompts to take off its ComfyUI.*/-export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAnswer & { worker: WorkerAnswer } {+export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAnswer & { worker: WorkerAnswer; ownerWaitingNow: number } {const d = db();const device = `wkr-${w.id}`;// With the write lock from the start (IMMEDIATE): what it reads of the line is still so when it writes, even while@@ -313,6 +313,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAheldElsewhere: false,waiting,claimableNow: claimableNow(fresh, now),+ ownerWaitingNow: ownerWaitingNow(fresh, now),stops,worker: {paused: !!fresh.paused_server,@@ -341,11 +342,23 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA* website, a drain, an older worker program or being outside its hours does.*/export function claimableNow(w: WorkerRow, now = Date.now()): number {+ return gpuClaimable(w, now, "people");+}++/**+ * The owner's own tasks this worker may claim right now, by the same rules as claimableNow. They never ask local+ * ComfyUI work to make room: its machine reads this only to let an idle local ComfyUI free the memory it keeps.+ */+export function ownerWaitingNow(w: WorkerRow, now = Date.now()): number {+ return gpuClaimable(w, now, "owner");+}++function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): number {if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;// Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room (left out in the query, so a long// line of CPU work never hides the GPU's).const rows = db()- .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS NOT NULL AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}ORDER BY ${LINE_ORDER} LIMIT ?`)+ .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS ${whose === "people" ? "NOT NULL" : "NULL"} AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}ORDER BY ${LINE_ORDER} LIMIT ?`).all(`,${w.pool},`, LOOK_AT) as TaskRow[];return rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;}diff --git a/tests/recovery-worker.test.ts b/tests/recovery-worker.test.tsindex 98a47752..004f668e 100644--- a/tests/recovery-worker.test.ts+++ b/tests/recovery-worker.test.ts@@ -349,6 +349,8 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {log: (line: string) => void p.logs.push(line),composer,catalogVersion: program.catalogVersion,+ // Local ComfyUI work is never a real port here (it answers nothing, so it is never taken for idle).+ localFetch: async () => new Response("not here", { status: 404 }),// The folders are looked at again on both clocks: a full rescan, and the check for model folders that were missing....(o.rescanMs && { rescanMs: o.rescanMs, modelsCheckMs: o.rescanMs }),...o.gpu,diff --git a/tests/worker-queue.test.ts b/tests/worker-queue.test.tsindex bd8314d6..c2cd6aaf 100644--- a/tests/worker-queue.test.ts+++ b/tests/worker-queue.test.ts@@ -281,6 +281,20 @@ describe("the beat", () => {pool.patchWorker(w.id, { paused: true });expect(beatAs(w).claimableNow).toBe(0);});++ it("says apart how many of the owner's own tasks this worker may claim now, by the same rules", () => {+ const w = standInWorker();+ accountTask();+ const owner = accountTask();+ const other = accountTask();+ db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL WHERE id IN (?, ?)").run(owner.id, other.id);+ expect(beatAs(w)).toMatchObject({ claimableNow: 1, ownerWaitingNow: 2 });+ // One it can't run (another pool) doesn't count.+ db().prepare("UPDATE relay_tasks SET pools = 'elsewhere' WHERE id = ?").run(other.id);+ expect(beatAs(w).ownerWaitingNow).toBe(1);+ pool.patchWorker(w.id, { paused: true });+ expect(beatAs(w)).toMatchObject({ claimableNow: 0, ownerWaitingNow: 0 });+ });});describe("the workers' measured run reaches the billing service", () => {diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsindex 3b3879a9..6c3d42cf 100644--- a/tests/worker-turns-run.test.ts+++ b/tests/worker-turns-run.test.ts@@ -8,6 +8,8 @@* - A game holds the GPU: the busy pause, and no turn is asked for.* - The studio doesn't say what the worker can take: local ComfyUI work pauses it, as before.* - Me first: the pause shortcut during a turn writes siteWaiting 0, and the job keeps its place.+ * - Only the owner's own job waits: no turn. Local ComfyUI work that runs a job is left alone; once it runs nothing, it+ * is asked to free its memory (its /queue read, then its /free) and the worker takes the job.* - The counters fail: a lock that names ComfyUI work leads to a turn.*/import fs from "node:fs";@@ -186,7 +188,27 @@ afterEach(async () => {}});-function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: string[]; studio?: { older: boolean } } = {}) {+/**+ * Local ComfyUI work as the worker reaches it (deps.localFetch, never a real port): its /queue says whether it runs a+ * job (`busy`), its /free empties its memory (`onFree`). Every request is noted.+ */+function fakeLocal(o: { busy: boolean; onFree?: () => void }) {+ const calls: string[] = [];+ const fetch = async (url: string, init: RequestInit = {}) => {+ const u = new URL(url);+ calls.push(`${init.method ?? "GET"} ${u.host}${u.pathname}`);+ if (u.pathname === "/queue" && (init.method ?? "GET") === "GET") return Response.json({ queue_running: o.busy ? [[1, "local-job", {}, {}, []]] : [], queue_pending: [] });+ if (u.pathname === "/free" && init.method === "POST") {+ expect(JSON.parse(String(init.body))).toEqual({ unload_models: true, free_memory: true });+ o.onFree?.();+ return new Response(null, { status: 200 });+ }+ return new Response("not here", { status: 404 });+ };+ return { o, calls, fetch };+}++function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: string[]; studio?: { older: boolean }; local?: ReturnType<typeof fakeLocal> } = {}) {const ctrl = new AbortController();const cfg = {site: SITE,@@ -219,6 +241,8 @@ function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: scatalogVersion: "a".repeat(64),gpuEveryMs: 200,turnGraceMs: 1500,+ // Local ComfyUI work is never a real port here: busy unless the test says otherwise.+ localFetch: (o.local ?? fakeLocal({ busy: true })).fetch,...gpu,});const r = { ctrl, done };@@ -316,11 +340,12 @@ describe("studio jobs first", () => {expect(p.logs.some((l) => /no longer keeps it paused/.test(l))).toBe(true);});- it("only the owner's own job waits: the studio counts none, so no turn is asked for and local ComfyUI work goes on", async () => {+ it("only the owner's own job waits: the studio counts none, so no turn is asked for and local ComfyUI work that runs a job goes on", async () => {const w = addWorker();const p = pc();const id = addTask({ owner: true });- start(w, p, fakeGpu(p, { workMb: 9000 }));+ const local = fakeLocal({ busy: true });+ start(w, p, fakeGpu(p, { workMb: 9000 }), { local });// The studio's real beat says 0 (not "unknown"): turns work, local ComfyUI work is no other program, and no// turn begins for the owner's own job.await until(() => comfyAnswers(p));@@ -330,6 +355,32 @@ describe("studio jobs first", () => {expect(workerRow(w).local_why).toBeNull();expect(task(id).state).toBe("waiting");expect(p.logs.some((l) => /make room|Another program/.test(l))).toBe(false);+ // It only looked at the local work's queue: never asked it to free anything while it works.+ expect(local.calls.length).toBeGreaterThan(0);+ expect(new Set(local.calls)).toEqual(new Set(["GET 127.0.0.1:8188/queue"]));+ expect(p.logs.some((l) => /owner's job waits for local ComfyUI work to finish/.test(l))).toBe(true);+ });++ it("only the owner's own job waits and local ComfyUI work runs nothing: it is asked to free its memory, and the job runs", async () => {+ const w = addWorker();+ const p = pc();+ const id = addTask({ owner: true });+ const gpu = { workMb: 9000 };+ const local = fakeLocal({ busy: true, onFree: () => (gpu.workMb = 400) });+ start(w, p, fakeGpu(p, gpu), { local });+ await until(() => comfyAnswers(p));+ await sleep(1500);+ expect(task(id).state).toBe("waiting");+ // Its local job ends; the models stay loaded.+ local.o.busy = false;+ await until(() => task(id).state !== "waiting", 30_000);+ expect(local.calls).toContain("POST 127.0.0.1:8188/free");+ expect(local.calls.every((c) => c === "GET 127.0.0.1:8188/queue" || c === "POST 127.0.0.1:8188/free")).toBe(true);+ expect(p.logs.some((l) => /runs nothing and keeps its models loaded/.test(l))).toBe(true);+ expect((await until(() => ["done", "failed"].includes(task(id).state) && task(id), 60_000)).state).toBe("done");+ // It never asked for room, and never paused; a minute after the job (shortened here) it writes 0 again.+ expect(p.logs.some((l) => /make room|Another program/.test(l))).toBe(false);+ await until(() => site(p)?.siteWaiting === 0, 20_000);});it("me first: the pause shortcut during a turn writes siteWaiting 0 and keeps the job in line; a resume asks again", async () => {diff --git a/tests/worker-turns.test.ts b/tests/worker-turns.test.tsindex a3037b54..51689be1 100644--- a/tests/worker-turns.test.ts+++ b/tests/worker-turns.test.ts@@ -7,7 +7,7 @@ import fs from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";import { GpuWatch } from "../bin/lib/worker/gpu.mjs";-import { BASELINE_CAP_MB, measureBaseline, parseCounters, parseListeners, pickGpu, readLock, splitMemory, unknownHolder, workPids } from "../bin/lib/worker/local-work.mjs";+import { BASELINE_CAP_MB, freeLocal, localIdle, measureBaseline, parseCounters, parseListeners, pickGpu, readLock, splitMemory, unknownHolder, workPids } from "../bin/lib/worker/local-work.mjs";import { readYielded, SiteTurns, TURNS, writeSite } from "../bin/lib/worker/turns.mjs";import { siteOf } from "../bin/lib/worker/run.mjs";import { tempDir } from "./helpers/temp-dir";@@ -79,7 +79,34 @@ describe("the port table and the GPU counters", () => {expect(s.ownMb).toBe(2000);expect(s.workMb).toBe(9000);expect(s.othersMb).toBe(0);- expect(s.work).toEqual({ pids: [4242, 4400], port: 8188 });+ expect(s.work).toEqual({ pids: [4242, 4400], port: 8188, ports: [8188, 8191] });+ });++ it("asks local ComfyUI work only whether it runs anything, and to free its memory: idle means both its lists are empty", async () => {+ const calls: string[] = [];+ const queues: Record<number, unknown> = { 8188: { queue_running: [], queue_pending: [] }, 8191: { queue_running: [], queue_pending: [[2, "p", {}, {}, []]] } };+ const fetchFn = async (url: string, init: RequestInit = {}) => {+ const u = new URL(url);+ calls.push(`${init.method ?? "GET"} ${u.host}${u.pathname}${init.body ? ` ${String(init.body)}` : ""}`);+ if (u.port === "8199") throw new Error("refused");+ return u.pathname === "/queue" ? Response.json(queues[Number(u.port)] ?? {}) : new Response(null, { status: 200 });+ };+ expect(await localIdle(fetchFn, [8188])).toBe(true);+ // One with a queued job, one that doesn't answer, one that answers something else: not idle.+ expect(await localIdle(fetchFn, [8188, 8191])).toBe(false);+ expect(await localIdle(fetchFn, [8199])).toBe(false);+ expect(await localIdle(fetchFn, [8190])).toBe(false);+ expect(await localIdle(fetchFn, [])).toBe(false);+ await freeLocal(fetchFn, [8188, 8199]);+ expect(calls).toEqual([+ "GET 127.0.0.1:8188/queue",+ "GET 127.0.0.1:8188/queue",+ "GET 127.0.0.1:8191/queue",+ "GET 127.0.0.1:8199/queue",+ "GET 127.0.0.1:8190/queue",+ 'POST 127.0.0.1:8188/free {"unload_models":true,"free_memory":true}',+ 'POST 127.0.0.1:8199/free {"unload_models":true,"free_memory":true}',+ ]);});it("a game holds memory: others above the busy line, and the game is named", () => {@@ -308,14 +335,21 @@ describe("turns", () => {});it("reads only the beat's claimableNow (a count); absent, or anything else, means the studio doesn't say", () => {- expect(siteOf({ claimableNow: 2 })).toEqual({ claimable: 2 });- expect(siteOf({ claimableNow: 0 })).toEqual({ claimable: 0 });+ expect(siteOf({ claimableNow: 2 })).toEqual({ claimable: 2, owner: 0 });+ expect(siteOf({ claimableNow: 0 })).toEqual({ claimable: 0, owner: 0 });// Fields the protocol doesn't have are not read.- expect(siteOf({ worker: { claimableNow: 1, yieldInterrupt: true }, oldestWaitS: 40 })).toEqual({ claimable: null });- expect(siteOf({ waiting: 9, claimableNow: -1, worker: {} })).toEqual({ claimable: null });+ expect(siteOf({ worker: { claimableNow: 1, yieldInterrupt: true }, oldestWaitS: 40 })).toEqual({ claimable: null, owner: 0 });+ expect(siteOf({ waiting: 9, claimableNow: -1, worker: {} })).toEqual({ claimable: null, owner: 0 });expect(siteOf(null).claimable).toBeNull();});+ it("reads the beat's ownerWaitingNow (a count) apart: 0 when the studio doesn't say", () => {+ expect(siteOf({ claimableNow: 0, ownerWaitingNow: 3 })).toEqual({ claimable: 0, owner: 3 });+ expect(siteOf({ claimableNow: 1, ownerWaitingNow: -2 })).toEqual({ claimable: 1, owner: 0 });+ expect(siteOf({ claimableNow: 1, ownerWaitingNow: "2" })).toEqual({ claimable: 1, owner: 0 });+ expect(siteOf({ waiting: 4 }).owner).toBe(0);+ });+it("the oldest wait: how long this worker has seen people's jobs waiting for it", () => {const { turns } = setup();expect(turns.step(T0, { ...facts, workHolds: false }).oldestWaitS).toBe(0);