Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Worker: RAM guard for a PC its owner also works on (opt-in)

Adarsh8a7968f57e78
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index 34e90139..a1544a7d 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -69,6 +69,12 @@ export const DEFAULTS = {
* such readings. The worker only reads it, with its GPU reading.
*/
sensorsFile: null,
+ /**
+ * The RAM guard (ram.mjs), for a PC its owner also works on: { othersGb, afterS?, everyS? }. Other programs above
+ * `othersGb` of the PC's memory: no job that streams from RAM, and after `afterS` (60) with no job in hand a pause that
+ * the automatic resume ends. None: off, as before.
+ */
+ ramGuard: null,
};
const file = (home, name) => path.join(home, name);
diff --git a/bin/lib/worker/ram.mjs b/bin/lib/worker/ram.mjs
new file mode 100644
index 00000000..efbecf1c
--- /dev/null
+++ b/bin/lib/worker/ram.mjs
@@ -0,0 +1,179 @@
+// The RAM guard (worker.json `ramGuard`, docs/gpu-workers.md "This PC's memory"): for a PC whose owner also works on
+// it. Off unless worker.json sets it. Other programs' RAM is the PC's used memory less what the worker's own processes
+// hold: the worker itself, its ComfyUI, its CPU slot's ComfyUI, its text slot's server and anything they started. Above
+// the guard's line:
+//
+// - its claims ask for no job that streams its weights from RAM (`noStream`): the studio offers it only jobs whose
+// weights fit whole on its card, and leaves the others for another worker;
+// - after `afterS` seconds above the line with no GPU job of its own, it pauses ("ram-busy:<program>"), as for a busy
+// GPU, and resumes by the same automatic resume (`autoResume`, `resumeAfterMin`). A job it runs is never stopped for
+// RAM alone: the studio's fallback after running out of memory covers a real shortage.
+//
+// One reading every `everyS` seconds (10): one PowerShell call on Windows (Win32_Process: each process's id, parent,
+// working set, private bytes and name), `ps` elsewhere. No admin rights: a process of another user may read 0, and
+// counts then only in the total.
+import { execFile } from "node:child_process";
+
+const MB = 2 ** 20;
+
+/** Every process as one line: id, parent id, working set, private bytes, name (tab-separated). No double quotes. */
+export const PROCS_SCRIPT = [
+ "$ErrorActionPreference = 'Stop'",
+ "Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,WorkingSetSize,PrivatePageCount,Name | ForEach-Object { ($_.ProcessId, $_.ParentProcessId, $_.WorkingSetSize, $_.PrivatePageCount, $_.Name) -join [char]9 }",
+].join("; ");
+
+/** `ps` elsewhere: id, parent id, resident KB, name. */
+export const PS_ARGS = ["-A", "-o", "pid=,ppid=,rss=,comm="];
+
+/** The guard's defaults: seconds above the line before it pauses, and seconds between two readings. */
+export const RAM_AFTER_S = 60;
+export const RAM_EVERY_S = 10;
+
+/** A reading that failed: the last good one stands in for this long, then the guard says nothing (never a pause). */
+export const RAM_REUSE_MS = 60_000;
+
+/** The largest other process is named only from this size (MB): smaller ones say "other programs". */
+export const NAME_FROM_MB = 256;
+
+/** Windows' own memory, never named as the program that uses the PC's memory. */
+const SYSTEM = new Set(["system", "secure system", "registry", "memory compression", "system idle process", "svchost", "msmpeng", "mssense", "csrss", "smss", "wininit", "services", "lsass", "dwm", "wudfhost", "fontdrvhost"]);
+
+const int = (v) => {
+ const n = Number(String(v ?? "").trim());
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null;
+};
+
+/**
+ * worker.json's `ramGuard` → { othersMb, afterMs, everyMs }, null when it is off (not set, null or false), or
+ * { problem } when it can't be used. `othersGb`: the line (GB, more than 0); `afterS` (10 to 3600, 60 by default);
+ * `everyS` (5 to 60, 10 by default).
+ */
+export function ramGuardOf(v) {
+ if (v === undefined || v === null || v === false) return null;
+ if (typeof v !== "object" || Array.isArray(v)) return { problem: "ramGuard in worker.json isn't { othersGb, afterS }" };
+ const gb = Number(v.othersGb);
+ if (!(gb > 0) || gb > 4096) return { problem: "ramGuard.othersGb in worker.json isn't a number of GB above 0" };
+ const after = v.afterS === undefined ? RAM_AFTER_S : Number(v.afterS);
+ if (!(after >= 10 && after <= 3600)) return { problem: "ramGuard.afterS in worker.json isn't 10 to 3600 seconds" };
+ const every = v.everyS === undefined ? RAM_EVERY_S : Number(v.everyS);
+ if (!(every >= 5 && every <= 60)) return { problem: "ramGuard.everyS in worker.json isn't 5 to 60 seconds" };
+ return { othersMb: Math.round(gb * 1024), afterMs: Math.round(after * 1000), everyMs: Math.round(every * 1000) };
+}
+
+/**
+ * The process list → [{ pid, ppid, mb, name }], or null when it holds none. Windows lines (PROCS_SCRIPT): `mb` is the
+ * larger of the working set and the private bytes. `ps` lines: the resident size.
+ */
+export function parseProcs(text) {
+ const out = [];
+ for (const line of String(text ?? "").split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ if (line.includes("\t")) {
+ const [pid, ppid, ws, priv, ...name] = line.split("\t");
+ const p = int(pid);
+ if (!p) continue;
+ out.push({ pid: p, ppid: int(ppid) ?? 0, mb: Math.max(int(ws) ?? 0, int(priv) ?? 0) / MB, name: name.join("\t").trim().slice(0, 64) || "?" });
+ continue;
+ }
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
+ if (m) out.push({ pid: Number(m[1]), ppid: Number(m[2]), mb: Number(m[3]) / 1024, name: m[4].split("/").pop().slice(0, 64) });
+ }
+ return out.length ? out : null;
+}
+
+const run = (cmd, args, timeout) =>
+ new Promise((resolve) => {
+ execFile(cmd, args, { timeout, windowsHide: true, maxBuffer: 8 * MB }, (err, stdout) => resolve(err ? null : String(stdout)));
+ });
+
+/** One reading of every process, or null when it can't be read. `powershell`: worker.json's, as for the port table. */
+export async function readProcs(powershell) {
+ if (process.platform === "win32" || Array.isArray(powershell)) {
+ const list = Array.isArray(powershell) ? powershell : powershell ? [powershell] : ["powershell"];
+ return parseProcs(await run(String(list[0]), [...list.slice(1).map(String), "-NoProfile", "-NonInteractive", "-Command", PROCS_SCRIPT], 15_000));
+ }
+ return parseProcs(await run("ps", PS_ARGS, 10_000));
+}
+
+/** The processes in the trees under `roots` (the roots too, when they are listed): the worker's own. */
+export function ownPids(procs, roots) {
+ const kids = new Map();
+ for (const p of procs) {
+ if (p.ppid === p.pid) continue;
+ if (!kids.has(p.ppid)) kids.set(p.ppid, []);
+ kids.get(p.ppid).push(p.pid);
+ }
+ const mine = new Set();
+ const todo = roots.filter((r) => Number.isInteger(r) && r > 0);
+ while (todo.length) {
+ const pid = todo.pop();
+ if (mine.has(pid)) continue;
+ mine.add(pid);
+ for (const k of kids.get(pid) ?? []) todo.push(k);
+ }
+ return mine;
+}
+
+/**
+ * Other programs' RAM: { othersMb, ownMb, who }. `usedMb`: the PC's used memory (stats.mjs ramNow); `roots`: the worker's
+ * own process ids (itself, its ComfyUIs, its text slot's server). `who`: the largest other process from NAME_FROM_MB,
+ * not one of Windows' own, else null.
+ */
+export function ramSplit(usedMb, procs, roots) {
+ const mine = ownPids(procs, roots);
+ let ownMb = 0;
+ let top = null;
+ for (const p of procs) {
+ if (mine.has(p.pid)) ownMb += p.mb;
+ else if (p.mb >= NAME_FROM_MB && !SYSTEM.has(p.name.toLowerCase().replace(/\.exe$/, "")) && (!top || p.mb > top.mb)) top = p;
+ }
+ return { othersMb: Math.max(0, Math.round(usedMb - ownMb)), ownMb: Math.round(ownMb), who: top?.name ?? null };
+}
+
+/**
+ * The guard's pause and resume. `update` takes each reading: `over` says the last reading was above the line (its
+ * claims ask for no streamed job), and `paused` whether the guard keeps the worker paused. It pauses once readings stayed
+ * above the line for `afterMs` with no GPU job of its own (`job`: the time above the line counts from its job's end).
+ * With `autoResume`, it resumes once readings stayed under the line for `resumeAfterMs`; without it, only `clear()` (a
+ * resume by hand) ends it. A reading of null (none for RAM_REUSE_MS) counts as under the line: a guard that can't read
+ * the memory never keeps the worker from people's jobs.
+ */
+export class RamWatch {
+ constructor(o) {
+ this.o = o;
+ this.over = false;
+ this.paused = false;
+ this.who = null;
+ this.othersMb = null;
+ this.overSince = null;
+ this.freeSince = null;
+ }
+
+ update(reading, job, now) {
+ if (reading) this.othersMb = reading.othersMb;
+ if (reading && reading.othersMb > this.o.othersMb) {
+ this.over = true;
+ this.freeSince = null;
+ this.overSince = job ? null : (this.overSince ?? now);
+ if (this.paused || (this.overSince !== null && now - this.overSince >= this.o.afterMs)) {
+ this.paused = true;
+ this.who = reading.who ?? this.who;
+ }
+ return;
+ }
+ this.over = false;
+ this.overSince = null;
+ this.freeSince ??= now;
+ if (this.paused && this.o.autoResume && now - this.freeSince >= this.o.resumeAfterMs) {
+ this.paused = false;
+ this.who = null;
+ }
+ }
+
+ /** A resume by hand clears it too. */
+ clear() {
+ this.paused = false;
+ this.who = null;
+ this.overSince = null;
+ }
+}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 892727c4..546e4a76 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -45,6 +45,7 @@ import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";
import { CpuMeter, ramNow, readSensors, STATS_SEND_MS, statsOf } from "./stats.mjs";
+import { RAM_REUSE_MS, ramGuardOf, ramSplit, RamWatch, readProcs } from "./ram.mjs";
import { readLocalWork, SiteTurns, writeMode, writeSite } from "./turns.mjs";
import { CodeWatch, headOf, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";
@@ -178,13 +179,16 @@ export function siteProblem(site, o = {}) {
/**
* The worker's local pause, from its switch (`worker pause`), the GPU, its model folders (`modelsMissing`: the ones that
- * aren't there) and its ComfyUI: { paused, why, until }. A pause by hand ("here", "here-until:<ms>", "here-now") always
- * wins over the GPU's.
+ * aren't there), its ComfyUI and its RAM guard (`ram`, ram.mjs RamWatch, or null): { paused, why, until }. A pause by
+ * hand ("here", "here-until:<ms>", "here-now") always wins over the GPU's, and the GPU's over the RAM guard's.
+ *
+ * @param {{ paused: boolean; who: string | null } | null} [ram]
*/
-export function localPause(control, gpu, comfyTrouble, now, modelsMissing = []) {
+export function localPause(control, gpu, comfyTrouble, now, modelsMissing = [], ram = null) {
if (control.paused && control.until && now >= control.until) return null; // its --for ran out: the caller clears it
if (control.paused) return { paused: true, why: control.now ? "here-now" : control.until ? `here-until:${control.until}` : "here", until: control.until ?? null };
if (gpu.paused) return { paused: true, why: `gpu-busy:${gpu.who ?? "another program"}`, until: null };
+ if (ram?.paused) return { paused: true, why: `ram-busy:${ram.who ?? "other programs"}`, until: null };
if (modelsMissing.length) return { paused: true, why: "models-not-ready", until: null };
if (comfyTrouble) return { paused: true, why: comfyTrouble, until: null };
return { paused: false, why: null, until: null };
@@ -209,7 +213,7 @@ 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, gpuGraceMs (MID_JOB_GRACE_MS), gpuBriefMs (BRIEF_PAUSE_MS), readGpuGen, idleClaimMs
+ * readListeners, readProcs and ramGuard (the RAM guard, ram.mjs), 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, codeWatch (update.mjs's CodeWatch: new
* code on disk ends it with "update" once no person's job waits for it and its jobs are done) and updateDeferMs
@@ -309,6 +313,22 @@ async function work(saved, deps, owner) {
briefResumeMs: BRIEF_COOL_DOWN_MS,
briefEveryMs: BRIEF_EVERY_MS,
});
+ // The RAM guard (ram.mjs, worker.json `ramGuard`; off unless set): other programs' share of the PC's memory, read every
+ // few seconds. Above its line, claims ask for no job that streams from RAM; after a while above it with no GPU job in
+ // hand, a pause, ended by the same automatic resume as a busy GPU's.
+ // (Tests give their own: { othersMb, afterMs, everyMs }.)
+ const ramCfg = deps.ramGuard !== undefined ? deps.ramGuard : ramGuardOf(cfg.ramGuard);
+ if (ramCfg?.problem) log(`${ramCfg.problem}: its RAM guard is off.`);
+ const ramGuard = ramCfg && !ramCfg.problem ? ramCfg : null;
+ const ramWatch = ramGuard ? new RamWatch({ othersMb: ramGuard.othersMb, afterMs: ramGuard.afterMs, autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000 }) : null;
+ if (ramGuard) log(`Its RAM guard is on: with other programs above ${Math.round((ramGuard.othersMb / 1024) * 10) / 10} GB of this PC's memory, it takes only jobs that fit whole on its card, and pauses after ${Math.round(ramGuard.afterMs / 1000)} s with no job in hand.`);
+ let ramReadAt = -Infinity;
+ // A reading under way, and the last one that came back and isn't used yet ({ split }: null when it failed).
+ let ramReading = null;
+ let ramRead = null;
+ let ramGood = null;
+ let ramGoodAt = -Infinity;
+ let ramFailSaid = false;
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);
@@ -992,8 +1012,9 @@ async function work(saved, deps, owner) {
const take = (o) => {
busyJob = true;
jobUsesGpu = !o?.onlyHeld;
+ // Other programs use the PC's memory (its RAM guard): a claim asks for no job that streams from RAM.
job = runner
- .claimAndRun(o)
+ .claimAndRun(!o?.onlyHeld && ramWatch?.over ? { ...o, noStream: true } : o)
.then((had) => {
if (!o?.onlyHeld) gpuMissedAt = had ? -Infinity : now();
})
@@ -1068,10 +1089,12 @@ async function work(saved, deps, owner) {
writeControl(deps.home, { paused: false });
control = { paused: false };
gpu.clear();
+ ramWatch?.clear();
log("The pause ran out: back to work.");
}
if (control.resumedAt && control.resumedAt > (gpu.clearedAt ?? 0)) {
gpu.clear();
+ ramWatch?.clear();
gpu.clearedAt = control.resumedAt;
}
// The GPU, every 5 s: nvidia-smi's total, and with a turns folder the GPU counters and the port table too.
@@ -1114,6 +1137,43 @@ async function work(saved, deps, owner) {
if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
}
}
+ // The RAM guard, every everyS: the PC's used memory less its own processes' (itself, its ComfyUIs, its text slot's
+ // server and what they started). A failed reading keeps the last good one for RAM_REUSE_MS, then counts as free. The
+ // reading runs beside the loop (a PowerShell start takes about a second, longer when memory is short): the loop
+ // uses each one once it is there.
+ if (ramWatch && !ramReading && t - ramReadAt >= ramGuard.everyMs) {
+ ramReadAt = t;
+ const roots = [process.pid, comfy.pid, cpuComfy?.pid ?? null, text?.server?.pid ?? null];
+ ramReading = (deps.readProcs ?? readProcs)(cfg.powershell)
+ .catch(() => null)
+ .then((procs) => {
+ const usedMb = (deps.ramNow ?? ramNow)().usedMb;
+ ramRead = { split: procs && usedMb !== null ? ramSplit(usedMb, procs, roots) : null };
+ })
+ .finally(() => (ramReading = null));
+ }
+ if (ramWatch && ramRead) {
+ const { split: got } = ramRead;
+ ramRead = null;
+ if (got) {
+ ramGood = got;
+ ramGoodAt = t;
+ ramFailSaid = false;
+ } else if (!ramFailSaid) {
+ log("Couldn't read the memory of this PC's programs: its RAM guard tries again at the next reading.");
+ ramFailSaid = true;
+ }
+ // The owner's switch for the automatic resume (the beat's) counts here as for a busy GPU.
+ ramWatch.o.autoResume = gpu.o.autoResume;
+ const wasOver = ramWatch.over;
+ const wasPaused = ramWatch.paused;
+ ramWatch.update(t - ramGoodAt <= RAM_REUSE_MS ? ramGood : null, busyJob && jobUsesGpu, t);
+ const gb = (mb) => `${Math.round((mb ?? 0) / 102.4) / 10} GB`;
+ if (!wasOver && ramWatch.over && !ramWatch.paused) log(`Other programs use ${gb(ramWatch.othersMb)} of this PC's memory (its RAM guard's line is ${gb(ramGuard.othersMb)}): it takes only jobs that fit whole on its card.`);
+ if (!wasPaused && ramWatch.paused) log(`This PC's memory is in use (${ramWatch.who ?? "other programs"}, ${gb(ramWatch.othersMb)} not its own): pausing until it stays under the line for the cool-down.`);
+ if (wasPaused && !ramWatch.paused) log("This PC's memory stayed free for the whole cool-down: resuming.");
+ else if (wasOver && !ramWatch.over && !ramWatch.paused) log("Other programs' memory is under its RAM guard's line again: it takes any job it can run.");
+ }
if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t) && t - guardMissingAt >= HOUR) comfyTrouble = null;
// A ComfyUI that stopped answering (hung) is stopped; the next turn starts it again. Every beat looks at it (its
// /system_stats), so one that answers anything at all is never taken for hung.
@@ -1136,7 +1196,7 @@ async function work(saved, deps, owner) {
});
} else modelsMissing = missing;
}
- let next = localPause(control, gpu, comfyTrouble, t, modelsMissing) ?? { paused: false, why: null, until: null };
+ let next = localPause(control, gpu, comfyTrouble, t, modelsMissing, ramWatch) ?? { paused: false, why: null, until: null };
// Waiting for its turn is not a pause: its jobs keep their place in the line. The helper's estimate of the start
// goes with it.
if (!next.paused && turn.waitForYield) next = { paused: false, why: turn.late ? "waiting-for-yield:no-answer" : "waiting-for-yield", until: turn.startsAt };
@@ -1284,9 +1344,10 @@ async function work(saved, deps, owner) {
}
}
// The text slot: never while paused by hand, on the website or outside its hours. While the worker waits for its
- // GPU's job to end before it restarts on new code, the text slot goes on: text jobs take seconds.
+ // GPU's job to end before it restarts on new code, the text slot goes on: text jobs take seconds. Its RAM guard's
+ // pause stops it too: its server's memory goes back to the PC's other programs.
if (text) {
- const byHand = pause.paused && /^here/.test(pause.why ?? "");
+ const byHand = pause.paused && /^(here|ram-busy)/.test(pause.why ?? "");
const turn = textTurn({ updating, gpuBusy: busyJob || busyCpu, byHand, worker: answer?.worker ?? null });
text.tick(t, { ...turn, room: textRoom() });
}
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index eedda1d2..d7258833 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -301,6 +301,26 @@ The worker obeys any one of these pauses. One pause never ends another pause.
cool-down. A pause by hand is never ended by the automatic resume. Turn it on with `autoResume` in `worker.json`, or
with **Resume by itself after another program used the GPU** in Settings → Workers. The website's switch wins over
`worker.json`. With it on, a PC can serve whenever its owner isn't using the GPU.
+- **This PC's memory is in use** (the RAM guard, off by default). For a PC whose owner also works on it with programs
+ that need memory more than the GPU (an editor, a game, Python, another AI app). Turn it on in `worker.json` with
+ `"ramGuard": { "othersGb": 12 }` (also `afterS`, 60 by default, and `everyS`, 10). Other programs' RAM is the PC's
+ used memory minus what the worker's own processes hold: the worker, its ComfyUI, its CPU slot's ComfyUI, its text
+ slot's server, and the programs they started. Each process counts the larger of its working set and its private
+ bytes. The worker reads them every `everyS` seconds: on Windows with one PowerShell call (`Win32_Process`, about a
+ second, beside its loop), elsewhere with `ps`. No admin rights are needed.
+ - Above `othersGb`, its claims ask for no job that streams its weights from RAM (`noStream` in the claim). The studio
+ then offers it only jobs whose weights fit whole on its card, and the others go to another worker. A streamed job
+ keeps its weights in the PC's RAM for its whole run, and on a 32 GB PC the measured ones fill it. A job whose weights
+ fit on the card uses the RAM only while it loads.
+ - Above `othersGb` for `afterS` seconds with no GPU job in hand, it pauses: the state says "This PC's memory is in use
+ (editor.exe)" (`ram-busy:<program>`, the largest other program). Its ComfyUI and its text slot's server stop, so
+ their memory goes back to the PC. The automatic resume ends it, as for a busy GPU: `resumeAfterMin` minutes in a row
+ under the line. A resume by hand ends it too.
+ - A job in hand is never stopped for RAM alone. The time above the line counts from its end. If the PC really runs out
+ of memory, the studio's fallback for a streamed job that runs out of memory moves it to another worker
+ ([Streaming from RAM](#streaming-from-ram)).
+ - A reading that fails keeps the last good one for a minute. After that, the guard counts the memory as free: a guard
+ that can't read never keeps the worker from people's jobs.
- **Hours:** outside its hours, the worker takes nothing new. Near the end of a window, it takes only a job that its
estimate says will finish in time.
@@ -740,6 +760,9 @@ Every other workflow streams by the computed rule.
no other worker for it, or for a job taken with every weight on the card, or for any other error, the job fails as
before. The worker still takes the workflow with every weight on its card. Settings → Workers shows the list on the
worker's card, and the owner clears one entry or all of them (`PATCH /api/admin/workers/{id}` with `clearNoStream`).
+- **A PC whose memory is in use.** A worker's claim with `noStream` (its RAM guard, [Pauses](#pauses)) counts no RAM
+ for that claim: it takes only a job whose weights, or a model variant's, fit whole on its card. Its facts stay as they
+ are, and the claim's words add "its PC's memory is in use: only jobs that fit whole on its card".
- **Times.** A worker that streams runs slower. Its run limits come from its own measured runs in the lane (above), so
they stay right for it.
@@ -1150,8 +1173,9 @@ its target), at most once an hour each.
than job tickets, which sends no account's run to workers).
`stallMs` is how long the job may go with no progress before the worker gives it back (see "The stall limit"). A
worker ignores a `stallMs` under one minute, and uses its own 10 minutes then.
- A worker's CPU slot sends `slot: "cpu"` and gets only work for that slot, with `slot: "cpu"` on the task. A
- finishing job carries `finish` (a finish ticket) in place of `graph` or `ticket`. `reportPreview: true` asks for live
+ A worker's CPU slot sends `slot: "cpu"` and gets only work for that slot, with `slot: "cpu"` on the task. Its GPU's
+ slot sends `noStream: true` while its RAM guard says the PC's memory is in use: it then gets only a job whose weights
+ fit whole on its card. A finishing job carries `finish` (a finish ticket) in place of `graph` or `ticket`. `reportPreview: true` asks for live
previews (see "Live previews").
- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finished
job also count: the last 20 jobs in each lane give the median and the 90th percentile.
@@ -1239,7 +1263,10 @@ routes.
`tests/worker-turns.test.ts`, `tests/worker-turns-run.test.ts`, `tests/worker-update.test.ts`, `tests/cpu-slot.test.ts`,
`tests/worker-cpu-slot.test.ts`, `tests/fuobe-connect-nodes.test.ts`, `tests/model-variants.test.ts`,
`tests/pool-model-variants.test.ts`, `tests/stream-needs.test.ts`, `tests/stream-oom-fallback.test.ts`,
- `tests/pool-first-pick.test.ts`, `tests/worker-build-loads.test.ts`). The model variant
+ `tests/pool-first-pick.test.ts`, `tests/worker-build-loads.test.ts`, `tests/worker-ram-guard.test.ts`). The RAM guard
+ tests read stand-in process lists (Windows' and `ps`), find the worker's own process trees, and run the worker with a
+ stand-in PC memory: a claim with `noStream`, the pause the studio names, the automatic resume, a job in hand that
+ goes on to its end, and no reading at all with the guard off. The model variant
tests check the build's refusals, which files a worker gets by its card and its files, the swapped graph and ticket,
and an older worker program. The streaming tests check the build's refusals, the memory rule (VRAM only, VRAM and
RAM, unknown RAM, dynamic VRAM off, the 3% allowance, the computed rule and its reserve, the workflows that never
diff --git a/tests/worker-ram-guard.test.ts b/tests/worker-ram-guard.test.ts
new file mode 100644
index 00000000..8ae5f674
--- /dev/null
+++ b/tests/worker-ram-guard.test.ts
@@ -0,0 +1,377 @@
+/**
+ * The worker's RAM guard (bin/lib/worker/ram.mjs, worker.json `ramGuard`), for a PC its owner also works on. Its parts
+ * on their own (the setting, the process list, the worker's own processes, the pause and resume), then the worker end to
+ * end against the studio's real routes and its own stand-in ComfyUI (tests/helpers/fake-local-comfy.ts): the process
+ * list and the PC's memory are stand-ins, never a real PowerShell or ps.
+ *
+ * - Above the line: its claims ask for no streamed job; with no job in hand for `afterS`, it pauses ("ram-busy"), and the
+ * studio says "This PC's memory is in use"; under the line for the cool-down, it resumes by itself.
+ * - A job in hand goes on to its end: the pause comes after it.
+ * - Off (no `ramGuard`): it never reads the process list, and its claims are as before.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { ownPids, parseProcs, RamWatch, ramGuardOf, ramSplit, PROCS_SCRIPT } from "../bin/lib/worker/ram.mjs";
+import { localPause, runWorker } from "../bin/lib/worker/run.mjs";
+import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";
+import { FAKE_PNG } from "./helpers/fake-local-comfy";
+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = tempDir("fuobe-worker-ram-guard-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const GB = 1024;
+
+describe("the setting (ramGuardOf)", () => {
+ it("off unless set; the defaults; what it refuses", () => {
+ expect(ramGuardOf(undefined)).toBeNull();
+ expect(ramGuardOf(null)).toBeNull();
+ expect(ramGuardOf(false)).toBeNull();
+ expect(ramGuardOf({ othersGb: 12 })).toEqual({ othersMb: 12 * GB, afterMs: 60_000, everyMs: 10_000 });
+ expect(ramGuardOf({ othersGb: 10.5, afterS: 30, everyS: 5 })).toEqual({ othersMb: 10752, afterMs: 30_000, everyMs: 5000 });
+ for (const bad of [{}, { othersGb: 0 }, { othersGb: "x" }, { othersGb: 12, afterS: 5 }, { othersGb: 12, everyS: 120 }, [12], 12, true]) {
+ expect(ramGuardOf(bad)).toHaveProperty("problem");
+ }
+ });
+});
+
+describe("the process list", () => {
+ it("reads Windows' lines (the larger of working set and private bytes) and ps lines", () => {
+ const win = ["4\t0\t4931584\t200704\tSystem", "100\t4\t1073741824\t2147483648\tgame.exe", "200\t100\t0\t0\tC:\\odd name.exe", "x\ty\tz\tw\tbad"].join("\r\n");
+ expect(parseProcs(win)).toEqual([
+ { pid: 4, ppid: 0, mb: 4931584 / 2 ** 20, name: "System" },
+ { pid: 100, ppid: 4, mb: 2048, name: "game.exe" },
+ { pid: 200, ppid: 100, mb: 0, name: "C:\\odd name.exe" },
+ ]);
+ expect(parseProcs(" 1 0 2048 /sbin/init\n 77 1 1048576 python3\n")).toEqual([
+ { pid: 1, ppid: 0, mb: 2, name: "init" },
+ { pid: 77, ppid: 1, mb: 1024, name: "python3" },
+ ]);
+ expect(parseProcs("")).toBeNull();
+ expect(parseProcs("nothing here")).toBeNull();
+ // The script passes through a Windows command line: no double quotes in it.
+ expect(PROCS_SCRIPT).not.toContain('"');
+ });
+
+ it("the worker's own: the trees under its roots, safe from loops and from roots that aren't listed", () => {
+ const procs = [
+ { pid: 10, ppid: 1, mb: 100, name: "node" },
+ { pid: 11, ppid: 10, mb: 5000, name: "python" },
+ { pid: 12, ppid: 11, mb: 50, name: "conhost" },
+ { pid: 20, ppid: 1, mb: 900, name: "llama-server" },
+ { pid: 30, ppid: 31, mb: 1, name: "a" },
+ { pid: 31, ppid: 30, mb: 1, name: "b" },
+ { pid: 40, ppid: 40, mb: 1, name: "self" },
+ ];
+ expect([...ownPids(procs, [10, 20, null as never, 99])].sort((a, b) => a - b)).toEqual([10, 11, 12, 20, 99]);
+ expect([...ownPids(procs, [30])].sort()).toEqual([30, 31]);
+ expect([...ownPids(procs, [40])]).toEqual([40]);
+ });
+
+ it("others = used less its own; the largest other program is named, never Windows' own or a small one", () => {
+ const procs = [
+ { pid: 10, ppid: 1, mb: 1000, name: "node.exe" },
+ { pid: 11, ppid: 10, mb: 9000, name: "python.exe" },
+ { pid: 50, ppid: 1, mb: 6000, name: "Memory Compression" },
+ { pid: 60, ppid: 1, mb: 4000, name: "game.exe" },
+ { pid: 61, ppid: 1, mb: 3000, name: "editor.exe" },
+ ];
+ expect(ramSplit(25_000, procs, [10])).toEqual({ othersMb: 15_000, ownMb: 10_000, who: "game.exe" });
+ expect(ramSplit(9_000, procs, [10])).toMatchObject({ othersMb: 0 });
+ expect(ramSplit(12_000, [{ pid: 60, ppid: 1, mb: 100, name: "small.exe" }], [10]).who).toBeNull();
+ });
+});
+
+describe("the pause and resume (RamWatch)", () => {
+ const o = { othersMb: 10 * GB, afterMs: 60_000, autoResume: true, resumeAfterMs: 600_000 };
+ const high = { othersMb: 14 * GB, who: "game.exe" };
+ const low = { othersMb: 6 * GB, who: null };
+
+ it("above the line its claims stream nothing at once; it pauses only after afterMs with no job in hand", () => {
+ const r = new RamWatch(o);
+ r.update(high, false, 0);
+ expect(r.over).toBe(true);
+ expect(r.paused).toBe(false);
+ r.update(high, false, 59_999);
+ expect(r.paused).toBe(false);
+ r.update(high, false, 60_000);
+ expect(r).toMatchObject({ paused: true, who: "game.exe" });
+ expect(localPause({ paused: false }, { paused: false }, null, 0, [], r)).toEqual({ paused: true, why: "ram-busy:game.exe", until: null });
+ });
+
+ it("its own job: the time above the line counts from the job's end, and the job is never stopped for it", () => {
+ const r = new RamWatch(o);
+ r.update(high, true, 0);
+ r.update(high, true, 300_000);
+ expect(r).toMatchObject({ over: true, paused: false });
+ r.update(high, false, 310_000);
+ expect(r.paused).toBe(false);
+ r.update(high, false, 370_000);
+ expect(r.paused).toBe(true);
+ });
+
+ it("resumes by itself only with the automatic resume, after the whole cool-down under the line; a spike starts it again", () => {
+ const r = new RamWatch(o);
+ r.update(high, false, 0);
+ r.update(high, false, 60_000);
+ r.update(low, false, 100_000);
+ expect(r).toMatchObject({ over: false, paused: true });
+ r.update(high, false, 500_000);
+ r.update(low, false, 510_000);
+ r.update(low, false, 1_109_999);
+ expect(r.paused).toBe(true);
+ r.update(low, false, 1_110_000);
+ expect(r.paused).toBe(false);
+
+ const off = new RamWatch({ ...o, autoResume: false });
+ off.update(high, false, 0);
+ off.update(high, false, 60_000);
+ off.update(low, false, 10_000_000);
+ expect(off.paused).toBe(true);
+ // A resume by hand.
+ off.clear();
+ expect(off.paused).toBe(false);
+ });
+
+ it("no reading counts as under the line: a guard that can't read never keeps it from people's jobs", () => {
+ const r = new RamWatch(o);
+ r.update(high, false, 0);
+ r.update(null, false, 1000);
+ expect(r.over).toBe(false);
+ r.update(high, false, 2000);
+ r.update(high, false, 61_999);
+ expect(r.paused).toBe(false);
+ });
+
+ it("a pause by hand and a busy GPU win over it", () => {
+ const r = new RamWatch(o);
+ r.update(high, false, 0);
+ r.update(high, false, 60_000);
+ expect(localPause({ paused: true }, { paused: false }, null, 0, [], r)?.why).toBe("here");
+ expect(localPause({ paused: false }, { paused: true, who: "game.exe" }, null, 0, [], r)?.why).toBe("gpu-busy:game.exe");
+ expect(localPause({ paused: false }, { paused: false }, null, 0, [], null)).toEqual({ paused: false, why: null, until: null });
+ });
+});
+
+// ---------------------------------------------------------------------------------------------------------------------
+// End to end
+
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { ComputerRunner } = await import("@/lib/computer-runner");
+
+const ROOT = path.resolve(__dirname, "..");
+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
+const SITE = "http://127.0.0.1:9";
+const RULES = inputRules(readCatalog(ROOT));
+const ALLOWED = new Set(["LoadImage", "KSampler", "SaveImage"]);
+const realFetch = globalThis.fetch;
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+let routes: ComputerRoutes;
+beforeAll(async () => {
+ routes = await loadRoutes();
+ setSetting("comfyWhere", "workers");
+});
+beforeEach(() => {
+ resetRates();
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];
+afterEach(async () => {
+ for (const r of running.splice(0)) {
+ r.ctrl.abort();
+ await r.done.catch(() => {});
+ }
+});
+
+type W = { id: string; token: string };
+const task = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+const workerRow = (w: W) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;
+
+function addWorker(): W {
+ const w = pool.addWorker(`ram-${Math.random().toString(36).slice(2, 8)}`);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } });
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: ["small"], workflows: ["wf-test"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ return w;
+}
+
+const ticketGraphs = new Map<string, Record<string, unknown>>();
+const composer = {
+ workerFactsFrom: () => ({}),
+ composeTicket: async (job: { generationId: string }) => ({ ok: true, graph: ticketGraphs.get(job.generationId), workflowId: "wf-test", size: { megapixels: 0, seconds: 0, outputs: 1 }, made: [] }),
+};
+
+let gens = 0;
+function addTask(): string {
+ const gid = `ram-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")
+ .run(gid, now, now);
+ const input = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");
+ const graph = { "1": { class_type: "LoadImage", inputs: { image: input } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } };
+ ticketGraphs.set(gid, graph);
+ return tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph,
+ ticket: { catalogVersion: catalogVersion(), inputs: [{ slot: "images.0", name: input }] } as never,
+ pool: { pools: ["pool"], account: "ram-account", rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
+ }).id;
+}
+
+/** The PC's memory as the stand-ins show it: the worker's own (itself and a child), the desktop, and a game of `gameMb`. */
+function fakeRam(o: { gameMb: number }) {
+ const reads = { n: 0 };
+ const procs = () => [
+ { pid: process.pid, ppid: 1, mb: 800, name: "node.exe" },
+ { pid: 987_654, ppid: process.pid, mb: 7000, name: "python.exe" },
+ { pid: 77, ppid: 1, mb: 4000, name: "explorer.exe" },
+ { pid: 5555, ppid: 1, mb: o.gameMb, name: "game.exe" },
+ ];
+ return {
+ reads,
+ o,
+ readProcs: async () => {
+ reads.n++;
+ return procs();
+ },
+ ramNow: () => ({ usedMb: procs().reduce((n, p) => n + p.mb, 0), totalMb: 32 * GB }),
+ };
+}
+
+interface Started {
+ logs: string[];
+ claims: Record<string, unknown>[];
+}
+
+function start(w: W, ram: ReturnType<typeof fakeRam> | null, o: { guard?: boolean; stepMs?: number; afterMs?: number } = {}): Started {
+ const base = tempDir("fuobe-worker-ram-pc-");
+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy") };
+ for (const d of Object.values(p)) fs.mkdirSync(d, { recursive: true });
+ const s: Started = { logs: [], claims: [] };
+ const api = apiAs(routes, null);
+ const ctrl = new AbortController();
+ const done = runWorker(
+ {
+ site: SITE,
+ token: w.token,
+ comfyDir: p.comfyDir,
+ workDir: p.workDir,
+ modelDirs: [],
+ 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,
+ autoResume: true,
+ // 1.2 s of cool-down.
+ resumeAfterMin: 0.02,
+ },
+ {
+ fetch: async (url: string, init: RequestInit = {}) => {
+ if (!String(url).startsWith(SITE)) return realFetch(url, init);
+ const u = new URL(url);
+ if (u.pathname === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: ["small"], workflows: ["wf-test"], missing: [] });
+ if (u.pathname === "/api/gpu/computer/claim" && typeof init.body === "string") s.claims.push(JSON.parse(init.body));
+ return api(u.pathname + u.search, init);
+ },
+ home: p.home,
+ signal: ctrl.signal,
+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },
+ ComputerRunner,
+ rules: RULES,
+ pins: {},
+ allowed: ALLOWED,
+ ffmpegVersion: async () => null,
+ awake: { set: () => {} },
+ sleep: (ms: number) => sleep(Math.min(ms, 50)),
+ log: (line: string) => void s.logs.push(line),
+ composer,
+ catalogVersion: "a".repeat(64),
+ gpuEveryMs: 200,
+ idleClaimMs: 200,
+ readGpu: async () => ({ usedMb: 300, tempC: 40, apps: [] }),
+ ...(ram && { readProcs: ram.readProcs, ramNow: ram.ramNow }),
+ ...(o.guard !== false && { ramGuard: { othersMb: 10 * GB, afterMs: o.afterMs ?? 800, everyMs: 100 } }),
+ },
+ );
+ running.push({ ctrl, done });
+ return s;
+}
+
+async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 50): Promise<Exclude<T, false | null | undefined | 0 | "">> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await fn();
+ if (v) return v as Exclude<T, false | null | undefined | 0 | "">;
+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);
+ await sleep(every);
+ }
+}
+
+describe("the RAM guard in the worker, end to end", () => {
+ it("above the line: claims stream nothing, then a pause the studio names; under it for the cool-down: back to work", async () => {
+ const w = addWorker();
+ const ram = fakeRam({ gameMb: 0 });
+ const s = start(w, ram, { afterMs: 1500 });
+ await until(() => s.claims.length > 0);
+ expect(s.claims[0]).not.toHaveProperty("noStream");
+ // A game starts. Others: the desktop and the game (15.9 GB), not its own 7.8 GB.
+ ram.o.gameMb = 12 * GB;
+ await until(() => s.claims.some((c) => c.noStream === true), 1500);
+ expect(s.logs.some((l) => /Other programs use 15\.9 GB of this PC's memory/.test(l))).toBe(true);
+ expect(workerRow(w).paused_local).toBe(0);
+ await until(() => workerRow(w).local_why === "ram-busy:game.exe");
+ expect(workerRow(w).paused_local).toBe(1);
+ expect(pool.workerState(workerRow(w))).toEqual({ state: "gpu-busy", words: "This PC's memory is in use (game.exe)" });
+ // The game ends: after the cool-down it resumes and claims as before.
+ ram.o.gameMb = 0;
+ await until(() => workerRow(w).paused_local === 0 && workerRow(w).local_why === null, 20_000);
+ expect(s.logs.some((l) => /stayed free for the whole cool-down: resuming/.test(l))).toBe(true);
+ const before = s.claims.length;
+ await until(() => s.claims.length > before);
+ expect(s.claims.at(-1)).not.toHaveProperty("noStream");
+ const id = addTask();
+ expect((await until(() => ["done", "failed"].includes(task(id).state) && task(id))).state).toBe("done");
+ });
+
+ it("a job in hand goes on to its end; the pause comes after it", async () => {
+ const w = addWorker();
+ const ram = fakeRam({ gameMb: 0 });
+ const s = start(w, ram, { stepMs: 600 });
+ const id = addTask();
+ await until(() => task(id).state === "running");
+ ram.o.gameMb = 12 * GB;
+ await sleep(1500);
+ // Over afterMs above the line, but its job runs: no pause, the job isn't sent back.
+ expect(workerRow(w).paused_local).toBe(0);
+ expect(task(id).worker_id).toBe(w.id);
+ expect((await until(() => ["done", "failed"].includes(task(id).state) && task(id))).state).toBe("done");
+ await until(() => workerRow(w).local_why === "ram-busy:game.exe");
+ expect(s.logs.some((l) => /This PC's memory is in use \(game\.exe, 15\.9 GB not its own\): pausing/.test(l))).toBe(true);
+ });
+
+ it("off (no ramGuard): it never reads the process list, and its claims are as before", async () => {
+ const w = addWorker();
+ const ram = fakeRam({ gameMb: 20 * GB });
+ const s = start(w, ram, { guard: false });
+ await until(() => s.claims.length >= 2);
+ await sleep(1000);
+ expect(ram.reads.n).toBe(0);
+ expect(s.claims.every((c) => !("noStream" in c))).toBe(true);
+ expect(workerRow(w).paused_local).toBe(0);
+ });
+});