The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: an account's run reaches them as a job ticket, inside each PC's ceiling
Adarsh0d41494a3bc8
diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsindex 360eb07b..dcbc104a 100644--- a/bin/lib/worker/gpu.mjs+++ b/bin/lib/worker/gpu.mjs@@ -55,6 +55,22 @@ export async function readGpu(cmd = "nvidia-smi") {return { ...g, apps };}+/** `nvidia-smi --query-gpu=compute_cap --format=csv,noheader` → the first GPU's generation ("8.9"), or null. */+export function parseGpuGen(text) {+ const line = String(text ?? "").split(/\r?\n/).map((l) => l.trim()).find(Boolean);+ return line && /^\d{1,2}\.\d{1,2}$/.test(line) ? line : null;+}++/**+ * The GPU's generation (its compute capability), or null when nvidia-smi can't say (an older one, or none).+ *+ * @param {string | string[]} [cmd] its path, or a command and its first arguments (as readGpu takes it)+ */+export async function readGpuGen(cmd = "nvidia-smi") {+ const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];+ return parseGpuGen(await run(bin, [...pre, "--query-gpu=compute_cap", "--format=csv,noheader"]));+}+/*** Is another program using the GPU? Others' VRAM is the GPU's used memory minus what the worker's own ComfyUI holds* (`ownMb`, with an allowance for its CUDA context while it runs). Busy above `busyVramMb`, or when another processdiff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex caa0db40..ca927f2e 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -40,7 +40,7 @@ export async function worker(args, io) {return 2;}const dist = io.distDir ?? path.join(here, "dist");- if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"].every((f) => fs.existsSync(path.join(dist, f)))) {+ if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json", "catalog-version.json", "compose/lib/ticket-compose.mjs"].every((f) => fs.existsSync(path.join(dist, f)))) {io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");return 2;}@@ -209,6 +209,29 @@ async function setup(home, io, say) {return 2;}const autoResume = /^y/i.test(await ask("Resume by itself when the GPU has been free for 10 minutes? (y/N)", old.autoResume ? "y" : "n"));+ // The PC's ceiling: the most it ever runs. The studio and its panel can only narrow inside it. Run setup again to change it.+ const { ceilingFrom, ceilingWords, workerCatalog } = await import("./tickets.mjs");+ const was = old.ceiling ?? {};+ const num = (v) => (typeof v === "number" && v > 0 ? String(v) : "0");+ let catalog = null;+ try {+ catalog = workerCatalog(io.catalogDir ?? path.resolve(here, "../../../workflows/comfyui"));+ } catch {}+ const limits = ceilingFrom(+ {+ work: await ask("Which lanes or workflows may this PC run? all, or their names separated by commas", was.lanes || was.workflows ? [...(was.lanes ?? []), ...(was.workflows ?? [])].join(",") : "all"),+ megapixels: await ask("The largest picture it makes, in megapixels (0 for no limit)", num(was.maxMegapixels)),+ seconds: await ask("The longest clip it makes, in seconds (0 for no limit)", num(was.maxSeconds)),+ outputs: await ask("The most results one run may ask for (0 for no limit)", num(was.maxOutputs)),+ },+ (id) => !catalog || catalog.has(id) || (id.includes("{n}") && [1, 2, 3, 4].some((n) => catalog.has(id.replace("{n}", String(n))))),+ );+ if (limits.error) {+ io.stderr.write(`${limits.error}\n`);+ return 2;+ }+ // The owner's own jobs come as full graphs; answering no takes job tickets only.+ const acceptGraphs = !/^n/i.test(await ask("Also run the studio owner's own jobs, which come as whole graphs? (Y/n)", old.acceptGraphs === false ? "n" : "y"));fs.mkdirSync(workDir, { recursive: true });if (process.platform === "win32") {// Not content indexed: jobs' files stay out of Windows Search.@@ -220,9 +243,12 @@ async function setup(home, io, say) {const saved = savedConfig(home);const port = Number(saved.port) === OLD_SETUP_PORT ? null : (saved.port ?? null);// A token given in FUOBE_WORKER_TOKEN stays out of the file.- saveConfig(home, { ...saved, port, site: site.replace(/\/+$/, ""), token: token || saved.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume });+ const { ceiling: _was, ...rest } = saved;+ void _was;+ saveConfig(home, { ...rest, port, site: site.replace(/\/+$/, ""), token: token || saved.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume, ...(limits.ceiling && { ceiling: limits.ceiling }), acceptGraphs });writeControl(home, { paused: true, now: false, until: null });say(`Saved in ${path.join(home, "worker.json")} (readable by you only). The worker starts paused here.`);+ say(`This PC runs ${ceilingWords(limits.ceiling)}. Run fuobe worker setup again to change it.`);say("Next: fuobe worker run. Resume it here with fuobe worker resume, and on the website in Settings → Workers.");return 0;}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex b0c320c2..ec69a161 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -20,7 +20,7 @@ import { StayAwake } from "./awake.mjs";import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";import { ffmpegOf, PROTOCOL, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";-import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";+import { GpuWatch, othersOf, readGpu, readGpuGen } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";@@ -28,6 +28,7 @@ import { takeLock, workerLives } from "./lock.mjs";import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";import { withPlainResults } from "./results.mjs";import { retrying } from "./retry.mjs";+import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";import { SiteTurns, writeSite } from "./turns.mjs";const here = path.dirname(fileURLToPath(import.meta.url));@@ -151,7 +152,8 @@ export function siteOf(answer) {* Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),* "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,* signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own- * options), readCounters, readListeners, gpuEveryMs }.+ * options), readCounters, readListeners, gpuEveryMs, readGpuGen, and for job tickets: composer (src/lib/ticket-compose.ts+ * as built), catalogVersion, catalogDir, allLanes }.*/export async function runWorker(saved, deps) {// One worker at a time on a worker folder: a second one would stop the first one's ComfyUI, empty its folders and@@ -191,6 +193,17 @@ async function work(saved, deps, owner) {const hold = new Hold(path.join(cfg.workDir, "hold"));const allowed = deps.allowed ?? allowedNodes(cfg.allowNodesFile);const rules = deps.rules ?? inputRules();+ // Job tickets (tickets.mjs): the catalog version its build composes for, its own copy of the catalog, and its PC's+ // ceiling (worker.json `ceiling`), the most it ever runs. Full graphs only for the owner's own jobs, and none at all+ // when worker.json says `acceptGraphs: false`.+ const catalogVersion = deps.catalogVersion !== undefined ? deps.catalogVersion : builtCatalogVersion();+ const catalogDir = deps.catalogDir ?? path.join(ROOT, "workflows/comfyui");+ const ceiling = ceilingOf(cfg.ceiling);+ let composer = deps.composer ?? null;+ let laneOf = null;+ let gpuGen = null;+ let studioCatalog = null;+ log(`This PC runs ${ceilingWords(ceiling)}${cfg.acceptGraphs === false ? ", from job tickets only" : ""}.`);const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy });// Only its own ComfyUI, and only while the process it started is up and ready: never whatever listens on that port.// Its results come without what a save node writes into them unasked (results.mjs).@@ -214,6 +227,8 @@ async function work(saved, deps, owner) {// Two busy readings in a row pause it when it tells programs apart (a reading can catch memory on its way).const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75, busyReadings: turns ? 2 : 1 });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);// ffmpeg: worker.json's, or the PATH's when worker.json names none (an older setup's never did).const ffmpegBin = ffmpegOf(cfg);const ffmpeg = ffmpegBin ? await (deps.ffmpegVersion ?? ffmpegVersion)(ffmpegBin) : null;@@ -376,10 +391,26 @@ async function work(saved, deps, owner) {return arrayBuffer(fs.readFileSync(made));}+ /** A job ticket's graph, composed here (or why it is refused). */+ async function composeJob(t) {+ if (!catalogVersion) return { refused: "update-worker" };+ composer ??= await import("./dist/compose/lib/ticket-compose.mjs");+ // Each workflow's lane, when its ceiling names lanes.+ if (ceiling?.lanes && !laneOf) laneOf = laneMap(index, deps.allLanes ?? (await import("./dist/lanes.mjs")).allLanes);+ const facts = composer.workerFactsFrom(await readPcAnswers(own, comfy.base));+ const r = await composer.composeTicket({ ticket: t.ticket, generationId: t.generationId, inputs: t.inputs }, { catalog: workerCatalog(catalogDir), catalogVersion, ceiling, laneOf, facts });+ if (r.ok) return { graph: r.graph, made: r.made };+ // Why, for the PC's owner (never a setting's value: those are someone's prompt).+ log(`Refused job ${t.id}: ${r.reason === "update-worker" ? "its ticket is for another catalog (update the worker)" : r.reason === "outside-ceiling" ? "it is more than this PC runs (its ceiling in worker.json)" : "its ticket isn't one it can use"}.`);+ return { refused: r.reason };+ }+const runner = new ComputerRunner({api: call,local: own,+ compose: composeJob,+ factsExtra: () => (gpuGen ? { gpuGen } : {}),sha256: async (data) => sha256(Buffer.from(data)),origin: site,socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,@@ -420,6 +451,9 @@ async function work(saved, deps, owner) {gpu: gpuInfo,inventoryHash: invHash,warmLane: null,+ // The catalog its build composes job tickets for, and what its PC may ever run.+ catalogVersion,+ ...(ceiling && { ceiling }),// The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.held: hold.ids().slice(0, 16),// The PC slept: a job taken back from it meanwhile goes on with no blame.@@ -433,6 +467,10 @@ async function work(saved, deps, owner) {// A studio that takes jobs only from a newer worker program: say so once (it sends this worker none).const min = Number(a?.worker?.minProtocol);if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");+ // A studio whose catalog is another than this build's: its people's runs wait for an updated worker. Said once.+ const theirs = a?.worker?.catalogVersion;+ if (typeof theirs === "string" && theirs !== catalogVersion && theirs !== studioCatalog) log("The studio's catalog is another than this worker's: it takes only the owner's own jobs until it is updated (docs/gpu-workers.md, \"Install and update\").");+ if (typeof theirs === "string") studioCatalog = theirs;answer = a;takeToken(a?.worker?.token);// A token from the environment with a lifetime: said once for each end date, so it is replaced there in time.@@ -448,6 +486,8 @@ async function work(saved, deps, owner) {worker: {hold,input: takeInput,+ graphs: cfg.acceptGraphs !== false,+ inside: (t) => graphInside(ceiling, t),// The studio's stall limit comes with each job; a stallMin in worker.json wins over it on this PC.stallMs: 10 * 60_000,stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex f85844f2..a26ba223 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -138,6 +138,7 @@ A file that looks like the note but was changed (it has a password or a sign-in| `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed || `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`) || `FUOBE_POOL_MEDIA_INPUTS` | The kinds of input file a run on the workers may send them, comma-separated: `image` (default) or `image,video,audio`. Clips and sound go only to workers that make each clip and sound again before their ComfyUI reads it (worker protocol 2 with ffmpeg set, [Clips and sound](gpu-workers.md#clips-and-sound)). A hosted run takes a kind only when this and the billing service's policy (`uploads`) both allow it, so set it together with `FUOBE_HOSTED_RUNS` and `FUOBE_BILLING_URL` when the policy opens clips and sound |+| `FUOBE_CATALOG_VERSION` | The catalog version accounts' job tickets are made for ([Job tickets and the PC's ceiling](gpu-workers.md#job-tickets-and-the-pcs-ceiling)), as 64 hex characters. Unset: the studio computes it from its own composer and catalog files, which is what a server running from its own checkout wants. Set it only when the server runs without those files || `FUOBE_WORKER_TOKEN_DAYS` | How many days a pool worker's token lasts; the worker gets its next one in a beat answer ([gpu-workers.md](gpu-workers.md#the-protocol)). Unset or `0`: tokens never expire || `FUOBE_BILLING_URL`, `FUOBE_BILLING_TOKEN` | An optional external billing service for hosted runs ([billing-hook.md](billing-hook.md)). None: hosted runs are closed, or free with `FUOBE_HOSTED_FREE=1` || `FUOBE_MODERATION_URL`, `FUOBE_MODERATION_TOKEN`, `FUOBE_MODERATION_MAX_WAIT_H` | An optional external moderation service ([moderation-hook.md](moderation-hook.md)). None: nothing is checked |diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex bc1365ff..4e296ad0 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -60,6 +60,11 @@ or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected- a folder that a cloud drive syncs;- an ffmpeg path where no ffmpeg runs.+ Setup then asks what this PC may ever run, its ceiling (see "Job tickets and the PC's ceiling"): the lanes or+ workflows (`all`, or their names), the largest picture in megapixels, the longest clip in seconds and the most+ results one run may ask for (0 for no limit). It also asks whether the PC runs the studio owner's own jobs, which+ come as whole graphs. A name that isn't in the studio's catalog is refused. Run setup again to change any answer.+On Windows it marks the worker folder as "not content indexed". The settings go to `worker.json`, and only you canread that file. Setup also pauses the worker on the PC.3. In Settings → Workers, set the worker's hours and the lanes it may run (with a delay for each lane), then press@@ -364,6 +369,49 @@ median of the workers' measured runs). The billing service's line facts (`QueueFonly. Rows are only added, and each is kept a year, like the admin API's log. The owner reads it at`GET /api/admin/workers/jobs` ([admin-api.md](admin-api.md)).+### Job tickets and the PC's ceiling++An account's run reaches a worker as a job ticket, never as a graph. The ticket names a workflow of the catalog, the+catalog version it was made for, the run's settings, each input file (its slot, its name, its kind and its SHA-256),+how many results it makes and how big it is, and the job's run and stall limits. The worker composes the graph itself,+with the studio's own composer (`src/lib/ticket-compose.ts` and `src/lib/comfy-compose.ts`, built into+`bin/lib/worker/dist/compose/`) and its own copy of the catalog (`workflows/comfyui` in its checkout). Every check in+"What the worker checks itself" then runs on the graph it composed. The studio owner's own jobs still come as whole+graphs, and so do a person's own computer's jobs (Fuobe Connect and the browser).++- **Settings.** Each setting has a type and a rule: a choice from a list, a number in a range, true or false, or a list+ of these. A person's words reach only the prompt fields (prompt, negative prompt, dialogue, shots and the voice's+ words). No setting may hold a path: a drive, a share, a rooted or home path, a `..` step, a file address or, in a+ setting that isn't free text, a slash, a file name, a web address or a variable. A file goes only in its slot. The+ studio checks the ticket when it makes it, and the worker checks it again before it composes.+- **Files the graph makes.** A few graphs read a small file that the composer makes (a palette swatch, a fade curve).+ The worker makes it again, checks it against the SHA-256 in the ticket, and sends its own copy to its ComfyUI. It+ never reads the studio's copy.+- **The catalog version.** One SHA-256 over the composer's files and the catalog's workflows. The worker's build writes+ it (`dist/catalog-version.json`), and the studio computes the same from its own files (or reads+ `FUOBE_CATALOG_VERSION`). Each beat says the worker's version. A ticket goes only to a worker with the same version.+ A worker built from another catalog takes the owner's own jobs, and its state in Settings → Workers reads **Update+ the worker** while accounts' runs may come to the install's GPUs. Update it (see "Install and update").+- **The PC is the ceiling.** `ceiling` in `worker.json` (setup asks for it) is the most the PC ever runs:+ `{ "lanes": [...], "workflows": [...], "maxMegapixels": 4, "maxSeconds": 10, "maxOutputs": 4 }`. Leave out a field+ for no limit of its own. Each beat says the ceiling. The lanes that the owner allows in Settings → Workers only+ narrow inside it, and the studio never hands the worker a job outside it: not a lane or a workflow it doesn't list,+ and not a bigger picture, a longer clip or more results. The worker checks each ticket against its ceiling again,+ before and after it composes, and gives back a job outside it.+- **Whole graphs.** Set `"acceptGraphs": false` in `worker.json` (setup asks) and the worker takes job tickets only,+ so not even the owner's own jobs reach it as graphs. A graph for an account's job is refused in any case.+- **Choices that depend on the PC.** The worker makes them from its own ComfyUI's answers (its GPU's memory, its RAM,+ its device, the model files and node packs it has), never from the studio's.++A ticket that the worker refuses before it runs (another catalog, or more than its PC allows) goes back in line at no+cost to the run. That worker is not offered it again until its build or its ceiling changes. A ticket that the worker+can't use at all fails the run, and the person who started it sees one plain sentence.++After an update of the studio that changes the catalog version, each job still waiting in line gets its ticket made+again for the new catalog before the next claim, with its place kept. The studio composes the same request again, so+its settings and files are checked again. A job whose workflow is no longer in the catalog, or whose settings are no+longer allowed, ends with one plain sentence. A job that a worker already holds finishes with the ticket it has.+### What the worker checks itselfBefore its ComfyUI gets a graph, the worker checks all of these. The studio cannot change these checks. To add a model,@@ -422,7 +470,7 @@ alike. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows`image,video,audio` for all); an account's run with a kind it doesn't allow is refused before it is queued. The workerthen makes each one again before its ComfyUI reads it (see "Clips and sound"). Every VideoHelperSuite save node of agraph for the workers is sent with `save_metadata` off, so no prompt rides inside a result. An account's run is shaped-by the workers' own facts (the least VRAM and RAM of the workers allowed its lane), never by the account's own computer.+by the worker that takes it (see "Job tickets and the PC's ceiling"), never by the account's own computer.### Clips and sound@@ -539,9 +587,14 @@ within 10 minutes of each other, each write an alert to the admin log (`worker.aits 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? }`. The answer adds `worker: { paused, pauseNow,- drain, autoResume, insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token?, tokenExpiresAt? }` (`token`:- the next token, above; `tokenExpiresAt`: when the token ends, for a token with a lifetime).+ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling? }`. 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).+ - `catalogVersion` and `ceiling` say the catalog its build composes job tickets for and what its PC may ever run+ (see "Job tickets and the PC's ceiling"). The facts it sends with its ComfyUI's add `gpuGen`, its GPU's+ generation (compute capability), when nvidia-smi can say.- `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUIbehind the guard.- `held` (optional) names the jobs whose finished results the worker keeps on its disk. A pause now sends those@@ -562,7 +615,9 @@ its target), at most once an hour each.(`bigvgan_vocoder/config.json`). The studio keeps only the files the index names, and hashes the list as it wassent, so its hash equals the worker's `inventoryHash`.- `POST /api/gpu/computer/claim`: the browser's claimed task plus- `{ lane, estMs, runLimitMs, stallMs, notAfter, attempt, models }`. See "The run limit" above for `runLimitMs`.+ `{ lane, estMs, runLimitMs, stallMs, notAfter, attempt, models, class, workflowId }`. An account's job carries+ `ticket` in place of `graph`, with its run and stall limits in it too. `class` is `owner` for the owner's own job,+ the only kind that comes with a graph. See "The run limit" above for `runLimitMs`.`stallMs` is how long the job may go with no progress before the worker gives it back (see "The stall limit"). Aworker ignores a `stallMs` under one minute, and uses its own 10 minutes then.- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finished@@ -575,10 +630,13 @@ its target), at most once an hour each.and at most the time since the job was sent to its ComfyUI (plus a minute, because ComfyUI starts a job a momentbefore the studio hears that it was sent).- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and- counts as an attempt. Only a worker's job can be given back.+ counts as an attempt. Only a worker's job can be given back. With `update-worker` (a ticket for another catalog)+ or `outside-ceiling` (more than its PC allows), the job never ran there: it costs no attempt, it waits as a job no+ worker took (its wait limit holds, unless a worker ran it before), and that worker is not offered it again until+ its build or its ceiling changes.- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,- `input-crashed` (its ComfyUI stopped twice on the job) or `input-unreadable` (ffmpeg could not read a clip or a- sound) as the reason. The worker's own log names the node and the input, never the value. For+ `input-crashed` (its ComfyUI stopped twice on the job), `input-unreadable` (ffmpeg could not read a clip or a+ sound) or `bad-ticket` (a ticket it can't use, or a graph where a ticket belongs) as the reason. The worker's own log names the node and the input, never the value. For`input-crashed` and `input-unreadable`, and for a job that a worker gave back for the last time, the person whostarted the run sees one plain sentence with no technical detail.@@ -586,7 +644,10 @@ Each worker counts against its own rate limits, so three workers that beat every### For the owner-- `GET /api/admin/workers` and `POST /api/admin/workers` (`{ name, pool? }`; the answer shows the token once).+- `GET /api/admin/workers` and `POST /api/admin/workers` (`{ name, pool? }`; the answer shows the token once). Each+ worker shows its PC's `ceiling`, the allowed lanes inside it (`lanesInside`), its `catalogVersion` and whether that+ is the studio's (`catalogCurrent`). Its state is `update-worker` while it is built from another catalog and accounts'+ runs may come to the install's GPUs.- `PATCH /api/admin/workers/<id>`: `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs,rotate, revoke }`. Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.A window can go past midnight.diff --git a/src/app/api/gpu/computer/claim/route.ts b/src/app/api/gpu/computer/claim/route.tsindex 09a31ee9..533845e0 100644--- a/src/app/api/gpu/computer/claim/route.ts+++ b/src/app/api/gpu/computer/claim/route.ts@@ -1,11 +1,12 @@import { callerKey, principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";import { workerClaim } from "@/server/computer/pool";import { claim } from "@/server/computer/tasks";+import { refreshTicketsBeforeClaim } from "@/server/computer/ticket-refresh";/*** The person's Fuobe tab asks for a job to run on its ComfyUI: one it started before and lost track of (a reload), or,- * when this computer runs the waiting jobs, the oldest one. The answer is the graph exactly as the server built it, the- * inputs to send under the names it chose, the prompt id it minted, and a new token for every call about it. No job:+ * when this computer runs the waiting jobs, the oldest one. The answer is the graph exactly as the server built it (for+ * an account's run on the workers, its job ticket: src/lib/job-ticket.ts), the inputs to send under the names it chose, the prompt id it minted, and a new token for every call about it. No job:* 204.*/export async function POST(request: Request) {@@ -17,6 +18,8 @@ export async function POST(request: Request) {const running = Array.isArray(body?.running) ? body.running.filter((x): x is string => typeof x === "string").slice(0, 32) : [];try {const worker = requestWorker(request);+ // Job tickets made for the catalog before this version of the studio are made again first (ticket-refresh.ts).+ if (worker?.kind === "pool") await refreshTicketsBeforeClaim();// A shared GPU takes the best task it can run from its pool (pool.ts); a person's computer, their own oldest.const task = worker?.kind === "pool" ? workerClaim(worker, running) : claim(principal, String(body?.device ?? ""), running);if (!task) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex b92e52a2..0f6d0cae 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -28,6 +28,9 @@ import {type WantedFile,} from "./relay";+/** A file's bytes as an ArrayBuffer of exactly its length. */+const toArrayBuffer = (d: ArrayBuffer | Uint8Array): ArrayBuffer => (d instanceof Uint8Array ? (d.buffer.slice(d.byteOffset, d.byteOffset + d.byteLength) as ArrayBuffer) : d);+/** The parts of a WebSocket the runner uses (the browser's, or Node's). */export interface SocketLike {binaryType: string;@@ -64,6 +67,14 @@ export interface RunnerDeps {vet?: (t: ClaimedTask) => TabFailure | null | Promise<TabFailure | null>;/** A job ended here, done or not: a worker deletes its files. */ended?: (t: ClaimedTask, phase: LocalJob["phase"]) => void | Promise<void>;+ /**+ * A worker program's composer (src/lib/ticket-compose.ts): the graph of a job ticket (src/lib/job-ticket.ts), built+ * from its own copy of the catalog, with the small files the graph makes itself; or why it refuses the ticket. A+ * browser tab has none: it never gets a ticket.+ */+ compose?: (t: ClaimedTask) => Promise<ComposedJob | { refused: TicketRefused }>;+ /** More facts to send with its ComfyUI's (a worker's GPU generation). */+ factsExtra?: () => Partial<ComputerFacts>;/** More to say in each beat (a worker's pause, its GPU, its inventory), and what the studio answered. */beatExtra?: () => Record<string, unknown>;onBeat?: (a: BeatAnswer) => void;@@ -71,6 +82,15 @@ export interface RunnerDeps {worker?: WorkerHooks;}+/** Why a worker refuses a job ticket: another catalog, more than its PC allows, or a ticket it can't use (or a graph where a ticket belongs). */+export type TicketRefused = "update-worker" | "outside-ceiling" | "bad-ticket";++/** A job ticket composed on the worker: its graph, and the files the graph makes itself (sent to its ComfyUI with the inputs). */+export interface ComposedJob {+ graph: NonNullable<ClaimedTask["graph"]>;+ made: { name: string; data: ArrayBuffer | Uint8Array; contentType: string }[];+}+/** A finished job's results as a worker keeps them on its own disk: its entries (one, or a meta-batch's passes). */export interface HeldResults {kind: "finished" | "passes";@@ -113,6 +133,13 @@ export interface WorkerHooks {stallLocalMs?: number | null;/** Free its ComfyUI's memory (before the one retry after it ran out). */free(): Promise<void>;+ /**+ * It takes full graphs from the studio for the owner's own jobs (false: job tickets only). A graph for anyone else's+ * job is refused whatever this says: an account's run comes as a ticket.+ */+ graphs?: boolean;+ /** Is a graph job (the owner's own) inside its PC's ceiling, by its lane or workflow? A ticket's are the composer's to check. */+ inside?(t: ClaimedTask): boolean;/** How many times its ComfyUI stopped while it ran this task. */crashes(t: ClaimedTask): number;/** Its ComfyUI won't let go of a prompt: stop it (the worker starts it again). */@@ -360,7 +387,7 @@ export class ComputerRunner {const l = await this.look();if (l.comfy !== "ok") return null;if (o.guard || this.guard === undefined) this.guard = await this.read<unknown>("/fuobe/guard").then(isGuard, () => false);- const f: ComputerFacts = statsFacts(l.stats, this.deps.origin, this.guard);+ const f: ComputerFacts = { ...statsFacts(l.stats, this.deps.origin, this.guard), ...this.deps.factsExtra?.() };if (o.loras) {const loras = await this.read<unknown>("/models/loras").catch(() => null);if (Array.isArray(loras)) f.loras = loras.filter((x): x is string => typeof x === "string");@@ -556,6 +583,8 @@ export class ComputerRunner {private leases = new Map<string, string>();private promptOf = new Map<string, string>();+ /** The files a composed job ticket's graph makes, by task and name: sent from here, never read from the studio. */+ private madeOf = new Map<string, Map<string, { data: ArrayBuffer | Uint8Array; contentType: string }>>();private stoppedDone = new Set<string>();/**@@ -606,6 +635,7 @@ export class ComputerRunner {try {await this.runJob(t);} finally {+ this.madeOf.delete(t.id);const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase)).catch(() => {});}@@ -621,7 +651,17 @@ export class ComputerRunner {// A worker's results kept from before (it stopped after its ComfyUI finished): they go up, the job doesn't run again.const held = worker ? await worker.hold.get(t).catch(() => null) : null;if (!held) {- const problem = graphProblem(t.graph, t.inputs.map((i) => i.name));+ // A job ticket becomes its graph here (a worker's composer); a graph comes only for the owner's own jobs.+ const notMine = await this.graphOf(t);+ if (notMine === "update-worker" || notMine === "outside-ceiling") {+ await this.giveBack(t, notMine);+ return this.job(t, { phase: "failed" });+ }+ if (notMine) {+ await this.report(t, { event: "failed", reason: "bad-ticket" });+ return this.job(t, { phase: "failed" });+ }+ const problem = graphProblem(t.graph!, t.inputs.map((i) => i.name));if (problem) {await this.report(t, { event: "failed", reason: "unsafe-graph" });return this.job(t, { phase: "failed" });@@ -689,6 +729,27 @@ export class ComputerRunner {}}+ /**+ * The job's graph, or why it is refused. A ticket is composed by the worker's own composer (a runner without one gives+ * it back to a worker that has one, or refuses it in a browser). A graph is taken as it is by a browser tab; a worker+ * takes one only for the owner's own job, and only while it takes graphs at all.+ */+ private async graphOf(t: ClaimedTask): Promise<TicketRefused | null> {+ const worker = this.deps.worker;+ if (t.ticket !== undefined) {+ if (!this.deps.compose) return worker ? "update-worker" : "bad-ticket";+ const c = await this.deps.compose(t).catch((): { refused: TicketRefused } => ({ refused: "bad-ticket" }));+ if ("refused" in c) return c.refused;+ t.graph = c.graph;+ this.madeOf.set(t.id, new Map(c.made.map((m) => [m.name, { data: m.data, contentType: m.contentType }])));+ return null;+ }+ if (!t.graph || typeof t.graph !== "object") return "bad-ticket";+ if (worker && ((t.class !== undefined && t.class !== "owner") || worker.graphs === false)) return "bad-ticket";+ if (worker?.inside && !worker.inside(t)) return "outside-ceiling";+ return null;+ }+/*** A worker's report of a finished job: its entries, its ComfyUI's execution time and its GPU's name (`kept`: results* kept from an earlier try).@@ -742,7 +803,7 @@ export class ComputerRunner {private async resend(t: ClaimedTask): Promise<boolean> {const own = { promptIds: [t.promptId] };await this.send("/history", { delete: [t.promptId] }, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [t.promptId] }) }).catch(() => null);- const body = { prompt: t.graph, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };+ const body = { prompt: t.graph!, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };const res = await this.send("/prompt", body, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);const answer = (await res?.json().catch(() => ({}))) as { prompt_id?: string } | undefined;if (!res?.ok || typeof answer?.prompt_id !== "string") return false;@@ -774,9 +835,12 @@ export class ComputerRunner {if (!there) await this.waitForComfy(t);const names = t.inputs.map((i) => i.name);const worker = this.deps.worker;+ const made = this.madeOf.get(t.id);for (const input of t.inputs) {// From the studio, checked against its SHA-256. A worker reads it at most once a job (it keeps a copy), so a- // studio that says it was read enough times (429) means it failed.+ // studio that says it was read enough times (429) means it failed. A file a composed ticket's graph makes itself+ // is the worker's own (its composer checked it against the ticket): the studio's copy is never read.+ const own = made?.get(input.name);const read = async (): Promise<ArrayBuffer | TabFailure> => {const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/inputs/${input.n}`, { headers: { "X-Fuobe-Lease": t.lease } });if (res.status === 404 || res.status === 409) throw new Stopped();@@ -785,7 +849,7 @@ export class ComputerRunner {const data = await res.arrayBuffer();return (await this.deps.sha256(data)) === input.sha256 ? data : "input-changed";};- const got = worker ? await worker.input(t, input, read) : await read();+ const got = own ? toArrayBuffer(own.data) : worker ? await worker.input(t, input, read) : await read();if (got === "give-back") return got;if (typeof got === "string") {await this.report(t, { event: "failed", reason: got });@@ -808,7 +872,7 @@ export class ComputerRunner {return false;}}- const body = { prompt: t.graph, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };+ const body = { prompt: t.graph!, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };const res = await this.send("/prompt", body, { promptIds: [t.promptId] }, { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);if (!res) {await this.waitForComfy(t);diff --git a/src/lib/lanes.ts b/src/lib/lanes.tsindex 93679ccb..a5d96c3b 100644--- a/src/lib/lanes.ts+++ b/src/lib/lanes.ts@@ -25,6 +25,10 @@ export interface Needs {packs: string[];/** The graphics memory a worker must report, with VRAM_TOLERANCE already allowed for. */minVramBytes: number;+ /** How big the job is (its largest picture in megapixels, its longest clip in seconds, its results): a PC's ceiling reads it. */+ size?: { megapixels: number; seconds: number; outputs: number };+ /** A job ticket's catalog version (src/lib/job-ticket.ts): only a worker built for that catalog takes the task. */+ catalogVersion?: string;}/**diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 5719a5d9..a76c1bd2 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -7,6 +7,8 @@* Pure (no I/O): the server's checks and the tab's script share it. None of these words reach the UI.*/+import type { Ceiling, JobTicket } from "./job-ticket";+/** Where a task is. */export type RelayState = "waiting" | "sending" | "queued" | "running" | "collecting" | "done" | "failed" | "canceled";@@ -24,18 +26,20 @@ export interface HistoryEntryLike {}/**- * Why the tab gave up on a task by itself (the server says it in plain words). A worker adds two: its ComfyUI stopped- * twice while running the task ("input-crashed"), and a clip or a sound that couldn't be made again ("input-unreadable").+ * Why the tab gave up on a task by itself (the server says it in plain words). A worker adds three: its ComfyUI stopped+ * twice while running the task ("input-crashed"), a clip or a sound that couldn't be made again ("input-unreadable"),+ * and a job ticket it refused (src/lib/job-ticket.ts), or a graph where a ticket belongs ("bad-ticket").*/-export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified", "input-crashed", "input-unreadable"] as const;+export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified", "input-crashed", "input-unreadable", "bad-ticket"] as const;export type TabFailure = (typeof TAB_FAILURES)[number];/*** Why a worker gives a task back to the line (another worker, or this one later, runs it): it made no progress for too* long ("stalled"), it ran past its run limit ("run-limit"), or it takes clips or sound and this worker can't make them- * again ("media").+ * again ("media"). Two more cost the task nothing (it never ran there): its job ticket was made for another catalog+ * than the worker's ("update-worker"), or the job is more than its PC allows ("outside-ceiling").*/-export const GIVE_BACK = ["stalled", "run-limit", "media"] as const;+export const GIVE_BACK = ["stalled", "run-limit", "media", "update-worker", "outside-ceiling"] as const;export type GiveBackWhy = (typeof GIVE_BACK)[number];/** What the tab reports about one task. */@@ -120,7 +124,12 @@ export interface ClaimedTask {generationId: string;/** The claim's token: every call about this task carries it. */lease: string;- graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ /**+ * The graph exactly as the server built it: a person's own computer's tasks, and the owner's own jobs on the workers.+ * An account's run on the workers carries a job ticket instead (`ticket`), and the worker composes the graph itself.+ */+ graph?: Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ ticket?: JobTicket;promptId: string;/** Ask ComfyUI for live previews of this prompt. */preview: boolean;@@ -144,6 +153,9 @@ export interface ClaimedTask {notAfter?: number | null;attempt?: number;models?: { folder: string; name: string; size: number; sha256: string | null }[];+ /** A worker's task: its class in the line ("owner": the owner's own job), and its workflow. */+ class?: "paid" | "free" | "owner";+ workflowId?: string;}/** The tab's facts about its ComfyUI (never its command line: that holds paths and user names). */@@ -161,6 +173,8 @@ export interface ComputerFacts {guard?: boolean;/** Its LoRA files (sent now and then, not on every beat). */loras?: string[];+ /** A worker's GPU generation (its compute capability, "8.9"). */+ gpuGen?: string;}export const FACT_LIMITS = { loras: 20_000, loraName: 256, text: 120 };@@ -209,6 +223,10 @@ export interface WorkerAnswer {* token (one given in its environment) says so before then.*/tokenExpiresAt?: number;+ /** The catalog version the studio makes job tickets for (src/lib/job-ticket.ts): a worker with another one is told to update. */+ catalogVersion?: string;+ /** The lanes it may take now: the owner's allowed lanes (`lanes`), narrowed to its PC's ceiling. */+ lanesInside?: string[];}/** What a worker says in its beat, on top of a browser's. */@@ -234,6 +252,10 @@ export interface WorkerBeat {stopped: string[];/** The tasks whose finished results the worker keeps on its disk (a stop-now leaves them its own, to send them up). */held?: string[];+ /** The catalog version its build composes job tickets for (absent: an older worker, which takes no ticket). */+ catalogVersion?: string | null;+ /** What its PC may ever run (worker.json `ceiling`, src/lib/job-ticket.ts Ceiling). The studio only narrows inside it. */+ ceiling?: Ceiling;/*** How long its PC slept (ms) since its last beat that the studio answered. A job the studio took back from it for* going quiet during that sleep goes on with no blame: no attempt counted, and this worker may take it again.@@ -430,6 +452,8 @@ export function tabFailureWords(reason: TabFailure, status?: number): string {return "This run couldn't finish with these files or settings.";case "input-unreadable":return "A clip or sound in this run couldn't be read.";+ case "bad-ticket":+ return "This run couldn't be made with these settings.";default:return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 54e44592..2453acb0 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -1,10 +1,13 @@import "server-only";import crypto from "node:crypto";+import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";import { allLanes, laneLabel, lanesFor, MEDIA_KINDS, needsOf, type Inventory, type Needs } from "@/lib/lanes";import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";import { loadIndex } from "../gpu/index-file";+import { hostedRunsOn } from "../hosted-switch";+import { catalogVersion } from "./catalog-version";import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";import { queueSettings, runCeilingMs } from "../queue-settings";import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";@@ -60,7 +63,7 @@ export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.c*/const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;/** The columns the line's counts read (never a task's graph or files). */-const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class";+const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json";/*** A task a worker took that is still sending its files to its ComfyUI this long after the claim (or after its ComfyUI lost* it and it began sending them again on the same claim) goes back in line.@@ -98,8 +101,18 @@ const capableOf = (w: WorkerRow) => json<{ lanes: string[]; workflows: string[]const factsOf = (w: WorkerRow) => json<ComputerFacts>(w.facts_json, {});const hoursOf = (w: WorkerRow): Hours | null => parseHours(json<unknown>(w.hours_json, null));const benchOf = (w: WorkerRow) => json<Record<string, { medianMs?: number; p90Ms?: number; loadMs?: number; peakVramBytes?: number }>>(w.bench_json, {});+/** What its PC may ever run, as its last beat said (null: no ceiling of its own). */+export const ceilingOf = (w: Pick<WorkerRow, "ceiling_json">): Ceiling | null => (w.ceiling_json ? cleanCeiling(json<unknown>(w.ceiling_json, {})) : null);+/**+ * Its build composes job tickets for this studio's catalog (src/lib/job-ticket.ts). A worker built from another catalog+ * (or too old to say) takes the owner's own jobs, and no account's run until it is updated.+ */+export const catalogCurrent = (w: Pick<WorkerRow, "catalog_version">): boolean => {+ const v = catalogVersion();+ return !!v && w.catalog_version === v;+};-export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "models-not-ready" | "waiting-for-yield" | "offline";+export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "models-not-ready" | "waiting-for-yield" | "update-worker" | "offline";/** The state in one word, and in words for the owner ("Paused here until 16:30", "Your GPU is busy (blender.exe)"). */export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerState; words: string } {@@ -128,6 +141,8 @@ export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerStatif (why.endsWith(":no-answer")) return { state: "waiting-for-yield", words: "Waiting for local ComfyUI work to make room (no answer after 3 minutes)" };return { state: "waiting-for-yield", words: `Waiting for local ComfyUI work to make room${w.local_until ? ` (starts about ${clock(w.local_until, tz)})` : ""}` };}+ // Built from another catalog while people's runs may come here: it takes the owner's own jobs, and theirs once updated.+ if (hostedRunsOn() && catalogVersion() && !catalogCurrent(w)) return { state: "update-worker", words: "Update the worker: it takes only your own jobs until then" };return { state: "idle", words: "Ready" };}@@ -172,6 +187,8 @@ export function cleanBeat(b: unknown): WorkerBeat {tempC: num(gpu.tempC),},...(o.facts !== undefined && { facts: cleanFacts(o.facts) }),+ ...(typeof o.catalogVersion === "string" && /^[0-9a-f]{64}$/.test(o.catalogVersion) && { catalogVersion: o.catalogVersion }),+ ...(o.ceiling !== undefined && o.ceiling !== null && { ceiling: cleanCeiling(o.ceiling) }),inventoryHash: text(o.inventoryHash, 80),warmLane: text(o.warmLane, 16),running: Array.isArray(o.running) ? (o.running.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],@@ -196,8 +213,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAconst facts = b.facts ? { ...b.facts, loras: undefined } : undefined;d.prepare(`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,- warm_lane = ?, facts_json = COALESCE(?, facts_json) WHERE id = ?`,- ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, w.id);+ warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ? WHERE id = ?`,+ ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, b.catalogVersion ?? null, b.ceiling ? JSON.stringify(b.ceiling) : null, w.id);// Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.if (b.slept) forgiveSleep(w, b.slept, now);for (const r of b.running) {@@ -250,7 +267,9 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAinsideHours: h.inside,nextChangeAt: h.nextChangeAt,lanes: Object.keys(allowOf(fresh)),+ lanesInside: lanesInside(Object.keys(allowOf(fresh)), ceilingOf(fresh)),minProtocol: MIN_PROTOCOL,+ ...(catalogVersion() && { catalogVersion: catalogVersion()! }),// While a model folder isn't there, the studio keeps the list it has (its lanes don't go missing meanwhile).sendInventory: b.local.why !== MODELS_NOT_READY && (!fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash),...(nextToken && { token: nextToken }),@@ -371,15 +390,22 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimedif (t.state === "waiting") logWorkerJob("claimed", t, w.id, now);// A worker that lost track of its own task gets it again with its first claim's time, so the sending clock (SENDING_MS)// is never wound back by asking again.- const c = takeTask(t, device, now, { worker_id: w.id, ...(t.state !== "waiting" && t.device === device && t.claimed_at && { claimed_at: t.claimed_at }) });+ // A job ticket's task keeps the time of its claim before this one: a refusal of the ticket (another catalog, more+ // than the PC allows) puts it back as it was, so a task no worker ever ran keeps its wait limit.+ const before = t.ticket_json && t.state === "waiting" ? { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), claimedBefore: t.claimed_at ?? null }) } : {};+ const c = takeTask(t, device, now, { worker_id: w.id, ...before, ...(t.state !== "waiting" && t.device === device && t.claimed_at && { claimed_at: t.claimed_at }) });+ // A job given back once for running past its limit gets the whole run ceiling on its next try (a lane's times may+ // come from shorter jobs than this one); past that, it fails.+ const limit = runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs);+ const stall = stallLimitMs(t.lane);return {...c,+ // A job ticket carries its run and stall limits too.+ ...(c.ticket && { ticket: { ...c.ticket, runLimitMs: limit, stallMs: stall } }),lane: t.lane ?? undefined,estMs: estOn(t, w),- // A job given back once for running past its limit gets the whole run ceiling on its next try (a lane's times may- // come from shorter jobs than this one); past that, it fails.- runLimitMs: runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs),- stallMs: stallLimitMs(t.lane),+ runLimitMs: limit,+ stallMs: stall,notAfter: t.not_after,attempt: t.requeues + 1,models: needs?.files ?? [],@@ -391,7 +417,11 @@ function estOn(t: TaskRow, w: WorkerRow): number | null {return (t.lane && benchOf(w)[t.lane]?.medianMs) || t.est_ms || null;}-/** May this worker run this task: its pool, its lane allowed and capable, its files, its VRAM, and the delays. */+/**+ * May this worker run this task: its pool, its lane allowed and capable, its PC's ceiling (the lanes or workflows it+ * may ever run, the largest picture, the longest clip, the most results), its build's catalog for a job ticket, its+ * files, its VRAM, and the delays.+ */function fits(t: TaskRow, w: WorkerRow, now: number): boolean {if (!(t.pools ?? "").split(",").includes(w.pool)) return false;if (t.only_worker && t.only_worker !== w.id) return false;@@ -401,6 +431,9 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {if (!(lane in allow)) return false;const cap = capableOf(w);const needs = json<Needs | null>(t.needs_json, null);+ if (ceilingProblem(ceilingOf(w), { workflowId: needs?.workflowId, lane, size: needs?.size })) return false;+ if (needs?.catalogVersion && needs.catalogVersion !== w.catalog_version) return false;+ if (refusedBy(t).includes(refusalKey(w))) return false;if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return false;const vram = factsOf(w).vramBytes ?? 0;if ((needs?.minVramBytes ?? 0) > vram) return false;@@ -607,6 +640,15 @@ setPoolClocks((t, now) => {/** The words of a run that a worker gave back for the last time. */export const GAVE_BACK_WORDS = "This run couldn't finish.";+/** Workers that refused a task's job ticket without running it (another catalog, or more than their PC allows). */+const refusedBy = (t: Pick<TaskRow, "extra_json">): string[] => json<{ refusedBy?: string[] }>(t.extra_json ?? null, {}).refusedBy ?? [];+/**+ * A worker as it was when it refused a ticket: its id, its build's catalog and its PC's ceiling. Once it is updated or+ * its ceiling changes, it may be offered the task again.+ */+const refusalKey = (w: Pick<WorkerRow, "id" | "catalog_version" | "ceiling_json">) =>+ `${w.id}:${crypto.createHash("sha256").update(`${w.catalog_version ?? ""}\n${w.ceiling_json ?? ""}`).digest("hex").slice(0, 16)}`;+/** A task a worker gave back for running past its run limit (its next try gets the whole run ceiling). */const runLimitedOf = (t: TaskRow) => json<{ runLimited?: boolean }>(t.extra_json, {}).runLimited === true;@@ -617,6 +659,15 @@ const runLimitedOf = (t: TaskRow) => json<{ runLimited?: boolean }>(t.extra_json* fails at once: one more try would only hold a GPU as long again.*/setPoolGiveBack((t, why) => {+ // A job ticket the worker refused before running it (built from another catalog, or more than its PC allows): back in+ // line at no cost, never offered to that worker again, and waiting as a task no worker took (its wait limit holds).+ if (why === "update-worker" || why === "outside-ceiling") {+ const w = t.worker_id ? (db().prepare("SELECT id, catalog_version, ceiling_json FROM relay_workers WHERE id = ?").get(t.worker_id) as Pick<WorkerRow, "id" | "catalog_version" | "ceiling_json"> | undefined) : undefined;+ const { claimedBefore, ...rest } = json<Record<string, unknown>>(t.extra_json, {});+ const extra = { ...rest, refusedBy: [...new Set([...refusedBy(t), ...(w ? [refusalKey(w)] : [])])].slice(-64) };+ if (backInLine(t, { blame: false })) setTask(t.id, { extra_json: JSON.stringify(extra), claimed_at: typeof claimedBefore === "number" ? claimedBefore : null });+ return;+ }if (why === "run-limit") {if (runLimitedOf(t)) return backInLine(t, { blame: true, why: GAVE_BACK_WORDS, last: true });setTask(t.id, { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), runLimited: true }) });@@ -750,8 +801,10 @@ export function workersCanRun(workflowId: string | null): boolean {if (w.pool !== "pool") return false;const allow = allowOf(w);const cap = capableOf(w);- if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow);- if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId)) return false;+ // Inside its PC's ceiling too: the lanes or workflows that PC may ever run.+ const ceiling = ceilingOf(w);+ if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow && insideCeiling(ceiling, { workflowId: id, lane: poolLane(id) }));+ if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId) || !insideCeiling(ceiling, { workflowId, lane })) return false;return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);});}@@ -796,9 +849,16 @@ export function lineFacts(accountId: string | null, asked: string | null, now =* What a task for workers stores: its lane, its needs, its class and its place in line. A person's run is "free" unless* the billing service said "paid"; the owner's own jobs are the "owner" class, served after every person's.*/-export function poolFields(workflowId: string, o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; waitMs?: number; onlyWorker?: string } = {}, now = Date.now()) {+export function poolFields(+ workflowId: string,+ o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string } = {},+ now = Date.now(),+) {const index = loadIndex();- const needs = needsOf(index, workflowId);+ const found = needsOf(index, workflowId);+ // How big the job is (a PC's ceiling reads it), and a job ticket's catalog version (only a worker built for it takes it).+ const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }) };+ const needs = found && { ...found, ...extra };const lane = poolLane(workflowId);return {pools: ["pool"],@@ -807,7 +867,7 @@ export function poolFields(workflowId: string, o: { account?: string; class?: "p// A head start is only inside a class, and never more than a day.rankAt: now - Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000)),lane,- needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0 },+ needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0, ...extra },notAfter: o.waitMs ? now + o.waitMs : undefined,onlyWorker: o.onlyWorker,};@@ -852,6 +912,12 @@ export interface WorkerView {switchAfterMs: number;warmLane: string | null;lanes: string[];+ /** What its PC may ever run (null: no ceiling of its own), and the allowed lanes inside it. */+ ceiling: Ceiling | null;+ lanesInside: string[];+ /** The catalog version its build composes job tickets for, and whether it is this studio's (else: update the worker). */+ catalogVersion: string | null;+ catalogCurrent: boolean;facts: ComputerFacts;bench: ReturnType<typeof benchOf>;seenAt: number | null;@@ -883,6 +949,10 @@ export function workerView(w: WorkerRow, now = Date.now()): WorkerView {switchAfterMs: w.switch_after_ms,warmLane: w.warm_lane,lanes: capableOf(w).lanes,+ ceiling: ceilingOf(w),+ lanesInside: lanesInside(Object.keys(allowOf(w)), ceilingOf(w)),+ catalogVersion: w.catalog_version ?? null,+ catalogCurrent: catalogCurrent(w),facts: factsOf(w),bench: benchOf(w),seenAt: w.seen_at,diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 7a7eadd7..0ef489c7 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -23,6 +23,7 @@ import {type TaskInput,type WantedFile,} from "@/lib/relay";+import type { JobTicket } from "@/lib/job-ticket";import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";import { runCeilingMs } from "../queue-settings";@@ -79,6 +80,8 @@ export interface TaskRow {device: string | null;lease_hash: string | null;graph_json: string | null;+ /** An account's task for workers: its job ticket (src/lib/job-ticket.ts), in place of a graph (graph_json is NULL). */+ ticket_json?: string | null;prompt_id: string;prefix: string | null;meta_batch: number;@@ -290,6 +293,12 @@ export function stageInput(principal: Principal, data: Buffer, contentType: strireturn staged;}+/** An input a principal staged and no task has taken yet: its SHA-256 and content type (a job ticket names both). */+export function stagedInput(principal: Principal, name: string): { sha256: string; contentType: string } | null {+ const r = rdb().prepare("SELECT sha256, content_type FROM relay_inputs WHERE principal = ? AND name = ? AND task_id IS NULL").get(principal, name) as { sha256: string; content_type: string } | undefined;+ return r ? { sha256: r.sha256, contentType: r.content_type } : null;+}+/** Every string a graph's nodes take (the names of the inputs it loads are among them). */function graphStrings(graph: Record<string, { inputs?: Record<string, unknown> }>): Set<string> {const out = new Set<string>();@@ -301,6 +310,11 @@ export interface NewTask {principal: Principal;generationId: string;graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ /**+ * An account's run on the workers: its job ticket. The task then keeps no graph (the worker composes it), and takes the+ * inputs the ticket names.+ */+ ticket?: JobTicket;prefix?: string;metaBatch?: boolean;preview?: boolean;@@ -321,18 +335,18 @@ export function createTask(t: NewTask): { id: string; promptId: string } {const promptId = crypto.randomUUID();const now = Date.now();const d = rdb();- const named = graphStrings(t.graph);+ const named = t.ticket ? new Set(t.ticket.inputs.map((i) => i.name)) : graphStrings(t.graph);d.transaction(() => {const pool = t.pool;d.prepare(`INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,- account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class)- VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json)+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,).run(id,t.principal,t.generationId,- JSON.stringify(t.graph),+ t.ticket ? null : JSON.stringify(t.graph),promptId,t.prefix ?? null,t.metaBatch ? 1 : 0,@@ -350,6 +364,7 @@ export function createTask(t: NewTask): { id: string; promptId: string } {pool?.notAfter ?? null,pool?.onlyWorker ?? null,pool ? (pool.class ?? (pool.account ? "free" : "owner")) : null,+ t.ticket ? JSON.stringify(t.ticket) : null,);const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];let n = 0;@@ -426,6 +441,7 @@ export function cleanFacts(f: unknown, keep?: ComputerFacts): ComputerFacts {...(typeof o.portable === "boolean" && { portable: o.portable }),...((o.cors === "exact" || o.cors === "any" || o.cors === "other") && { cors: o.cors }),...(typeof o.guard === "boolean" && { guard: o.guard }),+ ...(typeof o.gpuGen === "string" && /^\d{1,2}\.\d{1,2}$/.test(o.gpuGen) && { gpuGen: o.gpuGen }),...(loras && { loras }),};}@@ -538,11 +554,14 @@ export function takeTask(t: TaskRow, device: string, now: number, fields: PartiasetTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now, ...(fresh && t.pools && { attempts: 0, sending_since: null }), ...fields });if (fresh) rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));+ // An account's task for workers hands out its job ticket, never a graph (src/lib/job-ticket.ts).+ const ticket = t.ticket_json ? json<JobTicket | null>(t.ticket_json, null) : null;return {id: t.id,generationId: t.generation_id,lease,- graph: json(t.graph_json, {}),+ ...(ticket ? { ticket } : { graph: json(t.graph_json, {}) }),+ ...(t.pools && { class: (t.class === "paid" || t.class === "owner" ? t.class : t.class === "free" || t.account ? "free" : "owner") as "paid" | "free" | "owner", ...(t.workflow_id && { workflowId: t.workflow_id }) }),promptId: t.prompt_id,preview: !!t.preview,...(t.prefix && { prefix: t.prefix }),@@ -904,7 +923,7 @@ export function sweepRelay(now = Date.now()): { inputs: number; tasks: number }.all(now - RELAY_TIMES.keepMs) as { id: string; finished_at: number | null }[];for (const t of ended) {fs.rmSync(taskDir(t.id), { recursive: true, force: true });- d.prepare("UPDATE relay_tasks SET graph_json = NULL WHERE id = ?").run(t.id);+ d.prepare("UPDATE relay_tasks SET graph_json = NULL, ticket_json = NULL WHERE id = ?").run(t.id);}const old = d.prepare("DELETE FROM relay_tasks WHERE state IN ('done','failed','canceled') AND finished_at < ?").run(now - RELAY_TIMES.keepMs);return { inputs: stale.length, tasks: old.changes };diff --git a/src/server/computer/ticket-refresh.ts b/src/server/computer/ticket-refresh.tsnew file mode 100644index 00000000..6bfc84b2--- /dev/null+++ b/src/server/computer/ticket-refresh.ts@@ -0,0 +1,77 @@+import "server-only";+import type { JobTicket } from "@/lib/job-ticket";+import type { Needs } from "@/lib/lanes";+import { composeTicket } from "@/lib/ticket-compose";+import { db } from "../db";+import { getWorkflow, loadManifest } from "../providers/comfyui";+import { catalogVersion } from "./catalog-version";+import { GAVE_BACK_WORDS } from "./pool";+import { endTask, inputsOf, json, setTask, type TaskRow } from "./tasks";++/**+ * Job tickets made before this studio's catalog changed (a new version of the app): a task still waiting in line gets+ * its ticket made again for the catalog it runs now, with its place kept. The same request is composed with this+ * studio's composer, so its files and settings are checked again; the files the graph makes must come out the same. A+ * ticket that no longer composes (its workflow left the catalog, or its settings are no longer allowed) ends its run+ * in one plain sentence. Only waiting tasks: one a worker holds finishes with the ticket it has.+ */+export async function refreshTickets(): Promise<{ refreshed: number; ended: number }> {+ const version = catalogVersion();+ if (!version) return { refreshed: 0, ended: 0 };+ const rows = db()+ .prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND ticket_json IS NOT NULL AND json_extract(ticket_json, '$.catalogVersion') IS NOT ?")+ .all(version) as TaskRow[];+ const catalog = { has: (id: string) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow };+ let refreshed = 0;+ let ended = 0;+ for (const t of rows) {+ const old = json<JobTicket | null>(t.ticket_json ?? null, null);+ if (!old) continue;+ const ticket: JobTicket = { ...old, catalogVersion: version };+ delete ticket.runLimitMs;+ delete ticket.stallMs;+ const inputs = inputsOf(t.id).map((i) => ({ name: i.name, sha256: i.sha256 }));+ const r = await composeTicket({ ticket, generationId: t.generation_id, inputs }, { catalog, catalogVersion: version }).catch(() => null);+ // Written only while the task is as it was read (still waiting, the same ticket).+ db()+ .transaction(() => {+ const nowRow = db().prepare("SELECT state, ticket_json FROM relay_tasks WHERE id = ?").get(t.id) as Pick<TaskRow, "state" | "ticket_json"> | undefined;+ if (!nowRow || nowRow.state !== "waiting" || nowRow.ticket_json !== t.ticket_json) return;+ if (!r?.ok) {+ endTask(t.id, "failed", { error: GAVE_BACK_WORDS });+ ended++;+ return;+ }+ const fresh: JobTicket = { ...ticket, size: r.size };+ const needs = { ...json<Needs | Record<string, never>>(t.needs_json, {}), catalogVersion: version, size: r.size };+ // A new ticket: a worker that refused the old one may take it.+ const { refusedBy: _refused, ...extra } = json<Record<string, unknown>>(t.extra_json, {});+ void _refused;+ setTask(t.id, { ticket_json: JSON.stringify(fresh), needs_json: JSON.stringify(needs), extra_json: JSON.stringify(extra) });+ refreshed++;+ })+ .immediate();+ }+ return { refreshed, ended };+}++declare global {+ var __fuobeTicketRefresh: { version: string; at: number; running: Promise<unknown> } | undefined;+}++/** How often a claim looks again for tickets made for another catalog (another app process may still make them). */+const REFRESH_EVERY_MS = 60_000;++/** Before a worker's claim: refresh old tickets once for each catalog version, and again at most once a minute. */+export async function refreshTicketsBeforeClaim(now = Date.now()): Promise<void> {+ const version = catalogVersion();+ if (!version) return;+ const last = globalThis.__fuobeTicketRefresh;+ if (last && last.version === version && now - last.at < REFRESH_EVERY_MS) {+ await last.running.catch(() => {});+ return;+ }+ const running = refreshTickets().catch(() => null);+ globalThis.__fuobeTicketRefresh = { version, at: now, running };+ await running;+}diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsindex 9f606c75..58d5016d 100644--- a/src/server/computer/workers.ts+++ b/src/server/computer/workers.ts@@ -69,6 +69,10 @@ export interface WorkerRow {/** The network (a short hash) of its last call, and when. */last_network?: string | null;last_net_at?: number | null;+ /** The catalog version its build composes job tickets for (src/lib/job-ticket.ts), as its last beat said. */+ catalog_version?: string | null;+ /** What its PC may ever run (worker.json `ceiling`), as its last beat said. NULL: no ceiling of its own. */+ ceiling_json?: string | null;}const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");diff --git a/src/server/db.ts b/src/server/db.tsindex dbb9d74c..894f5f11 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1016,6 +1016,11 @@ const RELAY_COLUMNS: [string, string, string][] = [["relay_workers", "seen_json", "TEXT"],["relay_workers", "last_network", "TEXT"],["relay_workers", "last_net_at", "INTEGER"],+ // Job tickets (src/lib/job-ticket.ts): an account's task for workers carries one in place of a graph; a worker says+ // the catalog version its build composes for, and what its PC may ever run (its ceiling).+ ["relay_tasks", "ticket_json", "TEXT"],+ ["relay_workers", "catalog_version", "TEXT"],+ ["relay_workers", "ceiling_json", "TEXT"],];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex be8c8f77..9d36264d 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -548,6 +548,7 @@ export const ASSET_FREE: Record<string, string> = {"relay_tasks.refusal_json": "a ComfyUI refusal: node classes and model names","relay_tasks.needs_json": "what a job for the workers needs: workflow, model file names and sizes, node packs, VRAM","relay_tasks.tried_json": "the ids of the workers that lost or failed this job",+ "relay_tasks.ticket_json": "an account's job ticket for the workers: settings, and the names and SHA-256 of the job's own staged inputs","relay_workers.facts_json": "what a worker said about its ComfyUI: its GPU, memory and version","relay_workers.inventory_json": "a worker's model files and node packs: names, sizes and hashes on that PC","relay_workers.lanes_json": "the lanes a worker can run: hashes of model file names",@@ -555,6 +556,7 @@ export const ASSET_FREE: Record<string, string> = {"relay_workers.hours_json": "a worker's hours: a time zone and windows","relay_workers.allow_json": "the lanes the owner lets a worker run, with their delays","relay_workers.seen_json": "the countries and network hashes a worker's token was used from",+ "relay_workers.ceiling_json": "the most a worker's PC may run: lanes, workflow ids and sizes","relay_pairings.facts_json": "what a paired ComfyUI said about itself: its name, GPU and version",};diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex d875ed88..82505666 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -74,12 +74,16 @@ import {resultOf,runnerFacts,stageInput,+ stagedInput,taskProgress,type FinishedPlan,type Principal,type TaskRow,} from "../computer/tasks";import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, workersCanRun } from "../computer/pool";+import { catalogVersion } from "../computer/catalog-version";+import { ticketProblem, type JobTicket } from "@/lib/job-ticket";+import { catalogKnows, ticketFor } from "@/lib/ticket-compose";import { ownerWaitMs } from "../queue-settings";import { worldcastBase, worldcastHealth } from "../worldcast";@@ -1104,7 +1108,9 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,accountOnInstall: !!tenantAccount() && !!(poolScope.getStore() || serverScope.getStore()),ownStudio: !ownGpu() && !computerScope() && !tenantAccount(),});- return { ...out, request: { endpoint: endpointTemplate, op: ctx.op, input: request, made, sent, ...(ctx.loraSlot && { loraSlot: true }) } };+ // What the composer used: the request without the files it dropped (an account's file it didn't send).+ const used = out.dropped.length && request.extra ? { ...request, extra: Object.fromEntries(Object.entries(request.extra).filter(([k]) => !out.dropped.includes(k))) } : request;+ return { ...out, request: { endpoint: endpointTemplate, op: ctx.op, input: used, made, sent, ...(ctx.loraSlot && { loraSlot: true }) } };} catch (e) {if (e instanceof ComposeError) throw new ProviderError(e.message, e.status);throw e;@@ -1112,6 +1118,29 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,}+/** Said when an account's run can't be put into a job ticket (its settings are outside the ticket's rules). */+export const TICKET_REFUSED = "This run couldn't be made with these settings.";++/**+ * An account's run on the workers goes as a job ticket (src/lib/job-ticket.ts), never as a graph: the workflow, this+ * studio's catalog version, the typed settings the composer was given, each input file by its slot and SHA-256, and how+ * many results it makes. The ticket is checked here as the worker checks it before composing (ticketProblem).+ */+export function accountTicket(p: PreparedPrompt, principal: Principal, o: { outputs: number; kind?: MediaKind }): JobTicket {+ const version = catalogVersion();+ if (!version) throw new ProviderError(TICKET_REFUSED);+ let ticket: JobTicket;+ try {+ ticket = ticketFor(p.request, { catalogVersion: version, sent: p.request.sent, file: (name) => stagedInput(principal, name), facts: mediaInfoFor, outputs: { count: o.outputs, kind: o.kind ?? "file" }, size: p.size });+ } catch {+ throw new ProviderError(TICKET_REFUSED);+ }+ const staged = ticket.inputs.map((i) => ({ name: i.name, sha256: stagedInput(principal, i.name)?.sha256 ?? "" }));+ const catalog = { has: (id: string) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow };+ if (ticketProblem(ticket, { catalogVersion: version, known: (id) => catalogKnows(catalog, id), inputs: staged })) throw new ProviderError(TICKET_REFUSED);+ return ticket;+}+/** What ComfyUI's /prompt answers when it refuses a graph. */export type PromptRefusalBody = { error?: { type?: string; message?: string; extra_info?: { class_type?: string } }; node_errors?: unknown };@@ -1571,7 +1600,7 @@ export const comfyProvider: ProviderAdapter = {if (worker === "isolated" && computerScope()) throw new ProviderError(ISOLATED_ON_COMPUTER);// A route's own graph settings (Fuobe Speak's InfiniteTalk recipe) go in unless the run sets them.const asked = route.extra ? { ...input, extra: { ...route.extra, ...input.extra } } : input;- const { manifest, workflow: wf, meta } = await prepareWorkflow(route.endpoint, asked, {+ const prepared = await prepareWorkflow(route.endpoint, asked, {generationId,op: route.op,loraSlot: route.loraSlot === true,@@ -1597,6 +1626,7 @@ export const comfyProvider: ProviderAdapter = {// The pack switched off in Settings → Models & licences: Idol 3D runs its core graph, as without the pack.idolPack: async () => ((await import("@/server/model-access")).readAccess().packs.includes(IDOL_PACK) ? false : comfyHasClass(IDOL_PACK_CLASS, worker)),});+ const { manifest, workflow: wf, meta } = prepared;// MiniMax H3's 2K draft that kept its latent says where (the finish loads it only there: generations.ts latentHandOff).const latentAt = manifest.id === H3_LATENT_DRAFT_WORKFLOW ? comfyPlace() : null;if (latentAt) meta.latentAt = latentAt;@@ -1618,26 +1648,31 @@ export const comfyProvider: ProviderAdapter = {// The owner's job that no worker is allowed and able to run would wait with no end (the owner's jobs have no wait// limit unless the owner sets one): it is refused now, as an account's run is.if (forPool && computer === "owner" && !workersCanRun(manifest.id)) throw new ProviderError(NO_WORKER_FOR_LANE);+ const outputs = Math.max(1, manifest.outputs.length) * Math.max(1, Math.round(Number(input.numOutputs) || 1));+ // An account's run on the workers: a job ticket, and the worker composes the graph (the owner's own jobs keep theirs).+ const ticket = forPool && computer !== "owner" ? accountTicket(prepared, computer, { outputs, kind: model?.kind }) : undefined;const task = createTask({principal: computer,generationId,graph: forPool ? withoutSaveMetadata(wf) : wf,+ ...(ticket && { ticket }),prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,metaBatch,preview: true,workflowId: manifest.id,made: model?.kind,loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),- outputs: Math.max(1, manifest.outputs.length) * Math.max(1, Math.round(Number(input.numOutputs) || 1)),+ outputs,...(forPool && {pool:computer === "owner"? // The owner's jobs on the workers: the lane and files they need, after every person's run (the owner's// class), with the owner's own wait limit (none unless the owner sets one: queue-settings.ts).- poolFields(manifest.id, { class: "owner", waitMs: ownerWaitMs() })+ poolFields(manifest.id, { class: "owner", waitMs: ownerWaitMs(), size: prepared.size }): // An account's: the lane and files they need, in its class (paid before free), in the order they came// (with the billing service's head start inside the class), with the wait set for the run.- poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs() }),+ // A ticket's task goes only to a worker built for its catalog, and inside that PC's ceiling.+ poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs(), size: prepared.size, catalogVersion: ticket?.catalogVersion }),}),});// (`workers`: the run keeps its task's clocks, pool.ts, even when a poll of it fails.)diff --git a/tests/helpers/fake-nvidia-smi.mjs b/tests/helpers/fake-nvidia-smi.mjsindex 44aa205a..60dceab6 100644--- a/tests/helpers/fake-nvidia-smi.mjs+++ b/tests/helpers/fake-nvidia-smi.mjs@@ -1,12 +1,15 @@-// A stand-in for nvidia-smi (the worker's GPU check, bin/lib/worker/gpu.mjs): it answers the two queries the worker-// makes from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "apps": [{ "pid": 1, "name": "python.exe",-// "usedMb": null }] } (usedMb null prints [N/A], as Windows does).+// A stand-in for nvidia-smi (the worker's GPU check, bin/lib/worker/gpu.mjs): it answers the queries the worker makes+// from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "computeCap": "8.9", "apps": [{ "pid": 1, "name":+// "python.exe", "usedMb": null }] } (usedMb null prints [N/A], as Windows does; no computeCap: an older nvidia-smi).//// node tests/helpers/fake-nvidia-smi.mjs <state.json> --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounitsimport fs from "node:fs";const [file, ...args] = process.argv.slice(2);const s = JSON.parse(fs.readFileSync(file, "utf8"));-if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}\n`);+if (args.includes("--query-gpu=compute_cap")) {+ if (!s.computeCap) process.exit(2);+ process.stdout.write(`${s.computeCap}\n`);+} else if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}\n`);else if (args.some((a) => a.startsWith("--query-compute-apps"))) for (const a of s.apps ?? []) process.stdout.write(`${a.pid}, ${a.name}, ${a.usedMb === null || a.usedMb === undefined ? "[N/A]" : a.usedMb}\n`);else process.exit(2);diff --git a/tests/helpers/ticket-worker.ts b/tests/helpers/ticket-worker.tsnew file mode 100644index 00000000..d9df136d--- /dev/null+++ b/tests/helpers/ticket-worker.ts@@ -0,0 +1,26 @@+import type { Ceiling } from "@/lib/job-ticket";+import type { ClaimedTask } from "@/lib/relay";+import { composeTicket, type WorkerFacts } from "@/lib/ticket-compose";++/**+ * A worker's composer in the tests: a job ticket composed as `fuobe worker run` composes it (bin/lib/worker/run.mjs),+ * with this checkout's catalog and catalog version. The answer the shared runner's `compose` takes.+ */+export async function composeOnWorker(t: Pick<ClaimedTask, "ticket" | "generationId" | "inputs">, o: { ceiling?: Ceiling | null; facts?: WorkerFacts; catalogVersion?: string } = {}) {+ const { loadManifest, getWorkflow } = await import("@/server/providers/comfyui");+ const { catalogVersion } = await import("@/server/computer/catalog-version");+ const r = await composeTicket(+ { ticket: t.ticket, generationId: t.generationId, inputs: t.inputs },+ { catalog: { has: (id) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow }, catalogVersion: o.catalogVersion ?? catalogVersion()!, ceiling: o.ceiling, facts: o.facts },+ );+ return r.ok ? { graph: r.graph, made: r.made } : { refused: r.reason };+}++/** The graph a worker composes for a task's ticket, from the task's row (its ticket and the inputs it sends). */+export async function graphOfTask(row: { id: string; generation_id: string; ticket_json?: string | null }) {+ const tasks = await import("@/server/computer/tasks");+ const inputs = tasks.inputsOf(row.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));+ const r = await composeOnWorker({ ticket: JSON.parse(row.ticket_json ?? "null"), generationId: row.generation_id, inputs });+ if ("refused" in r) throw new Error(`The ticket was refused: ${r.refused}`);+ return r.graph as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+}diff --git a/tests/helpers/worker-driver.ts b/tests/helpers/worker-driver.tsindex b04fa833..c5897647 100644--- a/tests/helpers/worker-driver.ts+++ b/tests/helpers/worker-driver.ts@@ -11,15 +11,18 @@** Start a new driver with the same token to bring the worker back.*- * Its beats speak the worker program's own protocol (bin/lib/worker/config.mjs), so it is the worker the studio expects- * today. A beat answer that says the studio needs a newer worker program throws: a driver the studio would never give a+ * Its beats speak the worker program's own protocol (bin/lib/worker/config.mjs) and say this checkout's catalog version,+ * and it composes an account's job ticket with the studio's own composer, so it is the worker the studio expects today.+ * A beat answer that says the studio needs a newer worker program throws: a driver the studio would never give a* job must fail loudly, never look like a feature that isn't built.*/import { ComputerRunner } from "@/lib/computer-runner";import type { BeatAnswer } from "@/lib/relay";+import { catalogVersion } from "@/server/computer/catalog-version";import { PROTOCOL } from "../../bin/lib/worker/config.mjs";import { apiAs, sha256, type ComputerRoutes } from "./computer-tab";import type { StandInComfy } from "./standin-comfy";+import { composeOnWorker } from "./ticket-worker";/** The protocol the driver's beats speak: the worker program's. */export const DRIVER_PROTOCOL: number = PROTOCOL;@@ -147,7 +150,8 @@ export function workerDriver(o: {sha256,origin: "http://localhost:3000",sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, o.sleepCapMs ?? 50))),- beatExtra: () => ({ protocol: DRIVER_PROTOCOL, version: "test", local: { paused: !!paused, why: paused, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),+ compose: (t) => composeOnWorker(t),+ beatExtra: () => ({ protocol: DRIVER_PROTOCOL, version: "test", local: { paused: !!paused, why: paused, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),// As the worker program does when a job ends here: its prompt leaves its ComfyUI's history (once its ComfyUI has// stopped it, when the job was taken back).ended: async (t) => {diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex c687b5dd..10451474 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -4,6 +4,7 @@ import { startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";import { apiAs, loadRoutes, sha256, type ComputerRoutes } from "./helpers/computer-tab";import { tempDir } from "./helpers/temp-dir";+import { composeOnWorker, graphOfTask } from "./helpers/ticket-worker";/*** Account runs on this install's GPUs go through the workers' line: each job of an account's run is a task for the@@ -60,6 +61,7 @@ const { getModel } = await import("@/lib/catalog");const { ComputerRunner } = await import("@/lib/computer-runner");const { POOL_WORDS } = await import("@/lib/relay");const { ACCOUNT_MESSAGES } = await import("@/server/account-files");+const { catalogVersion } = await import("@/server/computer/catalog-version");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -118,12 +120,15 @@ function standInWorker(name = "stand-in", o: { paused?: boolean } = {}) {const lanes = allLanes(loadIndex(), sha);pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });db()- .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")- .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ? WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);return w;}-/** The worker program's side, as `fuobe worker run` drives it: the shared runner with the worker's token and its own ComfyUI. */+/**+ * The worker program's side, as `fuobe worker run` drives it: the shared runner with the worker's token, its own+ * ComfyUI, and its composer for job tickets.+ */function workerRunner(token: string) {const api = apiAs(routes, null, { authorization: `Bearer ${token}` });return new ComputerRunner(@@ -134,7 +139,8 @@ function workerRunner(token: string) {sha256,origin: "http://localhost:3000",sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),- beatExtra: () => ({ protocol: 2, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),+ compose: (t) => composeOnWorker(t),+ beatExtra: () => ({ protocol: 2, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),},{ device: "worker", port: comfy.port, clientId: "worker-test" },);@@ -185,7 +191,7 @@ function accountTask(o: { lane?: string; account?: string; rankAt?: number; notAtype WorkerRow = import("@/server/computer/workers").WorkerRow;const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;const beatAs = (w: { id: string }, now = Date.now()) =>- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);describe("with hosted runs off, nothing changes", () => {@@ -349,9 +355,11 @@ describe("an account's run on the workers", () => {expect(r.status, JSON.stringify(r.body)).toBe(201);const t = await until(() => taskOf(r.body.items![0].id));expect(t).toBeDefined();- expect(t!.graph_json ?? "").not.toContain("fuobe_someone_elses.png");- // The picture its graph loads is the one this run sent, kept for its task.- const graph = JSON.parse(t!.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ // It goes as a job ticket: no graph, and the name the run didn't send isn't in it.+ expect(t!.graph_json).toBeNull();+ expect(t!.ticket_json ?? "").not.toContain("fuobe_someone_elses.png");+ // The picture the worker's graph loads is the one this run sent, kept for its task.+ const graph = await graphOfTask(t!);const loaded = Object.values(graph).filter((x) => x.class_type === "LoadImage").map((x) => String(x.inputs.image));@@ -648,7 +656,7 @@ describe("graphs and results for the workers", () => {const t = rowOf(String((sent.meta as { relay: string }).relay));expect(t.principal).toBe(`acct:${accountId}`);expect(t.pools).toBe("pool");- const graph = JSON.parse(t.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ const graph = await graphOfTask(t);const saves = Object.values(graph).filter((n) => n.class_type === "VHS_VideoCombine");expect(saves.length).toBeGreaterThan(0);for (const node of saves) expect(node.inputs.save_metadata).toBe(false);diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 9f080d38..50723463 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -41,6 +41,7 @@ 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 billing = await import("@/server/billing");const hostedRun = await import("@/server/hosted-run");const limits = await import("@/server/pool-limits");@@ -160,7 +161,7 @@ const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasksconst workerRow = () => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(worker.id) as import("@/server/computer/workers").WorkerRow;/** The stand-in worker takes the next task in line, as the worker program does. */function workerTakes() {- pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));+ pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }));return pool.workerClaim(workerRow(), [], Date.now());}const started = (generationId: string) => !!(db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").get(generationId) as { started_at: number | null } | undefined)?.started_at;diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex 1d2177ee..aedc40d0 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -43,6 +43,7 @@ const { setSetting } = await import("@/server/settings");const { getGeneration } = await import("@/server/generations");const tasks = await import("@/server/computer/tasks");const pool = await import("@/server/computer/pool");+const { catalogVersion } = await import("@/server/computer/catalog-version");const billing = await import("@/server/billing");const qs = await import("@/server/queue-settings");const { loadManifest, comfyProvider, onComputer, NO_WORKER_FOR_LANE } = await import("@/server/providers/comfyui");@@ -106,7 +107,7 @@ function standInWorker(name = "stand-in") {type WorkerRow = import("@/server/computer/workers").WorkerRow;const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;const beatAs = (w: { id: string }, now = Date.now()) =>- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion() }), now);const claimAs = (w: { id: string }, now = Date.now()) => pool.workerClaim(workerRow(w), [], now);const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;diff --git a/tests/recovery-worker.test.ts b/tests/recovery-worker.test.tsindex d73306c3..920782c3 100644--- a/tests/recovery-worker.test.ts+++ b/tests/recovery-worker.test.ts@@ -22,7 +22,8 @@ import { tempDir } from "./helpers/temp-dir";* the checks after it always run against all of them.** Each job's graph is the stand-in's own (a sampler and the run's save node, with the run's file prefix), so the- * worker's node and model checks pass without model files; everything else about the job is the studio's.+ * worker's node and model checks pass without model files; everything else about the job is the studio's. An account's+ * job comes as a job ticket, so the worker's composer here gives the stand-in's graph for it.*/const ROOT = path.resolve(import.meta.dirname, "..");@@ -69,7 +70,16 @@ let studio: {lanes: () => string[];workflows: () => string[];};-let program: { runWorker: Any; rules: Any; parseCounters: Any; ComputerRunner: unknown };+let program: { runWorker: Any; rules: Any; parseCounters: Any; ComputerRunner: unknown; catalogVersion: string };+/** The stand-in graph of each run's job, by the run's id: what the worker's composer gives for its ticket. */+const standInGraphs = new Map<string, Record<string, unknown>>();+const composer = {+ workerFactsFrom: () => ({}),+ composeTicket: async (job: { generationId: string }) => {+ const graph = standInGraphs.get(job.generationId);+ return graph ? { ok: true, graph, workflowId: "stand-in", size: { megapixels: 0, seconds: 0, outputs: 1 }, made: [] } : { ok: false, reason: "bad-ticket", detail: "no stand-in graph" };+ },+};let routes: ComputerRoutes;let svc: StandInBilling;let a1 = "";@@ -105,7 +115,7 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {const { runWorker } = await load("bin/lib/worker/run.mjs");const { inputRules, readCatalog } = await load("scripts/lib/worker-catalog.mjs");const { parseCounters } = await load("bin/lib/worker/local-work.mjs");- program = { runWorker, rules: inputRules(readCatalog(ROOT)), parseCounters, ComputerRunner: (await import("@/lib/computer-runner")).ComputerRunner };+ program = { runWorker, rules: inputRules(readCatalog(ROOT)), parseCounters, ComputerRunner: (await import("@/lib/computer-runner")).ComputerRunner, catalogVersion: (await import("@/server/computer/catalog-version")).catalogVersion()! };routes = await loadRoutes();svc = await startStandInBilling();auth.setPassword("install password");@@ -176,7 +186,9 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {await sleep(20);t = taskOf(id);}- const graph = JSON.parse(t!.graph_json!) as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ // The graph the studio built for the run's ticket: its save node and file prefix stay.+ const { graphOfTask } = await import("./helpers/ticket-worker");+ const graph = await graphOfTask(t!);const save = Object.entries(graph).find(([, n]) => n.class_type === "SaveImage")!;let input: string | null = null;if (o.input) {@@ -190,7 +202,8 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {[save[0]]: { class_type: "SaveImage", inputs: { images: ["3", 0], filename_prefix: save[1].inputs.filename_prefix } },};const needs = { ...(JSON.parse(t!.needs_json ?? "{}") as object), files: [], packs: [], minVramBytes: 0 };- studio.db().prepare("UPDATE relay_tasks SET graph_json = ?, needs_json = ? WHERE id = ?").run(JSON.stringify(own), JSON.stringify(needs), t!.id);+ studio.db().prepare("UPDATE relay_tasks SET needs_json = ? WHERE id = ?").run(JSON.stringify(needs), t!.id);+ standInGraphs.set(id, own);return { id, task: t! };}@@ -330,6 +343,8 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {readGpu: async () => null,sleep: (ms: number) => sleep(Math.min(ms, 50)),log: (line: string) => void p.logs.push(line),+ composer,+ catalogVersion: program.catalogVersion,// The folders are looked at again on both clocks: a full rescan, and the check for model folders that were missing....(o.rescanMs && { rescanMs: o.rescanMs, modelsCheckMs: o.rescanMs }),...o.gpu,diff --git a/tests/worker-stamp.test.ts b/tests/worker-stamp.test.tsindex 56d18fc3..9893b12f 100644--- a/tests/worker-stamp.test.ts+++ b/tests/worker-stamp.test.ts@@ -30,7 +30,8 @@ function checkout() {/** A worker folder whose dist has every part, stamped with `stamp`. */function dist(stamp: string | null) {const dir = tempDir("fuobe-worker-dist-");- for (const f of ["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"]) fs.writeFileSync(path.join(dir, f), "{}");+ fs.mkdirSync(path.join(dir, "compose/lib"), { recursive: true });+ for (const f of ["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json", "catalog-version.json", "compose/lib/ticket-compose.mjs"]) fs.writeFileSync(path.join(dir, f), "{}");if (stamp !== null) fs.writeFileSync(path.join(dir, STAMP_FILE), JSON.stringify({ built: "scripts/build-worker.mjs", stamp }));return dir;}diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.tsnew file mode 100644index 00000000..6cf9c3e9--- /dev/null+++ b/tests/worker-tickets.test.ts@@ -0,0 +1,563 @@+/**+ * Job tickets and the PC's ceiling on the workers' line (src/server/computer/pool.ts) and in the worker program+ * (bin/lib/worker/run.mjs), against the studio's real routes and the worker's own stand-in ComfyUI (a process of its+ * own, behind the worker's guard). Never a real ComfyUI, never a GPU.+ *+ * - An account's task hands out its ticket, never a graph; the owner's own job keeps its graph.+ * - A ticket outside the PC's ceiling, or made for another catalog, is never claimed; the studio's allowed lanes only+ * narrow inside the ceiling; a worker built from another catalog says "update the worker" and still takes the+ * owner's own jobs.+ * - A ticket a worker refuses before running it costs the run nothing, and goes to another worker.+ * - The worker composes an account's ticket itself and renders it; a studio that sends a raw graph for an account's+ * task, or a job past the PC's ceiling, is refused and its ComfyUI never sees it.+ * - `fuobe worker setup` saves the ceiling, and a run of setup again changes it.+ */+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { worker as workerCommand } from "../bin/lib/worker/index.mjs";+import { 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-tickets-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+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 { comfyProvider } = await import("@/server/providers/comfyui");+const hosted = await import("@/server/hosted");+const { getModel } = await import("@/lib/catalog");+const { encodePng } = await import("@/lib/png-encode");+const { withoutSaveMetadata } = await import("@/lib/comfy-compose");+const { allLanes } = await import("@/lib/lanes");+const { loadIndex } = await import("@/server/gpu/index-file");+const { ComputerRunner } = await import("@/lib/computer-runner");+const composer = await import("@/lib/ticket-compose");++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", "ImageInvert", "SaveImage", "KSampler"]);+const VERSION = catalogVersion()!;+const OTHER = "e".repeat(64);+const realFetch = globalThis.fetch;+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++let routes: ComputerRoutes;+let accountId = "";+beforeAll(async () => {+ routes = await loadRoutes();+ setSetting("comfyWhere", "workers");+ auth.setPassword("install password");+ accountId = auth.createAccount("[email protected]", "long enough").id;+});+afterAll(() => {+ globalThis.__fuobeTestDiskFree = undefined;+ delete process.env.FUOBE_HOSTED_RUNS;+});+beforeEach(() => {+ resetRates();+ delete process.env.FUOBE_HOSTED_RUNS;+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+});++type W = { id: string; token: string };+type TaskRow = import("@/server/computer/tasks").TaskRow;+const row = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;+const LANE = pool.poolLane("selftest-image");++/** A worker the owner added and resumed, all day, allowed every lane, able to run every workflow. */+function addWorker(): W {+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);+ const lanes = allLanes(loadIndex(), sha);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });+ const workflows = (JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string }[] }).workflows.map((x) => x.id);+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ return w;+}++/** A worker's beat as the program sends it: its catalog version and its PC's ceiling. */+const beat = (w: W, o: { catalogVersion?: string | null; ceiling?: unknown } = {}) =>+ pool.workerBeat(+ workerRow(w),+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: o.catalogVersion === undefined ? VERSION : o.catalogVersion, ...(o.ceiling !== undefined && { ceiling: o.ceiling }) }),+ );+const claim = (w: W) => pool.workerClaim(workerRow(w), []);++let gens = 0;+function generation(account: string | null) {+ const gid = `tickets-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', 'oss-selftest-image', 'open', 'comfyui', 'edit', 'image', 'queued', ?, '[]', ?, ?)")+ .run(gid, JSON.stringify(account ? { account, place: "pool" } : {}), now, now);+ return gid;+}++/** A 1600 × 1200 picture (about 1.9 MP). */+const PICTURE = encodePng({ width: 1600, height: 1200, data: Buffer.alloc(1600 * 1200 * 4, 128) });++/**+ * An account's run of the self-test workflow (it inverts a picture), as the studio queues it for the workers: its+ * picture sent and its job submitted on this install's GPUs, which makes the task and its ticket.+ */+async function accountTask() {+ const gid = generation(accountId);+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const { picture, sent } = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(PICTURE, "image/png", "me.png", route))!;+ return { picture: name, sent: await comfyProvider.submit({ route, input: { images: [name], seed: 5 }, generationId: gid, model: getModel("oss-selftest-image") } as never) };+ });+ const id = String((sent.meta as { relay: string }).relay);+ return { id, gid, graph: withoutSaveMetadata(sent.payload as never), picture };+}++/** The owner's own job on the workers: a whole graph, in the owner's class. */+function ownerTask() {+ const gid = generation(null);+ const picture = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");+ const graph = { "1": { class_type: "LoadImage", inputs: { image: picture } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/owner-test" } } };+ const t = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId: "selftest-image", pool: pool.poolFields("selftest-image", { class: "owner" }) });+ return { id: t.id, gid, graph };+}++describe("the line hands out tickets inside each PC's ceiling", () => {+ it("an account's task carries its ticket and its limits, never a graph; the owner's own job keeps its graph", async () => {+ const w = addWorker();+ beat(w);+ const mine = await accountTask();+ expect(row(mine.id).graph_json).toBeNull();+ const got = claim(w)!;+ expect(got.id).toBe(mine.id);+ expect(got.graph).toBeUndefined();+ expect(got.class).toBe("free");+ expect(got.ticket).toMatchObject({ workflowId: "selftest-image", catalogVersion: VERSION, op: "edit", settings: { seed: 5 }, outputs: { count: 1, kind: "image" } });+ expect(got.ticket!.inputs).toEqual([expect.objectContaining({ slot: "images.0", name: mine.picture, kind: "image" })]);+ expect(got.ticket!.runLimitMs).toBe(got.runLimitMs);+ expect(got.ticket!.stallMs).toBe(got.stallMs);+ // Through JSON, the claim's way, the ticket composes the graph the studio built.+ const composed = await composer.composeTicket(+ { ticket: JSON.parse(JSON.stringify(got.ticket)), generationId: got.generationId, inputs: got.inputs },+ { catalog: { has: (id) => id === "selftest-image", get: (await import("@/server/providers/comfyui")).getWorkflow }, catalogVersion: VERSION },+ );+ expect(composed.ok && composed.graph).toEqual(mine.graph);+ tasks.endTask(mine.id, "canceled");+ const own = ownerTask();+ const theirs = claim(w)!;+ expect(theirs.id).toBe(own.id);+ expect(theirs.ticket).toBeUndefined();+ expect(theirs.graph).toEqual(own.graph);+ expect(theirs.class).toBe("owner");+ });++ it("a ticket outside the PC's ceiling is never claimed, and the studio's lanes only narrow inside it", async () => {+ const w = addWorker();+ const mine = await accountTask();+ const size = JSON.parse(row(mine.id).needs_json!).size as { megapixels: number };+ expect(size.megapixels).toBeGreaterThan(0);+ for (const ceiling of [{ maxMegapixels: size.megapixels / 2 }, { workflows: ["video-trim"] }, { lanes: ["0123456789ab"] }]) {+ const a = beat(w, { ceiling });+ expect(a.claimableNow, JSON.stringify(ceiling)).toBe(0);+ expect(claim(w), JSON.stringify(ceiling)).toBeNull();+ }+ // The owner allowed every lane; the PC allows one: its beat hears that one only.+ const narrowed = beat(w, { ceiling: { lanes: [LANE] } });+ expect(narrowed.worker.lanes.length).toBeGreaterThan(1);+ expect(narrowed.worker.lanesInside).toEqual([LANE]);+ expect(pool.workerView(workerRow(w)).ceiling).toEqual({ lanes: [LANE] });+ // Inside it: claimed.+ expect(beat(w, { ceiling: { maxMegapixels: size.megapixels * 2, workflows: ["selftest-image"], maxOutputs: 4 } }).claimableNow).toBe(1);+ expect(claim(w)?.id).toBe(mine.id);+ });++ it("a worker built from another catalog takes no ticket, says to update, and still takes the owner's own jobs", async () => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ const w = addWorker();+ const mine = await accountTask();+ beat(w, { catalogVersion: OTHER });+ expect(pool.workerState(workerRow(w)).state).toBe("update-worker");+ expect(pool.workerView(workerRow(w))).toMatchObject({ catalogVersion: OTHER, catalogCurrent: false, state: "update-worker" });+ expect(claim(w)).toBeNull();+ // Too old to say: the same.+ beat(w, { catalogVersion: null });+ expect(claim(w)).toBeNull();+ const own = ownerTask();+ expect(claim(w)?.id).toBe(own.id);+ tasks.endTask(own.id, "canceled");+ // Updated: it takes the ticket, and reads as ready.+ beat(w);+ expect(pool.workerState(workerRow(w)).state).toBe("idle");+ expect(claim(w)?.id).toBe(mine.id);+ // With hosted runs off, a worker's catalog never changes its state.+ delete process.env.FUOBE_HOSTED_RUNS;+ beat(w, { catalogVersion: OTHER });+ expect(pool.workerState(workerRow(w)).state).not.toBe("update-worker");+ });++ it("a ticket a worker refuses before running it costs nothing, and goes to another worker", async () => {+ const a = addWorker();+ const b = addWorker();+ beat(a);+ const mine = await accountTask();+ for (const why of ["update-worker", "outside-ceiling"] as const) {+ const got = claim(a)!;+ expect(got.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why }, () => ({ error: "unused" }));+ const back = row(mine.id);+ expect(back.state).toBe("waiting");+ expect(back.requeues).toBe(0);+ expect(back.claimed_at).toBeNull();+ // Never offered to that worker again.+ beat(a);+ expect(claim(a)).toBeNull();+ // Another worker takes it.+ beat(b);+ expect(claim(b)?.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why }, () => ({ error: "unused" }));+ expect(row(mine.id).requeues).toBe(0);+ db().prepare("UPDATE relay_tasks SET extra_json = NULL WHERE id = ?").run(mine.id);+ }+ // A ticket it can't use fails the run.+ beat(a);+ claim(a);+ tasks.report(row(mine.id), { event: "failed", reason: "bad-ticket" }, () => ({ error: "unused" }));+ expect(row(mine.id).state).toBe("failed");+ });++ it("a worker that refused a ticket is offered it again once its ceiling or its build changes", async () => {+ const a = addWorker();+ beat(a, { ceiling: { maxOutputs: 4 } });+ const mine = await accountTask();+ expect(claim(a)?.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why: "outside-ceiling" }, () => ({ error: "unused" }));+ // No worker ran it: it waits as a task no worker took, so its wait limit still holds.+ expect(row(mine.id).claimed_at).toBeNull();+ beat(a, { ceiling: { maxOutputs: 4 } });+ expect(claim(a)).toBeNull();+ beat(a, { ceiling: { maxOutputs: 8 } });+ expect(claim(a)?.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why: "update-worker" }, () => ({ error: "unused" }));+ beat(a, { ceiling: { maxOutputs: 8 } });+ expect(claim(a)).toBeNull();+ // Its catalog and its ceiling as they were when it refused: still not offered, whatever it said in between.+ beat(a, { catalogVersion: OTHER, ceiling: { maxOutputs: 8 } });+ beat(a, { ceiling: { maxOutputs: 8 } });+ expect(claim(a)).toBeNull();+ beat(a, { ceiling: { maxOutputs: 9 } });+ expect(claim(a)?.id).toBe(mine.id);+ });++ it("a task that a worker took before keeps that claim's time when another worker refuses its ticket", async () => {+ const a = addWorker();+ const b = addWorker();+ beat(a);+ beat(b, { ceiling: { maxOutputs: 4 } });+ const mine = await accountTask();+ expect(claim(a)?.id).toBe(mine.id);+ const first = row(mine.id).claimed_at;+ expect(first).toBeTruthy();+ // Its worker let it go (a pause): back in line at no cost.+ expect(pool.backInLine(row(mine.id), { blame: false })).toBe(true);+ expect(claim(b)?.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why: "outside-ceiling" }, () => ({ error: "unused" }));+ expect(row(mine.id)).toMatchObject({ state: "waiting", claimed_at: first, requeues: 0 });+ });++ it("a waiting task whose ticket was made for the catalog before an update gets its ticket made again, with its place kept", async () => {+ const { refreshTickets } = await import("@/server/computer/ticket-refresh");+ const w = addWorker();+ beat(w);+ const mine = await accountTask();+ const gone = await accountTask();+ const rankAt = row(mine.id).rank_at;+ // Both made before the update; one names a workflow the catalog no longer has.+ for (const [id, workflowId] of [+ [mine.id, "selftest-image"],+ [gone.id, "a-retired-workflow"],+ ]) {+ const ticket = { ...JSON.parse(row(id).ticket_json!), catalogVersion: OTHER, workflowId };+ const needs = { ...JSON.parse(row(id).needs_json!), catalogVersion: OTHER };+ db().prepare("UPDATE relay_tasks SET ticket_json = ?, needs_json = ?, extra_json = ? WHERE id = ?").run(JSON.stringify(ticket), JSON.stringify(needs), JSON.stringify({ refusedBy: ["someone:0000"] }), id);+ }+ expect(claim(w)).toBeNull();+ expect(await refreshTickets()).toEqual({ refreshed: 1, ended: 1 });+ const fresh = row(mine.id);+ expect(JSON.parse(fresh.ticket_json!)).toMatchObject({ catalogVersion: VERSION, workflowId: "selftest-image" });+ expect(JSON.parse(fresh.needs_json!).catalogVersion).toBe(VERSION);+ expect(JSON.parse(fresh.extra_json ?? "{}").refusedBy).toBeUndefined();+ expect(fresh.rank_at).toBe(rankAt);+ expect(row(gone.id)).toMatchObject({ state: "failed", error: pool.GAVE_BACK_WORDS });+ // Nothing left to do the second time.+ expect(await refreshTickets()).toEqual({ refreshed: 0, ended: 0 });+ expect(claim(w)?.id).toBe(mine.id);+ });+});++// ---------------------------------------------------------------------------+// The worker program++interface Studio {+ calls: string[];+ reports: Record<string, unknown>[];+ /** Change what the studio answers (a studio that does what it shouldn't). */+ rewrite: ((p: string, body: unknown) => unknown) | null;+ /** Change what the worker sends (before the studio reads it). */+ send: ((p: string, body: Record<string, unknown>) => Record<string, unknown>) | null;+}+const studio = (): Studio => ({ calls: [], reports: [], rewrite: null, send: null });++/** fetch for the worker: the studio's routes for SITE (through the test's rewrites), its own ComfyUI for the rest. */+function router(w: W, s: Studio) {+ const api = apiAs(routes, null);+ return async (url: string, init: RequestInit = {}) => {+ if (!String(url).startsWith(SITE)) return realFetch(url, init);+ const u = new URL(url);+ const p = u.pathname + u.search;+ s.calls.push(`${init.method ?? "GET"} ${u.pathname}`);+ if (p === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: [LANE], workflows: ["selftest-image"], missing: [] });+ let req = init;+ if (typeof init.body === "string" && init.body.startsWith("{")) {+ const body = JSON.parse(init.body) as Record<string, unknown>;+ if (p.endsWith("/report")) s.reports.push(body);+ if (s.send) req = { ...init, body: JSON.stringify(s.send(p, body)) };+ }+ expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);+ const res = await api(p, req);+ if (!s.rewrite || !res.ok || res.status === 204 || !(res.headers.get("content-type") ?? "").includes("json")) return res;+ return Response.json(s.rewrite(p, await res.json()), { status: res.status });+ };+}++interface Pc {+ home: string;+ workDir: string;+ comfyDir: string;+ countFile: string;+ graphFile: string;+ logs: string[];+}+function pc(): Pc {+ const base = tempDir("fuobe-ticket-pc-");+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), graphFile: path.join(base, "graphs.jsonl"), logs: [] as string[] };+ for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });+ return p;+}++const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];+afterEach(async () => {+ for (const r of running.splice(0)) {+ r.ctrl.abort();+ await r.done.catch(() => {});+ }+});++/** Start `fuobe worker run` in this process (its ComfyUI a stand-in process of its own). */+function start(w: W, s: Studio, p: Pc, o: { ceiling?: unknown; acceptGraphs?: boolean } = {}) {+ const ctrl = new AbortController();+ const cfg = {+ 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", "3", "--step-ms", "30", "--worker-guard", "1", "--count-file", p.countFile, "--graph-file", p.graphFile],+ comfyGuard: true,+ stallMin: 10,+ ffmpeg: null,+ ...(o.ceiling !== undefined && { ceiling: o.ceiling }),+ ...(o.acceptGraphs !== undefined && { acceptGraphs: o.acceptGraphs }),+ };+ const done = runWorker(cfg, {+ fetch: router(w, s),+ home: p.home,+ signal: ctrl.signal,+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },+ ComputerRunner,+ rules: RULES,+ pins: {},+ allowed: ALLOWED,+ readGpu: async () => null,+ readGpuGen: async () => "8.9",+ ffmpegVersion: async () => null,+ awake: { set: () => {} },+ sleep: (ms: number) => sleep(Math.min(ms, 50)),+ log: (line: string) => void p.logs.push(line),+ composer,+ catalogVersion: VERSION,+ allLanes,+ });+ const r = { ctrl, done };+ running.push(r);+ return r;+}++async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 100): 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 ended = (id: string) => until(() => ["done", "failed", "canceled"].includes(row(id).state) && row(id), 90_000);+const prompts = (p: Pc) => (fs.existsSync(p.countFile) ? fs.readFileSync(p.countFile, "utf8").trim().split("\n").filter(Boolean).length : 0);+const graphsSent = (p: Pc) => (fs.existsSync(p.graphFile) ? fs.readFileSync(p.graphFile, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as Record<string, unknown>) : []);++describe("the worker program composes tickets and keeps to its PC's ceiling", () => {+ it("composes an account's ticket itself, renders it, and says its catalog and ceiling in its beat", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const mine = await accountTask();+ start(w, s, p, { ceiling: { workflows: ["selftest-image"], maxMegapixels: 50 } });+ const t = await ended(mine.id);+ expect(t.state, t.error ?? "").toBe("done");+ expect(fs.readFileSync(tasks.outputFile(mine.id, 0)).length).toBeGreaterThan(0);+ // Its ComfyUI got the graph the studio would have built, composed on the worker.+ expect(prompts(p)).toBe(1);+ expect(graphsSent(p)[0]).toEqual(mine.graph);+ // The studio heard its catalog, its ceiling and its GPU's generation.+ await until(() => JSON.parse(workerRow(w).facts_json ?? "{}").gpuGen === "8.9", 30_000);+ expect(workerRow(w).catalog_version).toBe(VERSION);+ expect(JSON.parse(workerRow(w).ceiling_json!)).toEqual({ workflows: ["selftest-image"], maxMegapixels: 50 });+ });++ it("a studio that sends a raw graph for an account's task is refused, and its ComfyUI never sees it", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const mine = await accountTask();+ // The hacked studio: the account's task comes with a graph of its own making in place of the ticket.+ const evil = { "1": { class_type: "LoadImage", inputs: { image: mine.picture } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/evil" } } };+ s.rewrite = (q, body) => {+ if (q !== "/api/gpu/computer/claim") return body;+ const { task } = body as { task: Record<string, unknown> };+ const { ticket: _t, ...rest } = task;+ void _t;+ return { task: { ...rest, graph: evil } };+ };+ start(w, s, p);+ const t = await ended(mine.id);+ expect(t.state).toBe("failed");+ expect(s.reports).toContainEqual({ event: "failed", reason: "bad-ticket" });+ expect(prompts(p)).toBe(0);+ expect(p.logs.some((l) => /Starting its own ComfyUI/.test(l))).toBe(true);+ });++ it("with acceptGraphs off, the owner's own whole graph is refused too", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const own = ownerTask();+ start(w, s, p, { acceptGraphs: false });+ const t = await ended(own.id);+ expect(t.state).toBe("failed");+ expect(s.reports).toContainEqual({ event: "failed", reason: "bad-ticket" });+ expect(prompts(p)).toBe(0);+ });++ it("a job past the PC's ceiling is given back at no cost, even when the studio sends it anyway", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const mine = await accountTask();+ // The studio never hears the ceiling (a studio that ignores it would send the job all the same).+ s.send = (q, body) => {+ if (q !== "/api/gpu/computer/beat") return body;+ const { ceiling: _c, ...rest } = body;+ void _c;+ return rest;+ };+ start(w, s, p, { ceiling: { maxMegapixels: 0.0001 } });+ await until(() => s.reports.some((r) => r.event === "give-back"));+ expect(s.reports).toContainEqual({ event: "give-back", why: "outside-ceiling" });+ expect(prompts(p)).toBe(0);+ const back = row(mine.id);+ expect(back.state).toBe("waiting");+ expect(back.requeues).toBe(0);+ expect(p.logs.some((l) => /more than this PC runs/.test(l))).toBe(true);+ });++ it("a ticket for another catalog is given back, and the worker says to update", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const mine = await accountTask();+ // The studio hears its own version from the worker, but the worker's build composes for another one.+ s.send = (q, body) => (q === "/api/gpu/computer/beat" ? { ...body, catalogVersion: VERSION } : body);+ 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", "3", "--step-ms", "30", "--worker-guard", "1", "--count-file", p.countFile], comfyGuard: true, ffmpeg: null },+ { fetch: router(w, s), home: p.home, signal: ctrl.signal, requirements: { folders: [], files: {}, packs: {}, workflows: {} }, ComputerRunner, rules: RULES, pins: {}, allowed: ALLOWED, readGpu: async () => null, ffmpegVersion: async () => null, awake: { set: () => {} }, sleep: (ms: number) => sleep(Math.min(ms, 50)), log: (line: string) => void p.logs.push(line), composer, catalogVersion: OTHER, allLanes },+ );+ running.push({ ctrl, done });+ await until(() => s.reports.some((r) => r.event === "give-back"));+ expect(s.reports).toContainEqual({ event: "give-back", why: "update-worker" });+ expect(prompts(p)).toBe(0);+ expect(row(mine.id).requeues).toBe(0);+ expect(p.logs.some((l) => /update the worker/.test(l))).toBe(true);+ expect(p.logs.some((l) => /The studio's catalog is another than this worker's/.test(l))).toBe(true);+ });+});++describe("setup saves the PC's ceiling", () => {+ it("asks for the lanes or workflows and the sizes, and a run of setup again changes them", async () => {+ const home = tempDir("fuobe-ticket-setup-home-");+ const comfyDir = tempDir("fuobe-ticket-setup-comfy-");+ fs.writeFileSync(path.join(comfyDir, "main.py"), "");+ const out: string[] = [];+ const setup = async (ceiling: string[], graphs = "") => {+ const answers = ["https://studio.example", `fuobe_wkr_${"a".repeat(43)}`, comfyDir, path.join(comfyDir, "models"), path.join(tempDir("fuobe-ticket-setup-work-"), "w"), "-", "n", ...ceiling, graphs];+ const io = { env: { FUOBE_WORKER_HOME: home }, home, stdout: { write: (x: string) => void out.push(x) }, stderr: { write: (x: string) => void out.push(x) }, ask: async () => answers.shift() ?? "" };+ const code = await workerCommand(["setup"], io);+ return { code, saved: JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8")) as Record<string, unknown> };+ };+ const first = await setup(["selftest-image, video-trim", "4", "12", "2"]);+ expect(first.code).toBe(0);+ expect(first.saved.ceiling).toEqual({ workflows: ["selftest-image", "video-trim"], maxMegapixels: 4, maxSeconds: 12, maxOutputs: 2 });+ expect(first.saved.acceptGraphs).toBe(true);+ expect(out.join("")).toMatch(/This PC runs selftest-image, video-trim, pictures up to 4 MP, clips up to 12 s, 2 results a run/);+ // Again: the old answers are the defaults; "all" and 0 take the ceiling off, and "n" takes tickets only.+ const again = await setup(["all", "0", "0", "0"], "n");+ expect(again.saved.ceiling).toBeUndefined();+ expect(again.saved.acceptGraphs).toBe(false);+ // A name that isn't in the catalog: nothing changes.+ const bad = await setup(["no-such-workflow"]);+ expect(bad.code).toBe(2);+ expect(bad.saved.acceptGraphs).toBe(false);+ });++ it("reads its GPU's generation from nvidia-smi once, and an older nvidia-smi that can't say leaves it unknown", async () => {+ const { parseGpuGen, readGpuGen } = await import("../bin/lib/worker/gpu.mjs");+ const state = path.join(tempDir("fuobe-ticket-smi-"), "smi.json");+ const smi = [process.execPath, path.join(ROOT, "tests/helpers/fake-nvidia-smi.mjs"), state];+ fs.writeFileSync(state, JSON.stringify({ usedMb: 300, tempC: 40, computeCap: "12.0", apps: [] }));+ expect(await readGpuGen(smi)).toBe("12.0");+ fs.writeFileSync(state, JSON.stringify({ usedMb: 300, tempC: 40, apps: [] }));+ expect(await readGpuGen(smi)).toBeNull();+ expect(parseGpuGen("8.9\n")).toBe("8.9");+ expect(parseGpuGen("300, 45")).toBeNull();+ });+});diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsindex b76cd59b..ae5c5902 100644--- a/tests/worker-turns-run.test.ts+++ b/tests/worker-turns-run.test.ts@@ -66,6 +66,13 @@ function addWorker(): W {return w;}+/** A person's job comes as a job ticket: the worker's composer here gives its graph, by the run's id. */+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;/** A person's run for the workers, or (`owner`) one of the owner's own, which no turn is asked for. */function addTask(o: { owner?: boolean } = {}): string {@@ -75,10 +82,13 @@ function addTask(o: { owner?: boolean } = {}): string {.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: { "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" } } },+ graph,+ ...(!o.owner && { ticket: { inputs: [{ slot: "images.0", name: input }] } as never }),// A person's run (an account's): the studio counts it in the beat's claimableNow.pool: { pools: ["pool"], ...(!o.owner && { account: "turns-account" }), rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },}).id;@@ -203,6 +213,8 @@ function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { lockOwners?: sawake: { set: () => {} },sleep: (ms: number) => sleep(Math.min(ms, 50)),log: (line: string) => void p.logs.push(line),+ composer,+ catalogVersion: "a".repeat(64),gpuEveryMs: 200,turnGraceMs: 1500,...gpu,