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.

19.9 KB
Raw Blame
/**
 * 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, 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";
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("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);
    }
  });
});

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 reading (RamWatch)", () => {
  const high = { othersMb: 14 * GB, who: "game.exe" };
  const low = { othersMb: 6 * GB, who: 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("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);
  });
});

// ---------------------------------------------------------------------------------------------------------------------
// 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 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");
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 }),
  };
}

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> }[];
}

/** 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: [], frees: [] };
  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,
    },
    {
      fetch: async (url: string, init: RequestInit = {}) => {
        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));
        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 }),
      ramGuard: { othersMb: 10 * GB, everyMs: 100 },
    },
  );
  running.push({ ctrl, done });
  return s;
}

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("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);
    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), 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);
    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(() => said(s, /under its RAM guard's line again/), 5000);
    const before = s.claims.length;
    await until(() => s.claims.length > before + 1);
    expect(s.claims.at(-1)).not.toHaveProperty("noStream");
    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: 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 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");
    expect(task(id).requeues).toBe(0);
  });

  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);
    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);
    // 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);
  });
});