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: the RAM guard follows the site's switch, frees its own ComfyUI, never pauses

Adarsh499b8614df20
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index a1544a7d..852f0ba7 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -70,9 +70,10 @@ export const DEFAULTS = {
*/
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.
+ * The RAM guard's numbers (ram.mjs), for a PC its owner also works on: { othersGb?, everyS? } (12 GB and 10 s by
+ * default). The guard runs only while the owner's switch for this worker is on (Settings → Workers); with other
+ * programs above `othersGb` of the PC's memory it prefers jobs that fit whole on its card, and its ComfyUI lets go of
+ * its memory before each GPU job and when idle.
*/
ramGuard: null,
};
diff --git a/bin/lib/worker/ram.mjs b/bin/lib/worker/ram.mjs
index efbecf1c..5cb051a1 100644
--- a/bin/lib/worker/ram.mjs
+++ b/bin/lib/worker/ram.mjs
@@ -1,17 +1,18 @@
-// 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:
+// The RAM guard (docs/gpu-workers.md "This PC's memory"): for a PC whose owner also works on it. The owner switches it on
+// for one worker in Settings → Workers (the beat's answer, `worker.ramGuard`; off by default). worker.json `ramGuard`
+// holds only its numbers: { othersGb (12), everyS (10) }. 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 `othersGb`:
//
-// - 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.
+// - its claims ask for no job that streams its weights from RAM (`noStream`). That is a preference: the studio still gives
+// it such a job when no other worker could take that job now, so nobody waits for it;
+// - its own ComfyUI lets go of its memory (its /free: models unloaded, caches emptied) before each GPU job and when it
+// goes idle. Nothing pauses or stops: it keeps taking work, its text slot goes on, and a job in hand is never stopped
+// for RAM (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.
+// One reading every `everyS` seconds: 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;
@@ -25,11 +26,11 @@ export const PROCS_SCRIPT = [
/** `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;
+/** The guard's defaults: other programs' GB of the PC's memory (its line), and seconds between two readings. */
+export const RAM_OTHERS_GB = 12;
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). */
+/** A reading that failed: the last good one stands in for this long, then the guard counts the memory as free. */
export const RAM_REUSE_MS = 60_000;
/** The largest other process is named only from this size (MB): smaller ones say "other programs". */
@@ -44,20 +45,26 @@ const int = (v) => {
};
/**
- * 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).
+ * worker.json's `ramGuard` → its numbers { othersMb, everyMs }. Not set (or null, false): the defaults. `othersGb`: the
+ * line (GB, more than 0; 12 by default); `everyS`: seconds between two readings (5 to 60; 10 by default). A value it
+ * can't use keeps its default and adds `problem`. Whether the guard runs is the site's switch, never this.
*/
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) };
+ const out = { othersMb: Math.round(RAM_OTHERS_GB * 1024), everyMs: RAM_EVERY_S * 1000 };
+ if (v === undefined || v === null || v === false) return out;
+ if (typeof v !== "object" || Array.isArray(v)) return { ...out, problem: "ramGuard in worker.json isn't { othersGb, everyS }" };
+ const problems = [];
+ if (v.othersGb !== undefined) {
+ const gb = Number(v.othersGb);
+ if (gb > 0 && gb <= 4096) out.othersMb = Math.round(gb * 1024);
+ else problems.push("ramGuard.othersGb in worker.json isn't a number of GB above 0");
+ }
+ if (v.everyS !== undefined) {
+ const every = Number(v.everyS);
+ if (every >= 5 && every <= 60) out.everyMs = Math.round(every * 1000);
+ else problems.push("ramGuard.everyS in worker.json isn't 5 to 60 seconds");
+ }
+ return problems.length ? { ...out, problem: problems.join("; ") } : out;
}
/**
@@ -131,49 +138,28 @@ export function ramSplit(usedMb, procs, roots) {
}
/**
- * 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.
+ * The guard's state from each reading (`update`): `over` says the last reading was above the line (its claims ask for no
+ * streamed job, and its ComfyUI lets go of its memory before each GPU job and when idle); `who`, the largest other
+ * program then. A reading of null (none for RAM_REUSE_MS) counts as under the line: a guard that can't read the memory
+ * never changes how the worker works.
*/
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) {
+ update(reading) {
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;
- }
+ this.over = !!reading && reading.othersMb > this.o.othersMb;
+ this.who = this.over ? (reading.who ?? null) : null;
}
- /** A resume by hand clears it too. */
+ /** The site's switch went off: as under the line. */
clear() {
- this.paused = false;
+ this.over = false;
this.who = null;
- this.overSince = null;
}
}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 546e4a76..6c5ea9ee 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -179,16 +179,13 @@ 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), 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]
+ * 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. Its RAM guard never pauses it (ram.mjs).
*/
-export function localPause(control, gpu, comfyTrouble, now, modelsMissing = [], ram = null) {
+export function localPause(control, gpu, comfyTrouble, now, modelsMissing = []) {
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 };
@@ -213,7 +210,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, readProcs and ramGuard (the RAM guard, ram.mjs), gpuEveryMs, gpuGraceMs (MID_JOB_GRACE_MS), gpuBriefMs (BRIEF_PAUSE_MS), readGpuGen, idleClaimMs
+ * readListeners, readProcs, ramNow and ramGuard (the RAM guard's numbers, 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
@@ -313,15 +310,19 @@ 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.`);
+ // The RAM guard (ram.mjs): other programs' share of the PC's memory, read every few seconds while the owner's switch
+ // for this worker is on (the beat's `worker.ramGuard`; off by default). worker.json `ramGuard` gives only its numbers.
+ // Above its line, claims prefer jobs that fit whole on its card, and its ComfyUI lets go of its memory before each GPU
+ // job and when idle. It never pauses. (Tests give their own numbers: { othersMb, everyMs }.)
+ const ramCfg = deps.ramGuard ?? ramGuardOf(cfg.ramGuard);
+ if (ramCfg.problem) log(`${ramCfg.problem}: its RAM guard uses its default for it.`);
+ const ramGuard = { othersMb: ramCfg.othersMb, everyMs: ramCfg.everyMs };
+ const ramWatch = new RamWatch({ othersMb: ramGuard.othersMb });
+ // The site's switch as the last beat said (null before the first answer), and whether its ComfyUI let go of its memory
+ // since its last GPU job.
+ let ramOn = null;
+ let ramIdleFreed = false;
+ const gbOf = (mb) => `${Math.round((mb ?? 0) / 102.4) / 10} GB`;
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;
@@ -909,6 +910,12 @@ async function work(saved, deps, owner) {
emptyCache();
lastTask = t.id;
}
+ // Its RAM guard, above the line: its own ComfyUI lets go of its memory before a GPU job starts there (not for a
+ // job already in it, kept results going up, or a finishing job, which runs on no ComfyUI).
+ if (!o.onlyHeld && ramOn && ramWatch.over && t.finish === undefined && (!t.resume || t.resume === "sending")) {
+ ramIdleFreed = true;
+ await comfy.free();
+ }
},
},
},
@@ -1012,11 +1019,13 @@ 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.
+ // Other programs use the PC's memory (its RAM guard): a claim prefers no job that streams from RAM.
job = runner
- .claimAndRun(!o?.onlyHeld && ramWatch?.over ? { ...o, noStream: true } : o)
+ .claimAndRun(!o?.onlyHeld && ramOn && ramWatch.over ? { ...o, noStream: true } : o)
.then((had) => {
if (!o?.onlyHeld) gpuMissedAt = had ? -Infinity : now();
+ // A GPU job ran: its ComfyUI may hold models again, let go of once it is idle.
+ if (had && !o?.onlyHeld) ramIdleFreed = false;
})
.catch((e) => log(comfy.task ? `A job stopped: ${failure(e)}` : `It can't ask the studio for a job: ${failure(e)}`))
.finally(() => {
@@ -1089,12 +1098,10 @@ 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.
@@ -1137,11 +1144,22 @@ 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) {
+ // The RAM guard, while the owner's switch is on, 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.
+ const ramSwitch = answer?.worker?.ramGuard === true;
+ if (answer && ramSwitch !== ramOn) {
+ if (ramSwitch) log(`Its RAM guard is on: with other programs above ${gbOf(ramGuard.othersMb)} of this PC's memory, it prefers jobs that fit whole on its card, and its ComfyUI lets go of its memory before each job and when idle.`);
+ else if (ramOn) log("Its RAM guard is off: it takes any job it can run, as before.");
+ if (!ramSwitch) {
+ ramWatch.clear();
+ ramRead = null;
+ ramGood = null;
+ }
+ ramOn = ramSwitch;
+ }
+ if (ramOn && !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)
@@ -1152,7 +1170,7 @@ async function work(saved, deps, owner) {
})
.finally(() => (ramReading = null));
}
- if (ramWatch && ramRead) {
+ if (ramOn && ramRead) {
const { split: got } = ramRead;
ramRead = null;
if (got) {
@@ -1163,16 +1181,17 @@ async function work(saved, deps, owner) {
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.");
+ ramWatch.update(t - ramGoodAt <= RAM_REUSE_MS ? ramGood : null);
+ if (!wasOver && ramWatch.over) {
+ log(`Other programs use ${gbOf(ramWatch.othersMb)} of this PC's memory${ramWatch.who ? ` (the most: ${ramWatch.who})` : ""}, above its RAM guard's line of ${gbOf(ramGuard.othersMb)}: it prefers jobs that fit whole on its card, and its ComfyUI lets go of its memory before each job and when idle.`);
+ ramIdleFreed = false;
+ } else if (wasOver && !ramWatch.over) log("Other programs' memory is under its RAM guard's line again: it takes any job it can run, as before.");
+ }
+ // Above the line with no GPU job in hand: its own ComfyUI lets go of its memory, once until its next GPU job.
+ if (ramOn && ramWatch.over && !ramIdleFreed && !busyJob && comfy.ready) {
+ ramIdleFreed = true;
+ await comfy.free();
}
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
@@ -1196,7 +1215,7 @@ async function work(saved, deps, owner) {
});
} else modelsMissing = missing;
}
- let next = localPause(control, gpu, comfyTrouble, t, modelsMissing, ramWatch) ?? { paused: false, why: null, until: null };
+ let next = localPause(control, gpu, comfyTrouble, t, modelsMissing) ?? { 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 };
@@ -1344,10 +1363,9 @@ 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. Its RAM guard's
- // pause stops it too: its server's memory goes back to the PC's other programs.
+ // GPU's job to end before it restarts on new code, the text slot goes on: text jobs take seconds.
if (text) {
- const byHand = pause.paused && /^(here|ram-busy)/.test(pause.why ?? "");
+ const byHand = pause.paused && /^here/.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 d7258833..73790bd9 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -301,26 +301,6 @@ 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.
@@ -328,6 +308,32 @@ On Windows, the pause shortcut (Ctrl+Alt+P, from `fuobe worker install`) runs `f
for 1, 2 or 4 hours, or until you resume, and then pauses at once: the job goes back to the queue at no cost, and its
ComfyUI stops.
+### This PC's memory
+
+The RAM guard is for a PC that someone also works on, with programs that need memory more than the GPU (an editor, a
+game, Python, another AI app). It is off by default.
+
+- **The switch.** Turn it on or off for one worker in Settings → Workers with **RAM guard**
+ (`PATCH /api/admin/workers/{id}` with `ramGuard`). The worker learns it from the next beat's answer
+ (`worker.ramGuard`). The switch decides whether the guard runs. `worker.json` holds only its numbers:
+ `"ramGuard": { "othersGb": 12, "everyS": 10 }`. Both are optional, and those are the defaults. A number the worker
+ can't use keeps its default, and the worker says so in its log.
+- **The reading.** 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. While the switch is on, 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. With the switch off, it reads nothing.
+- **Above `othersGb`,** the worker does two things, and keeps taking work:
+ - Its own ComfyUI lets go of its memory before each GPU job, and once when it goes idle (its `/free`: models
+ unloaded, caches emptied). Only its own ComfyUI: it never asks another ComfyUI on the PC.
+ - Its claims send `noStream: true`: it prefers jobs whose weights fit whole on its card. A streamed job keeps its
+ weights in the PC's RAM for its whole run. A job whose weights fit on the card uses the RAM only while it loads.
+ This is a preference, never a wait: see [Streaming from RAM](#streaming-from-ram).
+- **Nothing pauses.** The guard never pauses the worker and never stops its ComfyUI or its text slot. A job in hand is
+ never stopped for RAM. 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.
+- **A reading that fails** keeps the last good one for a minute. After that, the guard counts the memory as free.
+
### Studio jobs first
A PC can also run ComfyUI work of its own: a ComfyUI that you use by hand, or a queue of your own renders. With
@@ -760,9 +766,17 @@ 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".
+- **A PC whose memory is in use.** A worker's claim with `noStream` (its RAM guard, [This PC's memory](#this-pcs-memory))
+ prefers jobs that fit whole on its card. The studio picks its best job as always. When that job would stream its
+ weights from this worker's RAM, the studio looks at the other workers that are free now: each one may take work,
+ nothing holds it back, and its GPU's slot is empty, as for [first pick](#who-picks-first). For each one, it finds
+ the job that worker's own claim would take next. The jobs that would stream here and that another worker takes next
+ are left for that worker, and this worker takes its best job of the rest. A streamed job that no other worker could
+ take now is still its own, so nobody waits for it: it is marked streamed, and the fallback above applies. A worker
+ busy with a job doesn't count, as for first pick. Another worker whose own last claim also sent `noStream` counts
+ only with the jobs that fit whole on its card, so two such workers never leave a job to each other. A job that fits
+ whole goes with the files that fit (a model variant's too). Its facts stay as they are, and the claim's words add
+ "its PC's memory is in use" with what it did.
- **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.
@@ -1120,10 +1134,10 @@ its target), at most once an hour each.
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,
until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling?, holding?, log? }`. The answer
- adds `worker: { paused, pauseNow, drain, autoResume, insideHours, nextChangeAt, lanes, lanesInside, minProtocol,
- sendInventory, token?, tokenExpiresAt?, catalogVersion? }` (`token`: the next token, above; `tokenExpiresAt`: when
- the token ends, for a token with a lifetime; `lanesInside`: the allowed lanes inside the PC's ceiling;
- `catalogVersion`: the studio's).
+ adds `worker: { paused, pauseNow, drain, autoResume, ramGuard, insideHours, nextChangeAt, lanes, lanesInside,
+ minProtocol, sendInventory, token?, tokenExpiresAt?, catalogVersion? }` (`token`: the next token, above;
+ `tokenExpiresAt`: when the token ends, for a token with a lifetime; `lanesInside`: the allowed lanes inside the
+ PC's ceiling; `catalogVersion`: the studio's; `ramGuard`: the owner's RAM guard switch, see "This PC's memory").
- `holding: { why, since, task? }` says why it doesn't start the line's work now although it may work, while work
waits that it could take: `starting-comfy`, `waiting-for-yield`, `local-work` (the owner's job waits for local
ComfyUI work to finish), `gpu-check`, `updating` (it restarts on new code after its job) or `sending-kept`;
@@ -1174,8 +1188,9 @@ its target), at most once an hour each.
`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. 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
+ slot sends `noStream: true` while its RAM guard says the PC's memory is in use: it then prefers a job whose weights
+ fit whole on its card, and gets a streamed one only when no other worker could take that job now
+ ([Streaming from RAM](#streaming-from-ram)). 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.
@@ -1235,8 +1250,9 @@ Each worker counts against its own rate limits, so three workers that beat every
newest row of its timeline other than a log line. `stats` is its PC's live hardware stats from its last beat, with
`receivedAt` (null: none).
- `GET /api/admin/workers/events`: the workers' timeline (above), newest first, by worker, kinds and run, in pages.
-- `PATCH /api/admin/workers/<id>`: `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs,
- pickOrder, rotate, revoke }`. `pickOrder` is a whole number from -100 to 100 ("Who picks first" above). Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.
+- `PATCH /api/admin/workers/<id>`: `{ paused, pauseNow, drain, autoResume, ramGuard, hours, allow, claimAfterMs,
+ switchAfterMs, pickOrder, rotate, revoke }`. `pickOrder` is a whole number from -100 to 100 ("Who picks first"
+ above). `ramGuard` is `true` or `false` ("This PC's memory" above). Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.
A window can go past midnight.
- `GET /api/admin/queue`: the jobs that wait in each lane, the oldest job, the estimate, and which workers have the
lane warm; and what the workers do now: `running` (each job a worker runs: its run, model, worker, step, progress,
@@ -1265,8 +1281,9 @@ routes.
`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`, `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
+ stand-in PC memory: the site's switch reaching the worker, a claim with `noStream`, its own ComfyUI letting go of
+ its memory before a job and when idle, no pause, and no reading at all with the switch off. The streaming tests
+ check the `noStream` preference: a streamed job left for another free worker, and taken when no other worker can. 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
index 8ae5f674..5c05a36e 100644
--- a/tests/worker-ram-guard.test.ts
+++ b/tests/worker-ram-guard.test.ts
@@ -1,13 +1,15 @@
/**
- * 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.
+ * The worker's RAM guard (bin/lib/worker/ram.mjs), for a PC its owner also works on. The owner's switch in Settings →
+ * Workers turns it on (the beat's answer, `worker.ramGuard`; off by default); worker.json `ramGuard` holds only its
+ * numbers. Its parts on their own (the numbers, the process list, the worker's own processes, the reading), the switch
+ * on the studio's side (the PATCH route, the view, the beat's answer), 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.
+ * - Above the line: its claims ask for no streamed job, and its own ComfyUI lets go of its memory (/free) when idle and
+ * before each job. Nothing pauses: it keeps taking jobs.
+ * - A job in hand goes on to its end.
+ * - The switch off (the default): it never reads the process list, and its claims are as before.
*/
import fs from "node:fs";
import path from "node:path";
@@ -30,15 +32,21 @@ 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("its numbers (ramGuardOf)", () => {
+ it("the defaults when not set; each number on its own; what it can't use keeps its default and says so", () => {
+ const def = { othersMb: 12 * GB, everyMs: 10_000 };
+ expect(ramGuardOf(undefined)).toEqual(def);
+ expect(ramGuardOf(null)).toEqual(def);
+ expect(ramGuardOf(false)).toEqual(def);
+ expect(ramGuardOf({})).toEqual(def);
+ expect(ramGuardOf({ othersGb: 10.5 })).toEqual({ othersMb: 10752, everyMs: 10_000 });
+ expect(ramGuardOf({ everyS: 5 })).toEqual({ othersMb: 12 * GB, everyMs: 5000 });
+ // An older worker.json's afterS is no longer read.
+ expect(ramGuardOf({ othersGb: 16, afterS: 60 })).toEqual({ othersMb: 16 * GB, everyMs: 10_000 });
+ for (const bad of [{ othersGb: 0 }, { othersGb: "x" }, { everyS: 120 }, { everyS: 1 }, [12], 12, true]) {
+ const r = ramGuardOf(bad);
+ expect(r, JSON.stringify(bad)).toHaveProperty("problem");
+ expect(r).toMatchObject(def);
}
});
});
@@ -90,74 +98,28 @@ describe("the process list", () => {
});
});
-describe("the pause and resume (RamWatch)", () => {
- const o = { othersMb: 10 * GB, afterMs: 60_000, autoResume: true, resumeAfterMs: 600_000 };
+describe("the reading (RamWatch)", () => {
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("over the line at once and under it at once; it never pauses the worker", () => {
+ const r = new RamWatch({ othersMb: 10 * GB });
+ r.update(high);
+ expect(r).toMatchObject({ over: true, who: "game.exe", othersMb: 14 * GB });
+ expect(r).not.toHaveProperty("paused");
+ expect(localPause({ paused: false }, { paused: false }, null, 0, [])).toEqual({ paused: false, why: null, until: null });
+ r.update(low);
+ expect(r).toMatchObject({ over: false, who: null, othersMb: 6 * GB });
});
- 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);
+ it("no reading counts as under the line; the switch going off clears it", () => {
+ const r = new RamWatch({ othersMb: 10 * GB });
+ r.update(high);
+ r.update(null);
+ expect(r.over).toBe(false);
+ r.update(high);
+ r.clear();
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 });
});
});
@@ -171,6 +133,8 @@ 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 workersRoute = await import("@/app/api/admin/workers/[id]/route");
+const auth = await import("@/server/auth");
const ROOT = path.resolve(__dirname, "..");
const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
@@ -254,16 +218,29 @@ function fakeRam(o: { gameMb: number }) {
};
}
+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);
+ }
+}
+
interface Started {
logs: string[];
claims: Record<string, unknown>[];
+ /** Its own ComfyUI's /free calls: { unload_models, free_memory } each, with the port they went to. */
+ frees: { port: string; body: Record<string, unknown> }[];
}
-function start(w: W, ram: ReturnType<typeof fakeRam> | null, o: { guard?: boolean; stepMs?: number; afterMs?: number } = {}): Started {
+/** The worker, with the RAM guard's numbers its worker.json would give (a 10 GB line, a reading every 100 ms). */
+function start(w: W, ram: ReturnType<typeof fakeRam> | null, o: { stepMs?: 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 s: Started = { logs: [], claims: [], frees: [] };
const api = apiAs(routes, null);
const ctrl = new AbortController();
const done = runWorker(
@@ -276,13 +253,14 @@ function start(w: W, ram: ReturnType<typeof fakeRam> | null, o: { guard?: boolea
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);
+ if (!String(url).startsWith(SITE)) {
+ const u = new URL(url);
+ if (u.pathname === "/free" && init.method === "POST") s.frees.push({ port: u.port, body: JSON.parse(String(init.body ?? "{}")) });
+ 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));
@@ -305,73 +283,135 @@ function start(w: W, ram: ReturnType<typeof fakeRam> | null, o: { guard?: boolea
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 } }),
+ ramGuard: { othersMb: 10 * GB, 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);
- }
-}
+const said = (s: Started, re: RegExp) => s.logs.some((l) => re.test(l));
+
+describe("the switch on the studio's side", () => {
+ const ownerCookie = () => `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ const patch = (id: string, body: unknown) =>
+ workersRoute.PATCH(new Request(`http://localhost/api/admin/workers/${id}`, { method: "PATCH", headers: { cookie: ownerCookie(), "content-type": "application/json", origin: "http://localhost" }, body: JSON.stringify(body) }), {
+ params: Promise.resolve({ id }),
+ } as never);
+ const beatAnswer = (w: W) =>
+ pool.workerBeat(
+ workerRow(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 5, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }),
+ Date.now(),
+ );
+
+ it("off by default; the owner turns it on and off through the workers API; the view and the beat's answer say it", async () => {
+ const w = addWorker();
+ expect(workerRow(w).ram_guard).toBe(0);
+ expect(pool.listWorkers().find((v) => v.id === w.id)?.ramGuard).toBe(false);
+ expect(beatAnswer(w).worker.ramGuard).toBe(false);
+ const on = await patch(w.id, { ramGuard: true });
+ expect(on.status).toBe(200);
+ expect(((await on.json()) as { worker: { ramGuard: boolean } }).worker.ramGuard).toBe(true);
+ expect(workerRow(w).ram_guard).toBe(1);
+ expect(beatAnswer(w).worker.ramGuard).toBe(true);
+ // Its timeline names the setting, never its value.
+ const edit = db().prepare("SELECT words FROM worker_events WHERE worker_id = ? AND kind = 'admin' ORDER BY id DESC LIMIT 1").get(w.id) as { words: string };
+ expect(edit.words).toBe("Settings changed: ramGuard");
+ expect((await patch(w.id, { ramGuard: false })).status).toBe(200);
+ expect(beatAnswer(w).worker.ramGuard).toBe(false);
+ });
+
+ it("refuses anything but true or false, and changes nothing", async () => {
+ const w = addWorker();
+ pool.patchWorker(w.id, { ramGuard: true });
+ for (const ramGuard of ["yes", 1, null, { othersGb: 12 }]) {
+ const res = await patch(w.id, { ramGuard });
+ expect(res.status, JSON.stringify(ramGuard)).toBe(400);
+ }
+ expect(workerRow(w).ram_guard).toBe(1);
+ });
+});
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 () => {
+ it("switched on, above the line: claims ask for no streamed job, its own ComfyUI lets go of its memory when idle and before each job, and it keeps working", async () => {
const w = addWorker();
+ pool.patchWorker(w.id, { ramGuard: true });
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");
+ const s = start(w, ram);
+ await until(() => said(s, /Its RAM guard is on/) && s.claims.length > 0);
+ expect(s.claims.every((c) => !("noStream" in c))).toBe(true);
+ expect(s.frees).toHaveLength(0);
// 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);
+ await until(() => s.claims.some((c) => c.noStream === true), 5000);
+ expect(said(s, /Other programs use 15\.9 GB of this PC's memory \(the most: game\.exe\), above its RAM guard's line of 10 GB/)).toBe(true);
+ // Idle: its ComfyUI lets go of its memory once (models unloaded, caches emptied), on its own port only.
+ await until(() => s.frees.length === 1, 5000);
+ expect(s.frees[0].body).toEqual({ unload_models: true, free_memory: true });
+ await sleep(800);
+ expect(s.frees).toHaveLength(1);
+ // A job: freed again before it starts, and once more when it is idle after it. No pause at any time.
+ const id = addTask();
+ expect((await until(() => ["done", "failed"].includes(task(id).state) && task(id))).state).toBe("done");
+ await until(() => s.frees.length >= 3, 5000);
+ expect(new Set(s.frees.map((f) => f.port)).size).toBe(1);
+ expect(s.frees.every((f) => f.port !== "8188")).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.
+ expect(pool.workerState(workerRow(w)).state).not.toBe("gpu-busy");
+ expect(s.logs.some((l) => /pausing/i.test(l))).toBe(false);
+ // The game ends: its claims are as before, and its ComfyUI keeps what it loads.
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);
+ await until(() => said(s, /under its RAM guard's line again/), 5000);
const before = s.claims.length;
- await until(() => s.claims.length > before);
+ await until(() => s.claims.length > before + 1);
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");
+ const freed = s.frees.length;
+ const next = addTask();
+ expect((await until(() => ["done", "failed"].includes(task(next).state) && task(next))).state).toBe("done");
+ expect(s.frees.length).toBe(freed);
});
- it("a job in hand goes on to its end; the pause comes after it", async () => {
+ it("a job in hand goes on to its end: never stopped for RAM", async () => {
const w = addWorker();
+ pool.patchWorker(w.id, { ramGuard: true });
const ram = fakeRam({ gameMb: 0 });
const s = start(w, ram, { stepMs: 600 });
+ await until(() => said(s, /Its RAM guard is on/));
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);
+ await until(() => said(s, /Other programs use 15\.9 GB/), 5000);
+ await sleep(1000);
expect(task(id).worker_id).toBe(w.id);
+ expect(workerRow(w).paused_local).toBe(0);
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);
+ expect(task(id).requeues).toBe(0);
});
- it("off (no ramGuard): it never reads the process list, and its claims are as before", async () => {
+ it("off by default: it never reads the process list; switched on from the site it does; off again, its claims are as before", async () => {
const w = addWorker();
const ram = fakeRam({ gameMb: 20 * GB });
- const s = start(w, ram, { guard: false });
+ const s = start(w, ram);
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);
+ // On from the site: its next beat's answer carries it.
+ pool.patchWorker(w.id, { ramGuard: true });
+ await until(() => s.claims.some((c) => c.noStream === true), 30_000);
+ expect(ram.reads.n).toBeGreaterThan(0);
+ // Off again.
+ pool.patchWorker(w.id, { ramGuard: false });
+ await until(() => said(s, /Its RAM guard is off/), 30_000);
+ // Its claims reach the studio without it again (a claim on its way before may still carry it; its many quick claims
+ // here use up the claim rate, so the count starts again).
+ const offAt = Date.now();
+ resetRates();
+ await until(() => (workerRow(w).asked_at ?? 0) > offAt + 500 && workerRow(w).asked_no_stream === 0, 10_000);
+ const reads = ram.reads.n;
+ await sleep(800);
+ expect(ram.reads.n).toBeLessThanOrEqual(reads + 1);
+ expect(workerRow(w).asked_no_stream).toBe(0);
});
});