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: no busy pause from the worker's own memory during its job
Adarsha72a25128cd1
diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsindex dcbc104a..19d5c738 100644--- a/bin/lib/worker/gpu.mjs+++ b/bin/lib/worker/gpu.mjs@@ -7,6 +7,14 @@ import { execFile } from "node:child_process";/** Memory a ComfyUI's CUDA context takes beyond what torch reports. */export const CONTEXT_ALLOWANCE_MB = 600;+/** Busy readings during its own job pause it only once they have lasted this long (the job is kept if they end sooner). */+export const MID_JOB_GRACE_MS = 20_000;+/** A pause whose busy readings ended within this time of its start was brief: its cool-down is BRIEF_COOL_DOWN_MS. */+export const BRIEF_PAUSE_MS = 30_000;+export const BRIEF_COOL_DOWN_MS = 2 * 60_000;+/** At most one shortened cool-down in this time (a program that keeps coming back gets the whole one). */+export const BRIEF_EVERY_MS = 60 * 60_000;+const num = (s) => {const v = Number(String(s ?? "").trim());return Number.isFinite(v) ? v : null;@@ -71,26 +79,52 @@ export async function readGpuGen(cmd = "nvidia-smi") {return parseGpuGen(await run(bin, [...pre, "--query-gpu=compute_cap", "--format=csv,noheader"]));}+const DESKTOP = new Set(+ "dwm explorer csrss winlogon shellhost shellexperiencehost startmenuexperiencehost searchhost searchapp textinputhost lockapp applicationframehost systemsettings crossdeviceresume widgets widgetservice phoneexperiencehost msedge msedgewebview2 chrome firefox brave opera code nvcontainer rustdesk anydesk teamviewer teams ms-teams discord slack spotify"+ .split(" ")+ .concat(["nvidia overlay", "nvidia share", "nvidia app"]),+);++/** A desktop or system process (the compositor, the shell, browsers, editors, overlays): never named as the cause. */+export function isDesktop(name) {+ return DESKTOP.has(String(name ?? "").trim().toLowerCase().replace(/\.exe$/i, ""));+}++/**+ * What its own ComfyUI holds: { mb, sure }. nvidia-smi's number for its process when it gives one (sure); else what torch+ * reports plus the context allowance, a lower bound only (not sure): weights that ComfyUI's dynamic VRAM keeps outside+ * torch's allocator aren't in it, and the read gives null when ComfyUI is slow to answer.+ */+export function ownOf(own, apps = []) {+ if (!own.running) return { mb: 0, sure: true };+ const app = own.pid ? apps.find((a) => a.pid === own.pid && a.usedMb !== null) : null;+ if (app) return { mb: app.usedMb, sure: true };+ return { mb: (own.mb ?? 0) + CONTEXT_ALLOWANCE_MB, sure: false };+}+/*** Is another program using the GPU? Others' VRAM is the GPU's used memory minus what the worker's own ComfyUI holds- * (`ownMb`, with an allowance for its CUDA context while it runs). Busy above `busyVramMb`, or when another process- * shows its own use above it. The total rule always works, also when per-process memory reads [N/A].+ * (ownOf). Busy above `busyVramMb`, or when another process (not a desktop one) shows its own use above it. The total+ * rule always works, also when per-process memory reads [N/A]. `unsure`: busy only by the total rule while its own job runs (`own.job`)+ * and its own share isn't known per process; GpuWatch skips such a reading.*/export function othersOf(reading, own, busyVramMb) {- const ownMb = own.running ? (own.mb ?? 0) + CONTEXT_ALLOWANCE_MB : 0;- const othersMb = Math.max(0, reading.usedMb - ownMb);- const others = reading.apps.filter((a) => a.pid !== own.pid);+ const mine = ownOf(own, reading.apps);+ const othersMb = Math.max(0, reading.usedMb - mine.mb);+ const others = reading.apps.filter((a) => a.pid !== own.pid && !isDesktop(a.name));const loud = others.find((a) => a.usedMb !== null && a.usedMb > busyVramMb);const busy = othersMb > busyVramMb || !!loud;const who = loud?.name ?? others.find((a) => a.usedMb === null || a.usedMb > 0)?.name ?? (busy ? "another program" : null);- return { busy, othersMb, who };+ return { busy, othersMb, who, unsure: busy && !loud && !!own.job && !mine.sure };}/*** The automatic pause and resume. `update` takes each reading's verdict; `paused` says whether the GPU keeps the worker- * paused now. Busy pauses after `busyReadings` busy readings in a row (1, the default: at once); with `autoResume`, it- * resumes once the GPU stayed free for `resumeAfterMs` in a row and is cooler than `resumeBelowC`. Any busy reading- * starts the cool-down again. Without autoResume, only `clear()` (a resume by hand) ends it.+ * paused now. Busy pauses after `busyReadings` busy readings in a row (1, the default: at once), and during its own job+ * (`verdict.job`) only once they have lasted `graceMs`; an unsure verdict is skipped. With `autoResume`, it resumes+ * once the GPU stayed free for `resumeAfterMs` in a row and is cooler than `resumeBelowC` (`briefResumeMs` after a+ * pause whose busy readings ended within `briefMs`, at most once per `briefEveryMs`). Any busy reading starts the+ * cool-down again. Without autoResume, only `clear()` (a resume by hand) ends it.*/export class GpuWatch {constructor(o) {@@ -99,15 +133,24 @@ export class GpuWatch {this.who = null;this.freeSince = null;this.busyInARow = 0;+ this.busySince = null;+ this.pausedAt = null;+ this.lastBusyAt = null;+ this.briefAt = null;/** What the last busy reading saw: "work" for local ComfyUI work only (studio jobs first), else null. */this.cause = null;}update(verdict, tempC, now) {+ if (verdict.unsure) return;if (verdict.busy) {this.busyInARow++;+ this.busySince ??= now;+ this.lastBusyAt = now;this.freeSince = null;- if (this.paused || this.busyInARow >= (this.o.busyReadings ?? 1)) {+ const wait = verdict.job ? (this.o.graceMs ?? 0) : 0;+ if (this.paused || (this.busyInARow >= (this.o.busyReadings ?? 1) && now - this.busySince >= wait)) {+ if (!this.paused) this.pausedAt = now;this.paused = true;this.who = verdict.who;this.cause = verdict.cause ?? null;@@ -115,10 +158,14 @@ export class GpuWatch {return;}this.busyInARow = 0;+ this.busySince = null;this.freeSince ??= now;- if (this.paused && this.o.autoResume && now - this.freeSince >= this.o.resumeAfterMs && (tempC === null || tempC === undefined || tempC < this.o.resumeBelowC)) {+ const brief = !!this.o.briefMs && this.lastBusyAt - this.pausedAt <= this.o.briefMs && (this.briefAt === null || now - this.briefAt >= (this.o.briefEveryMs ?? 0));+ const coolMs = brief ? Math.min(this.o.briefResumeMs ?? this.o.resumeAfterMs, this.o.resumeAfterMs) : this.o.resumeAfterMs;+ if (this.paused && this.o.autoResume && now - this.freeSince >= coolMs && (tempC === null || tempC === undefined || tempC < this.o.resumeBelowC)) {this.paused = false;this.who = null;+ if (brief && coolMs < this.o.resumeAfterMs) this.briefAt = now;}}@@ -127,6 +174,7 @@ export class GpuWatch {this.paused = false;this.who = null;this.busyInARow = 0;+ this.busySince = null;this.cause = null;}}diff --git a/bin/lib/worker/local-work.mjs b/bin/lib/worker/local-work.mjsindex 3d50761d..20f85336 100644--- a/bin/lib/worker/local-work.mjs+++ b/bin/lib/worker/local-work.mjs@@ -19,7 +19,7 @@import { execFile } from "node:child_process";import fs from "node:fs";import path from "node:path";-import { CONTEXT_ALLOWANCE_MB } from "./gpu.mjs";+import { isDesktop, ownOf } from "./gpu.mjs";/** ComfyUI's own default port and the next few: where local ComfyUIs listen unless worker.json says otherwise. */export const DEFAULT_PORTS = [8188, 8199];@@ -164,7 +164,8 @@ export function unknownHolder(counters, listing, ownPid, minMb) {}/**- * Split the GPU's used memory: { ownMb, workMb, othersMb, who, work: { pids, port (the first), ports (all of them) }, source }.+ * Split the GPU's used memory: { ownMb, ownSure, workMb, othersMb, who, work: { pids, port (the first), ports (all of them) }, source }.+ * `ownSure`: its own ComfyUI's share was read per process (ownOf), not only as torch's lower bound.* `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,@@ -172,7 +173,8 @@ export function unknownHolder(counters, listing, ownPid, minMb) {*/export function splitMemory(o) {const base = Math.max(0, Number(o.baselineMb) || 0);- const torchOwn = o.own.running ? (o.own.mb ?? 0) + CONTEXT_ALLOWANCE_MB : 0;+ const fallback = ownOf(o.own, o.apps);+ const fallbackMb = fallback.mb;if (o.counters && o.listing) {const { own, work } = workPids(o.listing, { ports: o.ports, ownPid: o.own.pid, ownPort: o.own.port, excludePorts: o.excludePorts, excludePids: o.excludePids });const gpu = pickGpu(o.counters, o.gpu);@@ -180,22 +182,22 @@ export function splitMemory(o) {const sum = (pids) => mine.filter((c) => pids.has(c.pid)).reduce((n, c) => n + c.mb, 0);const counted = sum(own);// Its own ComfyUI before the counters list it: what torch says, as before.- const ownMb = counted > 0 ? counted : torchOwn;+ const ownMb = counted > 0 ? counted : fallbackMb;const workMb = sum(new Set(work.keys()));const othersMb = Math.max(0, o.usedMb - ownMb - workMb - base);- const others = mine.filter((c) => !own.has(c.pid) && !work.has(c.pid) && c.mb > 0).sort((a, b) => b.mb - a.mb);- 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 nameOf = (pid) => o.listing.names?.[pid] ?? o.apps?.find((a) => a.pid === pid)?.name ?? null;+ const top = mine.filter((c) => !own.has(c.pid) && !work.has(c.pid) && c.mb > 0 && !isDesktop(nameOf(c.pid))).sort((a, b) => b.mb - a.mb)[0];+ const who = (top && nameOf(top.pid)) ?? "another program";const firstPort = [...work.values()][0] ?? null;- return { ownMb, workMb, othersMb, who, work: { pids: [...work.keys()], port: firstPort, ports: [...new Set(work.values())] }, source: "counters" };+ return { ownMb, ownSure: counted > 0 || fallback.sure, 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 rest = Math.max(0, o.usedMb - fallbackMb - base);const owners = (o.lockOwners ?? []).map((s) => String(s).toLowerCase()).filter(Boolean);if (o.lock !== null && o.lock !== undefined && owners.some((w) => String(o.lock).toLowerCase().startsWith(w))) {- return { ownMb: torchOwn, workMb: rest, othersMb: 0, who: null, work: { pids: [], port: null, lock: true }, source: "lock" };+ return { ownMb: fallbackMb, ownSure: fallback.sure, workMb: rest, othersMb: 0, who: null, work: { pids: [], port: null, lock: true }, source: "lock" };}- const named = o.apps?.find((a) => a.pid !== o.own.pid && (a.usedMb === null || a.usedMb > 0))?.name;- 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" };+ const named = o.apps?.find((a) => a.pid !== o.own.pid && (a.usedMb === null || a.usedMb > 0) && !isDesktop(a.name))?.name;+ return { ownMb: fallbackMb, ownSure: fallback.sure, 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. */diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 96288822..ec0ebaea 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -25,7 +25,7 @@ import { StayAwake } from "./awake.mjs";import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";-import { GpuWatch, othersOf, readGpu, readGpuGen } from "./gpu.mjs";+import { BRIEF_COOL_DOWN_MS, BRIEF_EVERY_MS, BRIEF_PAUSE_MS, GpuWatch, MID_JOB_GRACE_MS, othersOf, readGpu, readGpuGen } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders, runtimeFileList } from "./inventory.mjs";import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";@@ -191,7 +191,8 @@ export function siteOf(answer) {* "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,* signal, requirements, ComputerRunner, rules, pins, runtime (the run-time files it verifies: inventory.mjs* runtimeFileList), allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own options), readCounters,- * readListeners, gpuEveryMs, readGpuGen, idleClaimMs (IDLE_CLAIM_MS), canCleanPictures, and for job tickets: composer+ * readListeners, gpuEveryMs, gpuGraceMs (MID_JOB_GRACE_MS), gpuBriefMs (BRIEF_PAUSE_MS), readGpuGen, idleClaimMs+ * (IDLE_CLAIM_MS), canCleanPictures, and for job tickets: composer* (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, and codeWatch (update.mjs's CodeWatch: new* code on disk ends it with "update" once its jobs are done) }.*/@@ -264,8 +265,18 @@ async function work(saved, deps, owner) {: null;if (turns && !turns.folderOk()) log(`The turns folder ${cfg.yieldFolder} isn't there: local ComfyUI work counts as another program until it is.`);const busyMb = cfg.busyVramMb ?? 1024;- // Two busy readings in a row pause it when it tells programs apart (a reading can catch memory on its way).- const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75, busyReadings: turns ? 2 : 1 });+ // Two busy readings in a row pause it when it tells programs apart (a reading can catch memory on its way); during+ // its own job, only busy readings that last the grace time.+ const gpu = new GpuWatch({+ autoResume: !!cfg.autoResume,+ resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000,+ resumeBelowC: cfg.resumeBelowC ?? 75,+ busyReadings: turns ? 2 : 1,+ graceMs: deps.gpuGraceMs ?? MID_JOB_GRACE_MS,+ briefMs: deps.gpuBriefMs ?? BRIEF_PAUSE_MS,+ briefResumeMs: BRIEF_COOL_DOWN_MS,+ briefEveryMs: BRIEF_EVERY_MS,+ });const awake = deps.awake ?? new StayAwake({ now, log });// Its GPU's generation, once (tests give their own reader: the GPU's own tool is never run there).gpuGen = await (deps.readGpuGen ?? (deps.readGpu ? async () => null : () => readGpuGen(cfg.nvidiaSmi)))().catch(() => null);@@ -815,7 +826,7 @@ async function work(saved, deps, owner) {lastGpuAt = t;const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);if (reading) {- const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null };+ const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null, job: busyJob && jobUsesGpu };let verdict;if (turns) {split = await splitNow(t, reading, own);@@ -823,17 +834,18 @@ async function work(saved, deps, owner) {// otherwise it counts as another program, as before.const othersBusy = split.othersMb > busyMb;const workBusy = !turnsReady(t) && split.workMb > busyMb;- verdict = { busy: othersBusy || workBusy, who: othersBusy ? split.who : `ComfyUI${split.work.port ? ` on port ${split.work.port}` : ""}`, othersMb: split.othersMb, cause: othersBusy ? null : "work" };+ const busy = othersBusy || workBusy;+ verdict = { busy, who: othersBusy ? split.who : `ComfyUI${split.work.port ? ` on port ${split.work.port}` : ""}`, othersMb: split.othersMb, cause: othersBusy ? null : "work", unsure: busy && own.job && !split.ownSure, job: own.job, source: split.source };// A pause that only local ComfyUI work caused ends once turns work again (the next day, the folder back).if (!verdict.busy && gpu.paused && gpu.cause === "work") {gpu.clear();log("Local ComfyUI work no longer keeps it paused: back to work.");}- } else verdict = othersOf(reading, own, busyMb);+ } else verdict = { ...othersOf(reading, own, busyMb), job: own.job };const was = gpu.paused;gpu.update(verdict, reading.tempC, t);gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC };- if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing.`);+ if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing (${Math.round(verdict.othersMb ?? 0)} MB not its own${verdict.source ? `, by ${verdict.source}` : ""}).`);if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");}}diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.tsindex 09dc4947..2e6fdcf6 100644--- a/tests/worker-program.test.ts+++ b/tests/worker-program.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import net from "node:net";import path from "node:path";import { describe, expect, it } from "vitest";-import { GpuWatch, othersOf, parseApps, parseGpu } from "../bin/lib/worker/gpu.mjs";+import { GpuWatch, othersOf, ownOf, parseApps, parseGpu } from "../bin/lib/worker/gpu.mjs";import { cleanJob, vetGraph } from "../bin/lib/worker/checks.mjs";import { comfyArgs, OwnComfy, PortBusy, portFree } from "../bin/lib/worker/comfy.mjs";import { parseFor, syncedFolder } from "../bin/lib/worker/config.mjs";@@ -32,6 +32,78 @@ describe("the GPU check (check 11)", () => {expect(othersOf({ usedMb: 300, apps: [{ pid: 9, name: "game.exe", usedMb: 2000 }] }, { running: false }, 1024)).toMatchObject({ busy: true, who: "game.exe" });});+ it("during its own job, its memory that torch doesn't report (or a slow read) is no other program's: an unsure reading", () => {+ // A 20 GB model in ComfyUI's dynamic VRAM: torch reports 2 GB, or nothing when ComfyUI is slow to answer.+ const reading = { usedMb: 23_000, apps: [{ pid: 9, name: "ShellHost.exe", usedMb: null }] };+ for (const mb of [2000, null]) {+ expect(othersOf(reading, { running: true, mb, pid: 77, job: true }, 1024)).toMatchObject({ busy: true, unsure: true });+ // Between jobs it still counts (no job to lose): the busy pause, as before.+ expect(othersOf(reading, { running: true, mb, pid: 77 }, 1024)).toMatchObject({ busy: true, unsure: false });+ }+ // nvidia-smi's number for its own process, when it gives one, is its share: sure.+ expect(ownOf({ running: true, mb: 2000, pid: 77 }, [{ pid: 77, name: "python", usedMb: 21_500 }])).toEqual({ mb: 21_500, sure: true });+ expect(othersOf({ usedMb: 23_000, apps: [{ pid: 77, name: "python", usedMb: 21_500 }] }, { running: true, mb: 2000, pid: 77, job: true }, 1024)).toMatchObject({ busy: true, unsure: false });+ expect(othersOf({ usedMb: 22_000, apps: [{ pid: 77, name: "python", usedMb: 21_500 }] }, { running: true, mb: 2000, pid: 77, job: true }, 1024).busy).toBe(false);+ // A desktop process is never "loud" on its own, nor named.+ expect(othersOf({ usedMb: 2500, apps: [{ pid: 8, name: "msedge.exe", usedMb: 2000 }, { pid: 9, name: "dwm.exe", usedMb: null }] }, { running: false }, 1024)).toMatchObject({ busy: true, who: "another program" });+ expect(othersOf({ usedMb: 300, apps: [{ pid: 8, name: "Code.exe", usedMb: 2000 }] }, { running: false }, 1024).busy).toBe(false);+ // Another process that shows its own use is sure, job or not.+ expect(othersOf({ usedMb: 23_000, apps: [{ pid: 5, name: "game.exe", usedMb: 4000 }] }, { running: true, mb: 2000, pid: 77, job: true }, 1024)).toMatchObject({ busy: true, unsure: false, who: "game.exe" });+ });++ it("skips unsure readings: they neither pause nor end a pause", () => {+ const g = new GpuWatch({ autoResume: true, resumeAfterMs: 10 * MIN, resumeBelowC: 75, busyReadings: 2 });+ for (let t = 0; t < 60_000; t += 5000) g.update({ busy: true, unsure: true, who: "another program", job: true }, 60, t);+ expect(g.paused).toBe(false);+ expect(g.busyInARow).toBe(0);+ });++ it("during its own job, busy readings pause it only once they lasted the grace time; a game that stays still pauses it", () => {+ const opts = { autoResume: true, resumeAfterMs: 10 * MIN, resumeBelowC: 75, busyReadings: 2, graceMs: 20_000 };+ const g = new GpuWatch(opts);+ for (let t = 0; t <= 15_000; t += 5000) g.update({ busy: true, who: "game", job: true }, 60, t);+ expect(g.paused).toBe(false);+ g.update({ busy: false, job: true }, 60, 20_000);+ g.update({ busy: true, who: "game", job: true }, 60, 25_000);+ g.update({ busy: true, who: "game", job: true }, 60, 30_000);+ expect(g.paused).toBe(false);+ g.update({ busy: true, who: "game", job: true }, 60, 45_000);+ expect(g.paused).toBe(true);+ expect(g.who).toBe("game");+ // With no job, two readings, as before.+ const idle = new GpuWatch(opts);+ idle.update({ busy: true, who: "game" }, 60, 0);+ idle.update({ busy: true, who: "game" }, 60, 5000);+ expect(idle.paused).toBe(true);+ });++ it("a brief pause (the busy readings ended within 30 s) cools down 2 minutes, at most once an hour; one that stays, the whole 10", () => {+ const opts = { autoResume: true, resumeAfterMs: 10 * MIN, resumeBelowC: 75, briefMs: 30_000, briefResumeMs: 2 * MIN, briefEveryMs: 60 * MIN };+ const g = new GpuWatch(opts);+ g.update({ busy: true, who: "x" }, 60, 0);+ g.update({ busy: false }, 50, 5000);+ g.update({ busy: false }, 50, 5000 + 2 * MIN - 1);+ expect(g.paused).toBe(true);+ g.update({ busy: false }, 50, 5000 + 2 * MIN);+ expect(g.paused).toBe(false);+ // A second brief one within the hour: the whole cool-down.+ g.update({ busy: true, who: "x" }, 60, 10 * MIN);+ g.update({ busy: false }, 50, 10 * MIN + 5000);+ g.update({ busy: false }, 50, 10 * MIN + 5000 + 2 * MIN);+ expect(g.paused).toBe(true);+ g.update({ busy: false }, 50, 20 * MIN + 5000);+ expect(g.paused).toBe(false);+ // A program that stays past 30 s: the whole cool-down.+ const stays = new GpuWatch(opts);+ stays.update({ busy: true, who: "x" }, 60, 0);+ stays.update({ busy: true, who: "x" }, 60, 40_000);+ stays.update({ busy: false }, 50, 45_000);+ stays.update({ busy: false }, 50, 45_000 + 2 * MIN);+ expect(stays.paused).toBe(true);+ stays.update({ busy: false }, 50, 45_000 + 10 * MIN);+ expect(stays.paused).toBe(false);+ });+it("pauses at once; with the automatic resume off, never resumes by itself", () => {const g = new GpuWatch({ autoResume: false, resumeAfterMs: 10 * MIN, resumeBelowC: 75 });g.update({ busy: true, who: "blender.exe" }, 60, 0);diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsindex 6c3d42cf..abbda14b 100644--- a/tests/worker-turns-run.test.ts+++ b/tests/worker-turns-run.test.ts@@ -11,6 +11,8 @@* - 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.+ * - Its own job: memory the counters can't place (they fail under load) is no other program; a game that stays pauses it+ * after the grace time, one that leaves within it keeps the job.*/import fs from "node:fs";import path from "node:path";@@ -151,20 +153,21 @@ const GAME_PID = 5555;/*** The PC's GPU as the fakes show it: local ComfyUI work on 8188 holding `workMb`, a game holding `gameMb`, the desktop- * 500 MB (the baseline says 600), and the worker's own ComfyUI 1000 MB once it runs. `counters: false`: they can't be read.+ * 500 MB (the baseline says 600), and the worker's own ComfyUI `ownMb` (1000 MB) once it runs; its own /system_stats+ * gives no torch number. `counters: false` (or a function that says false): they can't be read.*/-function fakeGpu(p: Pc, o: { workMb?: number; gameMb?: number; counters?: boolean }) {+function fakeGpu(p: Pc, o: { workMb?: number; gameMb?: number; ownMb?: () => number; counters?: boolean | (() => boolean) }) {const own = () => comfyOf(p);const procs = () => [{ pid: WORK_PID, mb: o.workMb ?? 0 },{ pid: GAME_PID, mb: o.gameMb ?? 0 },{ pid: 77, mb: 500 },- ...(own() ? [{ pid: own()!.pid, mb: 1000 }] : []),+ ...(own() ? [{ pid: own()!.pid, mb: o.ownMb?.() ?? 1000 }] : []),];return {readGpu: async () => ({ usedMb: procs().reduce((n, c) => n + c.mb, 0), tempC: 50, apps: [] }),readCounters: async () => {- if (o.counters === false) return null;+ if ((typeof o.counters === "function" ? o.counters() : o.counters) === false) return null;const rows = procs();const text = [`"(PDH-CSV 4.0)",${rows.map((r) => `"\\\\PC\\GPU Process Memory(pid_${r.pid}_${LUID})\\Dedicated Usage"`).join(",")}`,@@ -208,7 +211,7 @@ function fakeLocal(o: { busy: boolean; onFree?: () => void }) {return { o, calls, fetch };}-function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: string[]; studio?: { older: boolean }; local?: ReturnType<typeof fakeLocal> } = {}) {+function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: string[]; studio?: { older: boolean }; local?: ReturnType<typeof fakeLocal>; stepMs?: number; gpuGraceMs?: number } = {}) {const ctrl = new AbortController();const cfg = {site: SITE,@@ -216,7 +219,7 @@ function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: scomfyDir: p.comfyDir,workDir: p.workDir,modelDirs: [],- comfyCommand: [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--steps", "4", "--step-ms", "40", "--worker-guard", "1"],+ comfyCommand: [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--steps", "4", "--step-ms", String(o.stepMs ?? 40), "--worker-guard", "1"],comfyGuard: true,ffmpeg: null,yieldFolder: p.turns,@@ -241,6 +244,7 @@ function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: scatalogVersion: "a".repeat(64),gpuEveryMs: 200,turnGraceMs: 1500,+ ...(o.gpuGraceMs !== undefined && { gpuGraceMs: o.gpuGraceMs }),// Local ComfyUI work is never a real port here: busy unless the test says otherwise.localFetch: (o.local ?? fakeLocal({ busy: true })).fetch,...gpu,@@ -419,3 +423,64 @@ describe("studio jobs first", () => {await until(() => site(p)?.siteWaiting === 0);});});++describe("its own job and the busy pause", () => {+ const inJob = (id: string) => ["sending", "queued", "running", "collecting"].includes(task(id)?.state ?? "");+ const ended = (id: string, p: Pc) => ["done", "failed"].includes(task(id).state) || p.logs.some((l) => /Another program/.test(l));++ it("its job loads 20 GB that torch doesn't report and the counters fail under the load: no pause, the job finishes", async () => {+ const w = addWorker();+ const p = pc();+ let id = "";+ let loaded = false;+ let failedReads = 0;+ const gpu = fakeGpu(p, {+ // The weights stay loaded after the job, as ComfyUI keeps them.+ ownMb: () => ((loaded ||= !!id && inJob(id)) ? 20_000 : 1000),+ counters: () => {+ const ok = !id || !inJob(id);+ if (!ok) failedReads++;+ return ok;+ },+ });+ id = addTask();+ start(w, p, gpu, { stepMs: 500 });+ await until(() => ended(id, p), 60_000);+ expect(p.logs.filter((l) => /Another program|Stopping its own ComfyUI/.test(l))).toEqual([]);+ expect(failedReads).toBeGreaterThanOrEqual(3);+ expect(task(id).state).toBe("done");+ await sleep(1000);+ expect(p.logs.some((l) => /Another program/.test(l))).toBe(false);+ });++ it("a game that comes mid-job and stays pauses it after the grace time, and its ComfyUI stops", async () => {+ const w = addWorker();+ const p = pc();+ const gpu: { gameMb: number } = { gameMb: 0 };+ const id = addTask();+ start(w, p, fakeGpu(p, gpu), { stepMs: 3000, gpuGraceMs: 1000 });+ await until(() => task(id).state === "running");+ const at = Date.now();+ gpu.gameMb = 6000;+ await until(() => p.logs.some((l) => /Another program is using the GPU \(game\): pausing/.test(l)), 30_000);+ expect(Date.now() - at).toBeGreaterThanOrEqual(1000);+ expect(task(id).state).not.toBe("done");+ await until(() => p.logs.some((l) => /Stopping its own ComfyUI \(paused\)/.test(l)));+ expect(workerRow(w).local_why).toBe("gpu-busy:game");+ });++ it("a game that leaves within the grace time keeps the job", async () => {+ const w = addWorker();+ const p = pc();+ const gpu: { gameMb: number } = { gameMb: 0 };+ const id = addTask();+ start(w, p, fakeGpu(p, gpu), { stepMs: 1500, gpuGraceMs: 4000 });+ await until(() => task(id).state === "running");+ gpu.gameMb = 6000;+ await sleep(700);+ gpu.gameMb = 0;+ await until(() => ended(id, p), 60_000);+ expect(p.logs.filter((l) => /Another program|Stopping its own ComfyUI/.test(l))).toEqual([]);+ expect(task(id).state).toBe("done");+ });+});diff --git a/tests/worker-turns.test.ts b/tests/worker-turns.test.tsindex 8edf5bd0..e649fb8c 100644--- a/tests/worker-turns.test.ts+++ b/tests/worker-turns.test.ts@@ -117,6 +117,22 @@ describe("the port table and the GPU counters", () => {expect(s.who).toBe("game");});+ it("never names a desktop process as the cause: the biggest other one, else another program", () => {+ const names = { ...LISTING, names: { ...LISTING.names, "77": "dwm", "78": "msedge", "5555": "game" } };+ const desktopOnly = splitMemory({ usedMb: 9000, counters: parseCounters(typeperf([[77, 1500], [78, 900]])), listing: names, own: { pid: null, port: null, running: false, mb: null }, ports: [8188, 8199], baselineMb: 600 });+ expect(desktopOnly).toMatchObject({ othersMb: 8400, who: "another program" });+ expect(splitMemory({ usedMb: 9000, counters: parseCounters(typeperf([[77, 3000], [5555, 2000]])), listing: names, own: { pid: null, port: null, running: false, mb: null }, ports: [8188, 8199], baselineMb: 600 }).who).toBe("game");+ const apps = [{ pid: 12092, name: "ShellHost.exe", usedMb: null }, { pid: 5, name: "blender.exe", usedMb: null }];+ expect(splitMemory({ usedMb: 9000, counters: null, listing: null, apps, own: { pid: null, port: null, running: false, mb: null }, baselineMb: 600, lock: null }).who).toBe("blender.exe");+ });++ it("its own ComfyUI's share is sure only when read per process (the counters), not from torch alone", () => {+ const own = { pid: 900, port: 31337, running: true, mb: 1400 };+ expect(splitMemory({ usedMb: 23_000, counters: parseCounters(typeperf([[900, 21_000]])), listing: LISTING, own, ports: [8188, 8199], baselineMb: 600 })).toMatchObject({ ownMb: 21_000, ownSure: true, othersMb: 1400 });+ expect(splitMemory({ usedMb: 23_000, counters: null, listing: null, apps: [], own, baselineMb: 600, lock: null })).toMatchObject({ source: "total", ownSure: false });+ expect(splitMemory({ usedMb: 23_000, counters: null, listing: null, apps: [], own: { ...own, running: false }, baselineMb: 600, lock: null }).ownSure).toBe(true);+ });+it("its own ComfyUI before the counters list it: torch's number, as before", () => {const s = splitMemory({ usedMb: 3000, counters: [], listing: LISTING, own: { pid: 900, port: 31337, running: true, mb: 1400 }, ports: [8188, 8199], baselineMb: 0 });expect(s.ownMb).toBe(2000);