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: finishing jobs stop with their run, CPU time is never GPU time, and job tickets only move forward
Adarshfe76dccb9ad3
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjsindex 3a9522e4..5fa6387b 100644--- a/bin/lib/worker/config.mjs+++ b/bin/lib/worker/config.mjs@@ -10,6 +10,13 @@ import path from "node:path";*/export const PROTOCOL = 3;+/**+ * The protocol this worker says it speaks: PROTOCOL, or 2 when it can't make pictures again (no sharp in its checkout).+ * The studio then sends it no job ticket (an account's run with a picture would only come back), and its owner's own jobs+ * go on as before.+ */+export const protocolOf = (canCleanPictures) => (canCleanPictures ? PROTOCOL : 2);+/** Where the worker keeps its settings: %LOCALAPPDATA%\FuobeWorker on Windows, ~/.config/fuobe-worker elsewhere. */export function workerHome(env = process.env, home = os.homedir()) {if (env.FUOBE_WORKER_HOME) return env.FUOBE_WORKER_HOME;diff --git a/bin/lib/worker/finish.mjs b/bin/lib/worker/finish.mjsindex d8a7068f..9b56a407 100644--- a/bin/lib/worker/finish.mjs+++ b/bin/lib/worker/finish.mjs@@ -105,6 +105,8 @@ export function finishers(o) {async function finish(t, inputs, { signal, progress }) {const kind = t.finish?.kind;if (!kinds.includes(kind)) return { refused: "finish-failed" };+ // Each script may run as long as the job's run limit (the studio's, in its claim); the runner stops the job there too.+ const timeoutMs = Number(t.runLimitMs) > 0 ? Number(t.runLimitMs) : 20 * 60_000;// Its own emptied folder: nothing of another job is beside it, and nothing of it stays.const dir = path.join(o.workDir, "finish", String(t.id).replace(/[^A-Za-z0-9_-]/g, "_"));fs.rmSync(dir, { recursive: true, force: true });@@ -117,7 +119,7 @@ export function finishers(o) {if (kind === "model3d") {const raw = put("raw.glb", inputs.model);const web = path.join(dir, "web.glb");- const r = await runScript(finishGlb, ["--in", raw, "--out", web, "--material", String(t.finish.settings.material ?? "auto"), "--limits", "account"], { cwd: dir, signal, env, timeoutMs: 5 * 60_000 });+ const r = await runScript(finishGlb, ["--in", raw, "--out", web, "--material", String(t.finish.settings.material ?? "auto"), "--limits", "account"], { cwd: dir, signal, env, timeoutMs });if (r.code === REFUSED) return { refused: "unsafe-model" };const stats = r.code === 0 && fs.existsSync(web) ? lastJson(r.stdout) : null;if (!stats) return { refused: "finish-failed" };@@ -131,7 +133,7 @@ export function finishers(o) {cwd: dir,signal,env,- timeoutMs: 10 * 60_000,+ timeoutMs,onLine: (line) => {const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());if (m) progress(0.3 + 0.7 * (Number(m[1]) / Number(m[2])));@@ -155,7 +157,7 @@ export function finishers(o) {cwd: dir,signal,env,- timeoutMs: 10 * 60_000,+ timeoutMs,onLine: (line) => {const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());if (m) progress(Number(m[1]) / Number(m[2]));diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 8ebd00d3..cde179d5 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -24,7 +24,7 @@ import { fileURLToPath } from "node:url";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 { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";import { GpuWatch, othersOf, readGpu, readGpuGen } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";@@ -72,6 +72,24 @@ export const MODELS_CHECK_MS = 60_000;*/export const SLEPT_MS = 60_000;+/**+ * After a claim that found no job for a slot, that slot asks again only this long after (ms): two idle slots never ask+ * more often than the studio's limit allows.+ */+export const IDLE_CLAIM_MS = 3000;++/**+ * The shortest wait after a claim that found nothing while the last beat said a person's job waits that this worker may+ * take now (ms): it asks again soon, but never once a second for as long as that word lasts (a beat comes every 10 s).+ */+export const CLAIM_GAP_MS = 1500;++/**+ * May a slot claim now: `missedAt` is when its last claim found nothing (-Infinity after a job, or before any claim). Not+ * before `idleMs` has gone by since, or CLAIM_GAP_MS while a person's job waits for it (`claimable`).+ */+export const claimDue = (t, missedAt, claimable = 0, idleMs = IDLE_CLAIM_MS) => t - missedAt >= (claimable > 0 ? Math.min(CLAIM_GAP_MS, idleMs) : idleMs);+/** A worker token as the studio makes them. */const NEXT_TOKEN = /^fuobe_wkr_[A-Za-z0-9_-]{43}$/;@@ -160,8 +178,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, readGpuGen, and for job tickets: composer (src/lib/ticket-compose.ts- * as built), catalogVersion, catalogDir, allLanes }.+ * options), readCounters, readListeners, gpuEveryMs, readGpuGen, idleClaimMs (IDLE_CLAIM_MS), canCleanPictures, 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@@ -363,7 +381,7 @@ async function work(saved, deps, owner) {// Pictures of an account's job are made again here: without the tool for it (pnpm install in its checkout), such a// job goes back to the line for another worker.const pictureTool = deps.canCleanPictures ?? canCleanPictures();- if (!pictureTool) log("It can't make pictures again here (run pnpm install in its checkout): an account's job with a picture goes back to the line.");+ if (!pictureTool) log("It can't make pictures again here (run pnpm install in its checkout): it takes only the owner's own jobs until it can.");/*** An input for its ComfyUI: read from the studio once, kept by its SHA-256 (in the slot's own `cacheDir`), a clip or* sound made again by ffmpeg, and a picture of an account's job ticket or of a finishing job made again from its pixels.@@ -520,7 +538,8 @@ async function work(saved, deps, owner) {beatExtra: () => {sleptSent = slept;return {- protocol: PROTOCOL,+ // Without its picture tool, it takes no job ticket: the studio sends it the owner's own jobs only.+ protocol: protocolOf(pictureTool),version: VERSION,// It saves the next token a beat answer gives it (never one for a token from the environment).canRotateToken: canRotate,@@ -566,6 +585,7 @@ async function work(saved, deps, owner) {hold,input: takeInput,graphs: cfg.acceptGraphs !== false,+ olderStudio: () => !!answer && typeof answer.worker?.catalogVersion !== "string",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,@@ -630,6 +650,7 @@ async function work(saved, deps, owner) {hold: cpuHold,input: takeInputIn(cpuCacheDir),graphs: cfg.acceptGraphs !== false,+ olderStudio: () => !!answer && typeof answer.worker?.catalogVersion !== "string",inside: (t) => graphInside(ceiling, t),stallMs: 10 * 60_000,stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,@@ -654,10 +675,17 @@ async function work(saved, deps, owner) {{ device: "worker-cpu", port: 8191, clientId: crypto.randomBytes(8).toString("hex"), slot: "cpu" },);}+ // When each slot's last claim found nothing (claimDue): it asks again a little later.+ const idleClaimMs = deps.idleClaimMs ?? IDLE_CLAIM_MS;+ let gpuMissedAt = -Infinity;+ let cpuMissedAt = -Infinity;const takeCpu = () => {busyCpu = true;cpuJob = cpuRunner.claimAndRun()+ .then((had) => {+ cpuMissedAt = had ? -Infinity : now();+ }).catch((e) => log(`A CPU slot job stopped: ${e.message}`)).finally(() => {busyCpu = false;@@ -691,6 +719,9 @@ async function work(saved, deps, owner) {jobUsesGpu = !o?.onlyHeld;job = runner.claimAndRun(o)+ .then((had) => {+ if (!o?.onlyHeld) gpuMissedAt = had ? -Infinity : now();+ }).catch((e) => log(`A job stopped: ${e.message}`)).finally(() => {busyJob = false;@@ -887,7 +918,7 @@ async function work(saved, deps, owner) {.finally(() => (starting = null));}}- if (comfy.ready && answer?.runner && !busyJob && !holdBack && !heldFirst) take();+ if (comfy.ready && answer?.runner && !busyJob && !holdBack && !heldFirst && claimDue(t, gpuMissedAt, siteOf(answer).claimable ?? 0, idleClaimMs)) take();} else if (comfy.alive() && (stopNow || !busyJob)) {log("Stopping its own ComfyUI (paused).");await comfy.stop();@@ -907,7 +938,7 @@ async function work(saved, deps, owner) {}).finally(() => (cpuStarting = null));}- if (cpuComfy.ready && answer?.runner && !busyCpu) takeCpu();+ if (cpuComfy.ready && answer?.runner && !busyCpu && claimDue(t, cpuMissedAt, 0, idleClaimMs)) takeCpu();} else if (cpuComfy.alive() && (!busyCpu || pause.why === "here-now" || answer?.worker?.pauseNow)) {await cpuComfy.stop();}diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 768ade2e..548a022c 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -355,7 +355,8 @@ run limit and stall limit, and the sending clock, end an attempt long before thait shows no progress from the attempt before.A job of the owner's that no worker can run is refused when it is sent, as an account's run is. Allow its lane for a-worker that has its model files first. The same check keeps an account's run out of the line when no worker could ever+worker that has its model files first. A job larger than every worker's PC may ever run (its ceiling's largest+picture, longest clip or most results) is refused when it is sent too, the owner's and an account's alike. The same check keeps an account's run out of the line when no worker could evertake it: a worker must be allowed the lane, its last list of files must have the workflow's files and node packs, andit must have the VRAM.@@ -409,8 +410,18 @@ can't use at all fails the run, and the person who started it sees one plain senAfter an update of the studio that changes the catalog version, each job still waiting in line gets its ticket madeagain 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.+its settings and files are checked again. The files the graph makes itself (a palette swatch, say) are made again too,+and staged in place of the old ones when they come out different. The job's lane and what it needs come from the new+catalog. 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.++Tickets only move forward. While a deploy's old and new app processes share the database, only the process that+started last makes tickets again, and only it ever ends a run for this. The other process leaves every ticket as it+is. A process that has said nothing for 5 minutes no longer counts.++An account's run needs a worker that takes this studio's job tickets now: protocol 3 or newer, built for this studio's+catalog. While every worker that could run it is built from the catalog before the studio's update, Run is off and+says the studio is busy, and the place in line counts no workers. The owner's own jobs still go to those workers.### What the worker checks itself@@ -466,8 +477,11 @@ its folders, and its copies of the inputs. At start, and whenever it stops, it estarts a job that its ComfyUI did not have last, it clears its ComfyUI the same way.The owner's pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). An account's-pictures go to the worker as they came, and the worker makes each one again from its pixels before its ComfyUI or a-finishing job reads it (see "Pictures of an account's run"). The studio never decodes them. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;+pictures go to the worker without being decoded, and the worker makes each one again from its pixels before its+ComfyUI or a finishing job reads it (see "Pictures of an account's run"). Before they leave, the studio blanks what+they carry besides their pixels, in place: EXIF and GPS, XMP, comments and text chunks. A JPEG keeps only its+orientation. A kind of picture that the studio can't blank that way (a GIF, say) is made again from its pixels on the+studio instead. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;`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@@ -506,9 +520,9 @@ else of the file stays: no EXIF, no GPS, no XMP, no comment. If the picture can'words. The studio sizes the picture as it shows (turned by its orientation), so a clip in the picture's own shape keepsthat shape.-The worker needs sharp for this, which `pnpm install` puts in its checkout. Without it, the worker logs so, and an-account's job with a picture goes back to the line for another worker. Only a worker of protocol 3 or newer takes an-account's job ticket. While accounts' runs may come to the install's GPUs, an older one reads **Update the worker**.+The worker needs sharp for this, which `pnpm install` puts in its checkout. Without it, the worker logs so and says+protocol 2 in its beat, so the studio sends it only the owner's own jobs. Only a worker of protocol 3 or newer takes an+account's job ticket or a finishing job. While accounts' runs may come to the install's GPUs, an older one reads **Update the worker**.### The CPU slot@@ -539,9 +553,22 @@ On the studio, a worker holds at most one GPU job and one CPU task. Each slot clclaim), so a CPU task never waits for the GPU's job, nor holds it up. The line counts each slot apart: a CPU task neverstands ahead of a GPU job on a worker with a CPU slot, and the place and the wait say so. A worker with no CPU slot takeslight CPU work in its GPU's slot, as before, and no finishing job. A finishing job goes only to a CPU slot that runs its-kind, in the run's class and at the run's place in line. A CPU task's run limit is its lane's run ceiling, at most 20-minutes. Another program on the GPU stops only the GPU's job; a pause now by hand stops both. A 3D run of an account on-the install's GPUs is taken only while a worker's CPU slot runs the 3D finish.+kind, in the run's class and at the run's place in line. Light CPU work has its lane's run limits in either slot. A+finishing job's run limit is its lane's run ceiling, which the owner sets in the queue settings. Another program on the+GPU stops only the GPU's job; a pause now by hand stops both. A 3D run of an account on the install's GPUs is taken+only while a worker heard from in the last few minutes, built for this studio's catalog, has a CPU slot that runs the+3D finish.++A finishing job is queued once for its run (and step), even when two app processes ask at the same time, and its+results are stored once. It waits for a CPU slot as long as its run may wait in line. If no CPU slot takes it by then,+a 3D model keeps its raw GLB and a camera path's step ends with one plain sentence. While it waits, the run's place in+line is the finishing job's. When the run is canceled or deleted, its finishing jobs end too: one in line at once,+with its files, and one that a CPU slot runs at its next progress report (the worker sends one at least every 10+seconds). A 3D model finished this way waits for the output check when the run asked for one, as any run's outputs do.+The time a CPU task runs is never counted as GPU time.++Each slot claims on its own count (60 claims a minute each). After a claim that found nothing, a slot asks again 3+seconds later, or 1.5 seconds later while the beat says that a person's job waits for it.### Live previews@@ -676,7 +703,9 @@ its target), at most once an hour each.- `POST /api/gpu/computer/claim`: the browser's claimed task plus`{ 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`.+ the only kind that comes with a graph. See "The run limit" above for `runLimitMs`. A worker treats a graph that+ names no class as the owner's own job only while the studio's beat answer names no catalog version (a studio older+ than job tickets, which sends no account's run to workers).`stallMs` is how long the job may go with no progress before the worker gives it back (see "The stall limit"). Aworker ignores a `stallMs` under one minute, and uses its own 10 minutes then.A worker's CPU slot sends `slot: "cpu"` and gets only work for that slot, with `slot: "cpu"` on the task. A@@ -687,17 +716,22 @@ its target), at most once an hour each.- Reports, inputs and results work as they do for the browser, with these additions:- `finished`, and the last `passes` report, carry `execMs` (the time that its ComfyUI spent executing the job, fromComfyUI's own timestamps: no waits, no uploads) and `device` (the GPU's name). The workers' log keeps both- (`GET /api/admin/workers/jobs`), and the billing service gets them as `gpuMs` and `device`. A job that ran more+ (`GET /api/admin/workers/jobs`), and the billing service gets them as `gpuMs` and `device`. For a CPU task+ (light CPU work, a finishing job), neither is kept: its time never counts as the run's GPU time, nor in a lane's+ typical time. A job that ran morethan once counts once: the attempt whose result was kept. The studio keeps at most the run ceiling of the job's lane,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 andcounts 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.+ or `outside-ceiling` (more than its PC allows), that worker is not offered the job again until its build or its+ ceiling changes. Refused on the claim that took it from the line, before anything was sent, it costs no attempt+ and waits as a job no worker took (its wait limit holds, unless a worker ran it before). Refused later on (a worker+ that started again after an update and took its own job back), it counts as an attempt, and the job keeps its+ claim's time.- `running` may carry `preview`: a JPEG as base64, at most 64 KB, at most one every 2 seconds (see "Live- previews"). A progress report with a preview may weigh up to 256 KB; any other stays under the small limit.+ previews"). A progress report with a preview may weigh up to about 91 KB (the preview as base64 and a few KB+ more); any other stays under the small limit.- `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), `input-unreadable` (ffmpeg could not read a clip or asound), `bad-ticket` (a ticket it can't use, or a graph where a ticket belongs), `unsafe-model` (a 3D model thatdiff --git a/src/app/api/gpu/computer/claim/route.ts b/src/app/api/gpu/computer/claim/route.tsindex 10bb89db..9725a2b4 100644--- a/src/app/api/gpu/computer/claim/route.ts+++ b/src/app/api/gpu/computer/claim/route.ts@@ -12,9 +12,10 @@ import { refreshTicketsBeforeClaim } from "@/server/computer/ticket-refresh";export async function POST(request: Request) {const principal = principalOf(request);if (principal instanceof Response) return principal;- const limited = rateOf(callerKey(request, principal), "claim", 60);- if (limited) return limited;const body = (await request.json().catch(() => null)) as { device?: unknown; running?: unknown; slot?: unknown } | null;+ // Each of a worker's slots claims for itself, each counted on its own: an idle CPU slot never uses up its GPU's claims.+ const limited = rateOf(callerKey(request, principal), body?.slot === "cpu" ? "claim-cpu" : "claim", 60);+ if (limited) return limited;const running = Array.isArray(body?.running) ? body.running.filter((x): x is string => typeof x === "string").slice(0, 32) : [];try {const worker = requestWorker(request);diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.tsindex 41a32020..b6178481 100644--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts@@ -1,4 +1,4 @@-import { GIVE_BACK, previewOf, RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";+import { GIVE_BACK, PREVIEW_LIMITS, previewOf, RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";import { noteFinished } from "@/server/computer/bench";@@ -15,8 +15,11 @@ const AT_ONCE = { person: 2, all: 16 };const LARGE_BYTES = 64 * 1024;/** A worker's: its progress report with a live preview stays under it. */const LARGE_BYTES_WORKER = 128 * 1024;-/** The most a progress report with a worker's live preview may weigh (its preview is kept only up to 64 KB). */-const RUNNING_BYTES = 256 * 1024;+/**+ * The most a progress report with a worker's live preview may weigh: its preview (a JPEG of at most 64 KB, as base64)+ * and a few KB for the rest, about 91 KB in all.+ */+const RUNNING_BYTES = Math.ceil(PREVIEW_LIMITS.maxBytes / 3) * 4 + 4 * 1024;/** The event as the tab sent it, with only the fields each one has, or null. */function eventOf(b: Record<string, unknown>): ReportEvent | null {diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex aaf520e9..ba487687 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -8,7 +8,7 @@* a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.*/import { isGuard } from "./comfy-guard";-import { finishProblem, type FinishResult, type FinishStats } from "./finish-ticket";+import { FINISH_RUN_MS, finishProblem, type FinishResult, type FinishStats } from "./finish-ticket";import { fetchWithin } from "./fetch-within";import { parseComfyBinary, parseComfyText } from "./comfy-ws";import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";@@ -176,6 +176,11 @@ export interface WorkerHooks {* job is refused whatever this says: an account's run comes as a ticket.*/graphs?: boolean;+ /**+ * The studio is older than job tickets (its last beat answer named no catalog version): its claims name no class, and+ * every graph it sends is the owner's own job (it sends no account's run to the workers).+ */+ olderStudio?(): 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. */@@ -282,6 +287,8 @@ export const MIN_RUN_LIMIT_MS = 10 * 60_000;export const MIN_STALL_MS = 60_000;const PROGRESS_EVERY_MS = 500;+/** A finishing job tells the studio it still runs at least this often (and hears a stop in the answer). */+const FINISH_BEAT_MS = 10_000;const POLL_MS = 1000;/** How often a ComfyUI that stopped answering is looked for on the other ports. */const FIND_EVERY_MS = 20_000;@@ -842,28 +849,51 @@ export class ComputerRunner {this.job(t, { phase: "running", value: 0, max: 100 });// Its run limit: past it, the job goes back in line (the next try has the whole limit again).const ctrl = new AbortController();- const limit = t.runLimitMs && t.runLimitMs > 0 ? t.runLimitMs : 20 * 60_000;+ const limit = t.runLimitMs && t.runLimitMs > 0 ? t.runLimitMs : FINISH_RUN_MS;const started = this.now();let timedOut = false;const timer = setTimeout(() => {timedOut = true;ctrl.abort();}, limit);+ // A stop from the studio (the run was canceled or deleted): the answer to a progress report says so, or the studio+ // no longer has the job. Its processes stop at once. A progress report goes at least every FINISH_BEAT_MS, so a+ // stop is heard even while a step of it says nothing for minutes.+ let stopped = false;+ const stopNow = () => {+ stopped = true;+ ctrl.abort();+ };let lastAt = 0;+ let value = 0;+ const tell = () => {+ if (stopped) return;+ lastAt = this.now();+ void this.report(t, { event: "running", value, max: 100 }).then(+ (a) => {+ if (a.stop) stopNow();+ },+ (e) => {+ if (e instanceof Stopped) stopNow();+ },+ );+ };const progress = (fraction: number) => {- const value = Math.max(0, Math.min(99, Math.round(fraction * 100)));+ value = Math.max(0, Math.min(99, Math.round(fraction * 100)));this.job(t, { phase: "running", value, max: 100 });- if (this.now() - lastAt < PROGRESS_EVERY_MS * 4) return;- lastAt = this.now();- void this.report(t, { event: "running", value, max: 100 }).catch(() => null);+ if (this.now() - lastAt >= PROGRESS_EVERY_MS * 4) tell();};+ const beat = setInterval(() => {+ if (this.now() - lastAt >= FINISH_BEAT_MS) tell();+ }, FINISH_BEAT_MS);let made: FinishMade | { refused: "unsafe-model" | "finish-failed" };try {made = await this.deps.finish(t, inputs, { signal: ctrl.signal, progress }).catch((): { refused: "finish-failed" } => ({ refused: "finish-failed" }));} finally {clearTimeout(timer);+ clearInterval(beat);}- if (!this.alive) throw new Stopped();+ if (!this.alive || stopped) throw new Stopped();if (timedOut) {await this.giveBack(t, "run-limit");return this.job(t, { phase: "failed" });@@ -920,8 +950,10 @@ export class ComputerRunner {return null;}if (!t.graph || typeof t.graph !== "object") return "bad-ticket";- // A studio names the owner's own job "owner"; a graph for any other job, or for one that names no class, is refused.- if (worker && (t.class !== "owner" || worker.graphs === false)) return "bad-ticket";+ // A studio names the owner's own job "owner"; a graph for any other job is refused, and so is one that names no class,+ // unless the studio is older than job tickets (its every graph job is the owner's own, and names no class).+ const cls = t.class ?? (worker?.olderStudio?.() ? "owner" : undefined);+ if (worker && (cls !== "owner" || worker.graphs === false)) return "bad-ticket";if (worker?.inside && !worker.inside(t)) return "outside-ceiling";return null;}diff --git a/src/lib/finish-ticket.ts b/src/lib/finish-ticket.tsindex 810bf063..5e5a2b43 100644--- a/src/lib/finish-ticket.ts+++ b/src/lib/finish-ticket.ts@@ -59,7 +59,10 @@ export const FINISH_FILES: Record<FinishKind, Record<string, { kind: "model3d" |/** A path's frames and frame rate: at most this many, and this fast. */export const PATH_LIMITS = { maxFrames: 241, maxFps: 60, maxKeys: 64 };-/** The longest a finish may run on a worker (its CPU slot's run limit for a finish). */+/**+ * The longest a finish runs on a worker whose claim names no run limit. The studio's claim names one: its lane's run+ * ceiling (queue-settings.ts, the owner's to set).+ */export const FINISH_RUN_MS = 20 * 60_000;const SHA = /^[0-9a-f]{64}$/;diff --git a/src/lib/ticket-compose.ts b/src/lib/ticket-compose.tsindex ec805653..ff8119f6 100644--- a/src/lib/ticket-compose.ts+++ b/src/lib/ticket-compose.ts@@ -160,17 +160,25 @@ export const catalogKnows = (catalog: ComposeCatalog, id: string) => catalog.has* The worker's side: check the ticket (its catalog version, its settings, its inputs against the files the job sends,* the PC's ceiling), then compose the graph with the composer and the worker's own catalog and facts. The files the* composer makes itself (made.<i>) are made here again: their copies on the studio are never read.+ *+ * `remake`: the studio's side when it makes a waiting ticket again for its catalog after an update (ticket-refresh.ts):+ * the files the graph makes may come out other than the ticket's (the composer that makes them changed), so they are+ * given back as they came out, for the studio to stage in place of the old ones, never checked against them.*/export async function composeTicket(job: { ticket: unknown; generationId: string; inputs: { name: string; sha256: string }[] },- env: { catalog: ComposeCatalog; catalogVersion: string; ceiling?: Ceiling | null; laneOf?: (workflowId: string) => string | null; facts?: WorkerFacts },+ env: { catalog: ComposeCatalog; catalogVersion: string; ceiling?: Ceiling | null; laneOf?: (workflowId: string) => string | null; facts?: WorkerFacts; remake?: boolean },): Promise<TicketOutcome> {if (!GENERATION_ID.test(String(job.generationId))) return { ok: false, reason: "bad-ticket", detail: "not a run id" };const refused = ticketProblem(job.ticket, { catalogVersion: env.catalogVersion, known: (id) => catalogKnows(env.catalog, id), inputs: job.inputs });if (refused) return { ok: false, ...refused };const t = job.ticket as JobTicket;const lane = (id: string) => env.laneOf?.(id) ?? null;- const before = ceilingProblem(env.ceiling, { workflowId: t.workflowId, lane: lane(t.workflowId), size: t.size });+ // A workflow that picks its graph at run time (`video-concat-{n}`) has no lane or name in the ceiling until it is+ // composed: before, only its sizes are checked; after, the graph it came out as, as the studio checked it.+ const templated = t.workflowId.includes("{");+ const ceiling = templated && env.ceiling ? { ...env.ceiling, lanes: undefined, workflows: undefined } : env.ceiling;+ const before = ceilingProblem(ceiling, { workflowId: templated ? null : t.workflowId, lane: templated ? null : lane(t.workflowId), size: t.size });if (before) return { ok: false, reason: "outside-ceiling", detail: before };// The request, with each file in its slot.const input = { ...t.settings } as GenInput & Record<string, unknown>;@@ -201,9 +209,10 @@ export async function composeTicket(accountOnInstall: true,made: async (data, contentType) => {const slot = made[madeHere.length];- if (!slot) throw new ComposeError("The ticket has no place for a file the graph makes");- madeHere.push({ name: slot.name, data: Buffer.from(data), contentType });- return slot.name;+ if (!slot && !env.remake) throw new ComposeError("The ticket has no place for a file the graph makes");+ const name = slot?.name ?? `made-${madeHere.length}`;+ madeHere.push({ name, data: Buffer.from(data), contentType });+ return name;},media: (name) => {const m = facts.get(name);@@ -216,10 +225,10 @@ export async function composeTicket(reuseModels: async () => f.reuseModels,idolPack: async () => f.idolPack,});- if (madeHere.length !== made.length) return { ok: false, reason: "bad-ticket", detail: "the ticket names files the graph doesn't make" };+ if (!env.remake && madeHere.length !== made.length) return { ok: false, reason: "bad-ticket", detail: "the ticket names files the graph doesn't make" };// A file made here is the studio's to the byte, or the ticket wasn't made for this graph.for (const [i, m] of madeHere.entries()) {- if (crypto.createHash("sha256").update(m.data).digest("hex") !== made[i].sha256) return { ok: false, reason: "bad-ticket", detail: "a file the graph makes isn't the ticket's" };+ if (!env.remake && crypto.createHash("sha256").update(m.data).digest("hex") !== made[i].sha256) return { ok: false, reason: "bad-ticket", detail: "a file the graph makes isn't the ticket's" };}const after = ceilingProblem(env.ceiling, { workflowId: out.manifest.id, lane: lane(out.manifest.id), size: out.size });if (after) return { ok: false, reason: "outside-ceiling", detail: after };diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex 28e4c4e6..582c283d 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -6,12 +6,13 @@ import { FINISH_FILES, FINISH_VERSION, finishProblem, PATH_LIMITS, type FinishKiimport type { HistoryEntryLike, WantedFile } from "@/lib/relay";import { accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom } from "../account-files";import { db } from "../db";-import { accountFinishProblem, MODEL_FINISH_VERSION, modelToFinish, OWN_ORBIT, withTurntable } from "../model3d-finish";+import { pictureWithoutMetadata } from "../media-clean";+import { ACCOUNT_TURNTABLE, accountFinishProblem, MODEL_FINISH_VERSION, modelToFinish, OWN_ORBIT, withTurntable } from "../model3d-finish";import { getSetting } from "../settings";import { absolutePath, deleteAsset, getAsset, readRef, saveFile, type Asset } from "../storage";import { tenantAccount } from "../tenant";-import { cpuSlotOf, poolWaitMs } from "./pool";-import { createTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type TaskRow } from "./tasks";+import { cpuSlotOf, poolWaitMs, RETRY_WINDOW_MS, ticketReady } from "./pool";+import { createTask, endTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type TaskRow } from "./tasks";import type { WorkerRow } from "./workers";/**@@ -28,11 +29,18 @@ import type { WorkerRow } from "./workers";* it. The owner's own runs, and runs on an account's own GPU or key, keep this server's finish, as before.*/-/** The finishing jobs a worker's CPU slot runs (any pool worker not revoked, paused or not: a run then waits in line). */-export function workersFinish(kind: FinishKind): boolean {+/**+ * Does a worker's CPU slot run this kind of finishing job: a pool worker not revoked, heard from in the last few minutes+ * (paused or not: a run then waits in line), whose program takes this studio's job tickets (ticketReady), and whose last+ * beat said its CPU slot runs that kind. A worker gone quiet for longer, or built from another catalog, counts for none:+ * a run is then never queued for a finish nothing would take.+ */+export function workersFinish(kind: FinishKind, now = Date.now()): boolean {if (getSetting("comfyWhere") !== "workers") return false;- const rows = db().prepare("SELECT cpu_slot_json FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND pool = 'pool' AND cpu_slot_json IS NOT NULL").all() as Pick<WorkerRow, "cpu_slot_json">[];- return rows.some((w) => !!cpuSlotOf(w)?.finishes.includes(kind));+ const rows = db()+ .prepare("SELECT cpu_slot_json, protocol, catalog_version FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND pool = 'pool' AND cpu_slot_json IS NOT NULL AND seen_at > ?")+ .all(now - RETRY_WINDOW_MS) as Pick<WorkerRow, "cpu_slot_json" | "protocol" | "catalog_version">[];+ return rows.some((w) => ticketReady(w) && !!cpuSlotOf(w)?.finishes.includes(kind));}/** A finishing job's ticket as its task keeps it, or null. */@@ -48,10 +56,22 @@ export function finishTask(generationId: string, kind: FinishKind, step = 0): Taconst runTask = (generationId: string) =>db().prepare("SELECT class, rank_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND finish_json IS NULL ORDER BY created_at DESC LIMIT 1").get(generationId) as Pick<TaskRow, "class" | "rank_at"> | undefined;+/** The wait the run was stamped with (the billing service's limit), else this install's (FUOBE_POOL_WAIT_MIN). */+function runWaitMs(generationId: string): number {+ const r = db().prepare("SELECT json_extract(request_json, '$.waitMs') AS w FROM generations WHERE id = ?").get(generationId) as { w: unknown } | undefined;+ const w = Number(r?.w);+ return Number.isFinite(w) && w > 0 ? w : poolWaitMs();+}+/**- * Queue a finishing job for an account's run: its files staged as the account's, its ticket checked as the worker will- * check it, in the run's class and at the run's place in line (a job no worker takes within the wait limit fails, not- * charged). Returns the task's id.+ * Queue a finishing job for an account's run: its files staged as the account's (a picture with what it carries besides+ * its pixels blanked, as for a run's job), its ticket checked as the worker will check it, in the run's class and at the+ * run's place in line. It waits for a worker's CPU slot as long as the run was allowed to wait in line (its stamped wait,+ * else this install's): a job no CPU slot took by then fails, and the run ends without what it would have made (a 3D+ * model keeps its raw GLB; a camera path's step says one plain sentence). Once a CPU slot took it, it waits in its place+ * after any recovery, as every job does. Once a run (and step): while a job of this kind for it is in line, running or+ * done, its id comes back and nothing new is queued, in one locked step even while another app process (a deploy's+ * overlap) asks too. Returns the task's id.*/export function queueFinish(o: {kind: FinishKind;@@ -62,8 +82,16 @@ export function queueFinish(o: {step?: number;}): string {const principal = `acct:${o.account}` as const;+ const queued = () => {+ const had = finishTask(o.generationId, o.kind, o.step ?? 0);+ return had && had.state !== "canceled" ? had.id : null;+ };+ const was = queued();+ if (was) return was;const inputs = o.inputs.map((i) => {- const name = stageInput(principal, i.data, i.contentType, i.name);+ const data = i.contentType.startsWith("image/") ? pictureWithoutMetadata(i.data, i.contentType) : i.data;+ if (!data) throw new Error("This run couldn't finish.");+ const name = stageInput(principal, data, i.contentType, i.name);return { slot: i.slot, name, sha256: stagedInput(principal, name)!.sha256 };});const ticket: FinishTicket = { v: FINISH_VERSION, kind: o.kind, settings: o.settings, inputs };@@ -73,28 +101,36 @@ export function queueFinish(o: {console.warn(`[fuobe] A finishing job for ${o.generationId} wasn't queued: ${problem}.`);throw new Error("This run couldn't finish.");}- const run = runTask(o.generationId);- const now = Date.now();- const t = createTask({- principal,- generationId: o.generationId,- graph: {},- finish: ticket,- workflowId: `finish-${o.kind}`,- made: o.kind === "model3d" ? "model3d" : "video",- ...(o.step !== undefined && { extra: { step: o.step } }),- pool: {- pools: ["pool"],- account: o.account,- class: run?.class === "paid" ? "paid" : "free",- rankAt: run?.rank_at ?? now,- lane: "small",- needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },- notAfter: now + poolWaitMs(),- slot: "cpu",- },- });- return t.id;+ // Looked at again with the write lock: another process that queued it meanwhile wins (the inputs staged here go with+ // the next sweep of staged files that no task took).+ return db()+ .transaction((): string => {+ const again = queued();+ if (again) return again;+ const run = runTask(o.generationId);+ const now = Date.now();+ const t = createTask({+ principal,+ generationId: o.generationId,+ graph: {},+ finish: ticket,+ workflowId: `finish-${o.kind}`,+ made: o.kind === "model3d" ? "model3d" : "video",+ ...(o.step !== undefined && { extra: { step: o.step } }),+ pool: {+ pools: ["pool"],+ account: o.account,+ class: run?.class === "paid" ? "paid" : "free",+ rankAt: run?.rank_at ?? now,+ lane: "small",+ needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },+ notAfter: now + runWaitMs(o.generationId),+ slot: "cpu",+ },+ });+ return t.id;+ })+ .immediate();}/**@@ -126,6 +162,7 @@ export function planFinish(t: Pick<TaskRow, "id" | "finish_json">, entries: Histif (budget <= 0) return { error: "There's no room to keep this result right now." };const wanted: WantedFile[] = results.map((r, n) => ({ n, filename: r.filename, subfolder: "", type: "output", kind: roles[r.role].kind, maxBytes: Math.max(1, Math.min(roles[r.role].maxBytes, budget)) }));const stats = Array.isArray(out.stats) && out.stats[0] && typeof out.stats[0] === "object" ? (out.stats[0] as Record<string, unknown>) : {};+ // Why no turntable came back, as the worker said it (it may name things of its PC): for the server's log only.const turntable = Array.isArray(out.turntable) && typeof out.turntable[0] === "string" ? out.turntable[0].slice(0, 200) : undefined;const kept: FinishStats = {...(typeof stats.material === "string" && /^[a-z]{1,16}$/.test(stats.material) && { material: stats.material }),@@ -205,7 +242,7 @@ export function startWorkerModelFinish(generationId: string, outputs: OutputFileclearInterval(watching().get(generationId));watching().delete(generationId);if (r.state === "failed") return o.done(keep({ error: `web GLB: ${r.why === "tab:unsafe-model" ? "the model isn't a self-contained GLB, so it is kept as it is" : "the finish didn't come back, so the model is kept as it is"}` }));- o.done(storeModelFinish(generationId, outputs, i, r));+ o.done(storeModelFinishOnce(id, () => storeModelFinish(generationId, outputs, i, r)));};const timer = setInterval(look, LOOK_MS);timer.unref?.();@@ -213,10 +250,18 @@ export function startWorkerModelFinish(generationId: string, outputs: OutputFilelook();}-/** Stop looking at a run's finish on a worker (the run was canceled or deleted; its task stops with the run). */+/**+ * A run was canceled or deleted: its finishing jobs on the workers stop with it (the 3D finish and every camera path+ * step). One still in line ends at once, with its staged files; one a worker's CPU slot runs is taken off it (the slot+ * hears it in its next report or the worker's next beat). This server stops looking at it too.+ */export function stopWorkerFinish(generationId: string): void {clearInterval(watching().get(generationId));watching().delete(generationId);+ const live = db()+ .prepare("SELECT id FROM relay_tasks WHERE generation_id = ? AND finish_json IS NOT NULL AND state IN ('waiting','sending','queued','running','collecting')")+ .all(generationId) as { id: string }[];+ for (const t of live) endTask(t.id, "canceled", { error: "Stopped" });}/**@@ -263,6 +308,25 @@ export function glbFileSelfContained(file: string): boolean {}}+/**+ * The finished outputs of a run's 3D finish, stored once: the first look at the finished job (in this process or another,+ * as in a deploy's overlap) stores its files and notes the outputs on the job, in one locked step; every later look gets+ * those outputs, and nothing is stored twice.+ */+function storeModelFinishOnce(taskId: string, store: () => OutputFile[]): OutputFile[] {+ const storedOf = () => json<{ stored?: OutputFile[] }>((db().prepare("SELECT extra_json FROM relay_tasks WHERE id = ?").get(taskId) as Pick<TaskRow, "extra_json"> | undefined)?.extra_json ?? null, {}).stored;+ return db()+ .transaction((): OutputFile[] => {+ const had = storedOf();+ if (had) return had;+ const outputs = store();+ const row = db().prepare("SELECT extra_json FROM relay_tasks WHERE id = ?").get(taskId) as Pick<TaskRow, "extra_json"> | undefined;+ if (row) db().prepare("UPDATE relay_tasks SET extra_json = ? WHERE id = ?").run(JSON.stringify({ ...json<Record<string, unknown>>(row.extra_json, {}), stored: outputs }), taskId);+ return outputs;+ })+ .immediate();+}+/** The model output with the worker's finish on it: the web GLB, the turntable clip and its poster, stored as the run's. */function storeModelFinish(generationId: string, outputs: OutputFile[], i: number, r: Extract<FinishOutcome, { state: "done" }>): OutputFile[] {const mesh = outputs[i];@@ -282,7 +346,10 @@ function storeModelFinish(generationId: string, outputs: OutputFile[], i: numberconst clip = save("turntable", "video/mp4", "turntable.mp4", "generation");const poster = clip ? save("poster", r.files.poster?.contentType ?? "image/webp", "poster.webp", "derived") : null;const ownOrbit = outputs.some((x) => x.kind === "video" && x.meta?.role === "orbit");- const turntable = ownOrbit ? OWN_ORBIT : clip ? "done" : (r.turntable ?? "skipped: no turntable");+ // No turntable came back: the account's words, as its own finish here gives them (its browser records one). The+ // worker's reason, which may name things of its PC, goes to the server's log only.+ if (!clip && !ownOrbit && r.turntable) console.warn(`[fuobe] 3D finish for ${generationId}: no turntable came back (${r.turntable.replace(/[^\x20-\x7e]/g, "?")}).`);+ const turntable = ownOrbit ? OWN_ORBIT : clip ? "done" : ACCOUNT_TURNTABLE;const finish = { version: MODEL_FINISH_VERSION, ...(r.stats.material && { material: r.stats.material }), ...(r.stats.triangles !== undefined && { triangles: r.stats.triangles }), rawBytes: r.stats.bytesIn ?? getAsset(mesh.assetId!)?.size, webBytes: r.stats.bytesOut ?? web.size, webAsset: web.id, turntable };const next = outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, web: web.url, finish } } : x));if (!clip) return next;@@ -317,7 +384,10 @@ export async function pathOnWorker(generationId: string, step: number, input: {if (!account) return { state: "failed", error: "This run couldn't finish." };const t = finishTask(generationId, "path", step);if (!t || t.state === "canceled") {- const [photo, depth] = await Promise.all([readRef(input.photo), readRef(input.depth)]);+ const read = await Promise.all([readRef(input.photo), readRef(input.depth)]);+ const pictures = await Promise.all(read.map(finishPicture)).catch(() => null);+ if (!pictures) return { state: "failed", error: "This run couldn't finish." };+ const [photo, depth] = pictures;const id = queueFinish({kind: "path",generationId,@@ -337,11 +407,39 @@ export async function pathOnWorker(generationId: string, step: number, input: {if (r.state === "failed") return { state: "failed", error: "This run couldn't finish." };const f = r.files.path;if (!f) return { state: "failed", error: "This run couldn't finish." };- // Kept once: a later sweep finds the stored file by the task.- const kept = json<{ kept?: string }>(t.extra_json, {}).kept;- if (kept) return { state: "done", url: kept };- const clip = saveFile({ data: fs.readFileSync(f.path), contentType: "video/mp4", name: "path-render.mp4", source: "derived", generationId });- const extra = { ...json<Record<string, unknown>>(t.extra_json, {}), kept: clip.url };- db().prepare("UPDATE relay_tasks SET extra_json = ? WHERE id = ?").run(JSON.stringify(extra), t.id);- return { state: "done", url: clip.url };+ return { state: "done", url: keepPathClip(generationId, t.id, f.path) };+}++/**+ * A picture for a finishing job: as it is when queueFinish can blank what it carries besides its pixels; any other kind+ * of picture (a GIF, say) made again from its pixels here, upright, as a PNG. Throws when it isn't a picture.+ */+async function finishPicture<T extends { data: Buffer; contentType: string; name: string }>(f: T): Promise<T> {+ if (!f.contentType.startsWith("image/") || pictureWithoutMetadata(f.data, f.contentType)) return f;+ const sharp = (await import("sharp")).default;+ const png = await sharp(f.data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 }).rotate().png().toBuffer();+ return { ...f, data: png, contentType: "image/png", name: "picture.png" };+}++/**+ * The path clip of a finished job, stored as the run's file once: a later sweep (or another app process at the same+ * time) finds the stored file by the task. The look and the write are one locked step, and the clip is noted only on a+ * task that had none; a copy stored by a second caller anyway is deleted.+ */+function keepPathClip(generationId: string, taskId: string, file: string): string {+ const keptOf = () => json<{ kept?: string }>((db().prepare("SELECT extra_json FROM relay_tasks WHERE id = ?").get(taskId) as Pick<TaskRow, "extra_json"> | undefined)?.extra_json ?? null, {}).kept;+ return db()+ .transaction((): string => {+ const kept = keptOf();+ if (kept) return kept;+ const clip = saveFile({ data: fs.readFileSync(file), contentType: "video/mp4", name: "path-render.mp4", source: "derived", generationId });+ const row = db().prepare("SELECT extra_json FROM relay_tasks WHERE id = ?").get(taskId) as Pick<TaskRow, "extra_json">;+ const extra = { ...json<Record<string, unknown>>(row.extra_json, {}), kept: clip.url };+ const r = db().prepare("UPDATE relay_tasks SET extra_json = ? WHERE id = ? AND json_extract(COALESCE(extra_json, '{}'), '$.kept') IS NULL").run(JSON.stringify(extra), taskId);+ const other = r.changes === 1 ? undefined : keptOf();+ if (!other) return clip.url;+ deleteAsset(clip.id);+ return other;+ })+ .immediate();}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 9facc4b1..e9d9a38d 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -1,6 +1,6 @@import "server-only";import crypto from "node:crypto";-import { FINISH_KINDS, FINISH_RUN_MS, type FinishTicket } from "@/lib/finish-ticket";+import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";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 CpuSlot, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";@@ -129,9 +129,6 @@ export function slotFor(t: Pick<TaskRow, "slot" | "finish_json">, w: Pick<Workerreturn t.slot === "cpu" && cpuSlotOf(w) ? "cpu" : "gpu";}-/** The run limit of a task in a CPU slot: its lane's run ceiling, never more than a finishing job's. */-const cpuRunLimitMs = (t: Pick<TaskRow, "lane">) => Math.min(FINISH_RUN_MS, runCeilingMs(t.lane));-// ---------------------------------------------------------------------------// What a worker is now@@ -155,6 +152,12 @@ export const catalogCurrent = (w: Pick<WorkerRow, "catalog_version">): boolean =return !!v && w.catalog_version === v;};+/**+ * Takes an account's job ticket: a worker program new enough (TICKET_PROTOCOL: it makes every picture again from its+ * pixels) built for this studio's catalog.+ */+export const ticketReady = (w: Pick<WorkerRow, "protocol" | "catalog_version">): boolean => (w.protocol ?? 0) >= TICKET_PROTOCOL && catalogCurrent(w);+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)"). */@@ -338,10 +341,11 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA*/export function claimableNow(w: WorkerRow, now = Date.now()): number {if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;+ // Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room (left out in the query, so a long+ // line of CPU work never hides the GPU's).const rows = db()- .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS NOT NULL AND INSTR(',' || pools || ',', ?) > 0 ORDER BY ${LINE_ORDER} LIMIT ?`)+ .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS NOT NULL AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}ORDER BY ${LINE_ORDER} LIMIT ?`).all(`,${w.pool},`, LOOK_AT) as TaskRow[];- // Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room.return rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;}@@ -414,6 +418,13 @@ export function inventoryHash(inv: Inventory): string {/** Tasks for workers that wait, best first, at most this many looked at per claim. */const LOOK_AT = 200;+/**+ * The tasks a slot of this worker looks at, as SQL: its CPU slot only those marked for one (light CPU work and finishing+ * jobs); its GPU's slot never a finishing job, nor light CPU work when it has a CPU slot of its own. In the query, so a+ * long line of the other slot's tasks never fills the slot's window of LOOK_AT.+ */+const slotWhere = (w: Pick<WorkerRow, "cpu_slot_json">, slot: WorkerSlot) => (slot === "cpu" ? "AND slot = 'cpu' " : cpuSlotOf(w) ? "AND finish_json IS NULL AND slot IS NULL " : "AND finish_json IS NULL ");+/*** A worker asks for work for one of its slots (its GPU's, or its CPU slot: `slot`), inside one transaction: first a task* that slot had and lost track of; then, if the slot holds none and the worker may take work, the best waiting task that@@ -432,27 +443,28 @@ export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), sif (slot === "cpu" && !cpuSlotOf(fresh)) return null;const held = d.prepare(`SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY ${LINE_ORDER}`).all(fresh.id, device) as TaskRow[];const mine = held.find((t) => !running.includes(t.id));- if (mine) return claimed(mine, fresh, device, now, slot);+ if (mine) return claimed(mine, fresh, device, now);if (held.length || !eligible(fresh, now)) return null;const t = pick(fresh, now, slot);- return t ? claimed(t, fresh, device, now, slot) : null;+ return t ? claimed(t, fresh, device, now) : null;}).immediate();}-function claimed(t: TaskRow, w: WorkerRow, device: string, now: number, slot: WorkerSlot = "gpu"): ClaimedTask {+function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {const needs = json<Needs | null>(t.needs_json, null);const bench = t.lane ? benchOf(w)[t.lane] : undefined;if (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.- // 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 }) } : {};+ // A job ticket's task keeps the time of its claim before this one, and which claim that note is for (`claimFor`, this+ // claim's time): a refusal of the ticket on this same claim, before anything ran (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, claimFor: now }) } : {};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.- // A CPU slot's task has the CPU slot's own run limit (a finishing job's at most).- const limit = slot === "cpu" ? cpuRunLimitMs(t) : runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs);+ // come from shorter jobs than this one); past that, it fails. Light CPU work has the same limits in either slot. A+ // finishing job has its lane's run ceiling (queue-settings.ts, the owner's to set).+ const limit = t.finish_json || runLimitedOf(t) ? runCeilingMs(t.lane) : runLimitMs(bench?.p90Ms, t.lane, bench?.loadMs);const stall = Math.min(stallLimitMs(t.lane), limit);return {...c,@@ -535,9 +547,9 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {*/function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): TaskRow | null {const settings = queueSettings(now);- // A CPU slot looks only at the tasks marked for one.+ // Each slot looks only at its own tasks.const rows = db()- .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slot === "cpu" ? "AND slot = 'cpu' " : ""}ORDER BY ${LINE_ORDER} LIMIT ?`)+ .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, slot)}ORDER BY ${LINE_ORDER} LIMIT ?`).all(`,${w.pool},`, LOOK_AT) as TaskRow[];const ok = lineOrder(rows, settings.fairShare).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));if (!ok.length) return null;@@ -733,12 +745,22 @@ const runLimitedOf = (t: TaskRow) => json<{ runLimited?: boolean }>(t.extra_json*/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).+ // line at no cost, never offered to that worker again. Refused on the claim that took it from the line, before+ // anything ran on that claim, it waits as it did before that claim (a task no worker took keeps its wait limit). Once+ // a job of it was sent or ran, it keeps its claim's time: its wait limit is over for good. In one locked step with+ // going back in line, so a claim another app process makes meanwhile is never changed.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 });+ db()+ .transaction(() => {+ 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, claimFor, ...rest } = json<Record<string, unknown>>(t.extra_json, {});+ const extra = { ...rest, refusedBy: [...new Set([...refusedBy(t), ...(w ? [refusalKey(w)] : [])])].slice(-64) };+ const untouched = typeof claimFor === "number" && claimFor === t.claimed_at && t.state === "sending" && !t.sent_at && !t.started_at;+ if (!backInLine(t, untouched ? { blame: false } : { blame: true, why: GAVE_BACK_WORDS })) return;+ if (taskById(t.id)?.state !== "waiting") return;+ setTask(t.id, { extra_json: JSON.stringify(extra), ...(untouched && { claimed_at: typeof claimedBefore === "number" ? claimedBefore : null }) });+ })+ .immediate();return;}if (why === "run-limit") {@@ -867,20 +889,24 @@ export function poolLane(workflowId: string): string {* Is there a worker for this workflow (any workflow: `workflowId` null): one the owner added and didn't revoke, allowed* the workflow's lane, and able to run it as its last list of files said (its verified files and node packs, the kinds* of input it takes) with the VRAM it needs, whether it is paused, outside its hours or offline right now (a run then- * waits in line for it). A run that no worker could ever take is refused before Run, never left to wait for nothing.+ * waits in line for it). Inside its PC's ceiling: the lanes or workflows that PC may ever run, and, given the job's+ * `size`, its largest picture, longest clip and most results. A run that no worker could ever take is refused before+ * it is queued, never left to wait for nothing. `tickets`: only a worker that takes job tickets now (ticketReady), as+ * an account's run needs; without it, a worker built from another catalog counts too (the owner's own jobs, and+ * whether this install's GPUs could ever run it).*/-export function workersCanRun(workflowId: string | null): boolean {+export function workersCanRun(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean } = {}): boolean {const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;const lane = workflowId ? poolLane(workflowId) : null;// (Runs made here go to the "pool" pool: poolFields.)return poolWorkers().some((w) => {if (w.pool !== "pool") return false;+ if (o.tickets && !ticketReady(w)) return false;const allow = allowOf(w);const cap = capableOf(w);- // 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;+ if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId) || ceilingProblem(ceiling, { workflowId, lane, size: o.size })) return false;return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);});}@@ -914,8 +940,11 @@ export function lineFacts(accountId: string | null, asked: string | null, now =const workflowId = asked && !asked.includes("{") ? asked : null;const lane = workflowId ? poolLane(workflowId) : null;const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;- // A new run of a person's, in the free class (a paid run's head start is the billing service's to price, not to quote).- const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;+ // A new run of a person's, in the free class (a paid run's head start is the billing service's to price, not to quote):+ // a job ticket for this studio's catalog, which only a worker built for it takes (its place and wait, and the workers+ // online, count those workers only).+ const version = catalogVersion();+ const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify({ ...needs, ...(version && { catalogVersion: version }) }) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;const p = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fitsSlot({ ...probe, created_at: 0 }, w, now, slotFor(probe, w)))).length;return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null };diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex d0564d73..9f27651f 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -393,6 +393,27 @@ export function createTask(t: NewTask): { id: string; promptId: string } {return { id, promptId };}+/**+ * One of a task's inputs put in place of another (a job ticket made again, whose graph's own file came out new): `next`+ * is staged as the task's, after its other inputs, and `old` (when given) goes with its file. `next` null: `old` only+ * goes. Returns the new input's name and SHA-256.+ */+export function swapTaskInput(t: Pick<TaskRow, "id" | "principal">, old: string | null, next: { data: Buffer; contentType: string; name: string } | null): { name: string; sha256: string } | null {+ const d = rdb();+ let made: { name: string; sha256: string } | null = null;+ if (next) {+ const name = stageInput(t.principal as Principal, next.data, next.contentType, next.name);+ const n = (d.prepare("SELECT COALESCE(MAX(n), -1) + 1 AS n FROM relay_inputs WHERE task_id = ?").get(t.id) as { n: number }).n;+ d.prepare("UPDATE relay_inputs SET task_id = ?, n = ? WHERE name = ?").run(t.id, n, name);+ made = { name, sha256: crypto.createHash("sha256").update(next.data).digest("hex") };+ }+ if (old) {+ fs.rmSync(inputFile(old), { force: true });+ d.prepare("DELETE FROM relay_inputs WHERE name = ? AND task_id = ?").run(old, t.id);+ }+ return made;+}+/** The names of the inputs a principal staged that no task has taken yet (its next task's files). */export const freeInputs = (principal: Principal): string[] =>(rdb().prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL").all(principal) as { name: string }[]).map((r) => r.name);@@ -740,8 +761,11 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLikeconst entries = e.event === "finished" ? [e.entry] : e.entries;if (!Array.isArray(entries) || entries.some((x) => !x || typeof x !== "object")) throw new RelayError(400, "Bad history entry");const p = plan(entries, e.event === "passes");- // A worker's job ended on its ComfyUI: the workers' log keeps its measured run (the billing service settles with it).- if (t.pools && t.worker_id && (!("follow" in p) || !t.meta_batch)) logWorkerJob("finished", t, t.worker_id, now, execFields(e, t, now) ?? {});+ // A worker's job ended on its ComfyUI: the workers' log keeps its measured run (the billing service settles with it,+ // and a lane's typical run is read from it). CPU work (light CPU work, a finishing job) uses no GPU: its time and+ // device are never kept as the run's GPU time.+ const cpuWork = t.slot === "cpu" || !!t.finish_json;+ if (t.pools && t.worker_id && (!("follow" in p) || !t.meta_batch)) logWorkerJob("finished", t, t.worker_id, now, cpuWork ? {} : (execFields(e, t, now) ?? {}));if ("follow" in p) {if (!t.meta_batch) {endTask(t.id, "failed", { error: "This run finished without a result. Press Retry." });diff --git a/src/server/computer/ticket-refresh.ts b/src/server/computer/ticket-refresh.tsindex 6bfc84b2..252c9c66 100644--- a/src/server/computer/ticket-refresh.ts+++ b/src/server/computer/ticket-refresh.ts@@ -1,23 +1,52 @@import "server-only";-import type { JobTicket } from "@/lib/job-ticket";-import type { Needs } from "@/lib/lanes";-import { composeTicket } from "@/lib/ticket-compose";+import crypto from "node:crypto";+import type { JobTicket, TicketInput } from "@/lib/job-ticket";+import { composeTicket, inputKind } 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";+import { GAVE_BACK_WORDS, poolFields } from "./pool";+import { endTask, inputsOf, json, setTask, swapTaskInput, 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.+ * its ticket made again for the catalog it runs now, with its place kept (its rank, class and wait). The same request is+ * composed with this studio's composer, so its files and settings are checked again; the files the graph makes are made+ * again too, and staged in place of the old ones when they came out other than before. Its lane and what it needs come+ * from this catalog. 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.+ *+ * Only forward: while a deploy's two app processes share the database, only the one started last (the newest version)+ * makes tickets again, and only it ever ends a run for it. The other leaves every ticket as it is.*/-export async function refreshTickets(): Promise<{ refreshed: number; ended: number }> {- const version = catalogVersion();++declare global {+ var __fuobeProcessStart: number | undefined;+}++/** When this app process started. */+export const processStart = () => (globalThis.__fuobeProcessStart ??= Math.round(Date.now() - process.uptime() * 1000));++/** An app process that said nothing for this long has stopped (each one says so at most a minute apart while workers claim). */+const GONE_MS = 5 * 60_000;++/**+ * Say that a process of this catalog version runs (started at `startedAt`), and whether it is the newest: of the app+ * processes on this database heard from lately, none started after it with another version. A deploy's new process is+ * the newest from its start; so is a rollback's.+ */+export function newestCatalog(version: string, startedAt = processStart(), now = Date.now()): boolean {+ const d = db();+ d.prepare("INSERT INTO catalog_processes (version, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(version) DO UPDATE SET started_at = MAX(started_at, excluded.started_at), seen_at = MAX(seen_at, excluded.seen_at)").run(version, startedAt, now);+ const later = d.prepare("SELECT 1 FROM catalog_processes WHERE version != ? AND seen_at > ? AND started_at > ? LIMIT 1").get(version, now - GONE_MS, startedAt);+ return !later;+}++export async function refreshTickets(o: { version?: string; startedAt?: number; now?: number } = {}): Promise<{ refreshed: number; ended: number }> {+ const version = o.version ?? catalogVersion();if (!version) return { refreshed: 0, ended: 0 };+ // A process of an older version (a deploy's overlap) leaves every ticket as it is.+ if (!newestCatalog(version, o.startedAt ?? processStart(), o.now ?? Date.now())) 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[];@@ -31,7 +60,7 @@ export async function refreshTickets(): Promise<{ refreshed: number; ended: numbdelete 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);+ const r = await composeTicket({ ticket, generationId: t.generation_id, inputs }, { catalog, catalogVersion: version, remake: true }).catch(() => null);// Written only while the task is as it was read (still waiting, the same ticket).db().transaction(() => {@@ -42,12 +71,25 @@ export async function refreshTickets(): Promise<{ refreshed: number; ended: numbended++;return;}- const fresh: JobTicket = { ...ticket, size: r.size };- const needs = { ...json<Needs | Record<string, never>>(t.needs_json, {}), catalogVersion: version, size: r.size };+ // The files the graph makes, as they came out now: the same bytes keep their staged file, new ones take the old+ // one's place.+ const wasMade = ticket.inputs.filter((i) => i.slot.startsWith("made.")).sort((a, b) => Number(a.slot.slice(5)) - Number(b.slot.slice(5)));+ const made: TicketInput[] = r.made.map((m, i) => {+ const had = wasMade[i];+ const sha256 = crypto.createHash("sha256").update(m.data).digest("hex");+ if (had && had.sha256 === sha256) return had;+ const swapped = swapTaskInput(t, had?.name ?? null, { data: m.data, contentType: m.contentType, name: `made-${i}` })!;+ return { slot: `made.${i}`, name: swapped.name, kind: inputKind(m.contentType, swapped.name), sha256: swapped.sha256 };+ });+ for (const gone of wasMade.slice(r.made.length)) swapTaskInput(t, gone.name, null);+ const fresh: JobTicket = { ...ticket, inputs: [...ticket.inputs.filter((i) => !i.slot.startsWith("made.")), ...made], size: r.size };+ // Its lane and what it needs, from this catalog (the workflow may have moved to other files); its rank, class and+ // wait as they were.+ const fields = poolFields(r.workflowId, { size: r.size, catalogVersion: version });// 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) });+ setTask(t.id, { ticket_json: JSON.stringify(fresh), needs_json: JSON.stringify(fields.needs), lane: fields.lane, slot: fields.slot ?? null, extra_json: JSON.stringify(extra) });refreshed++;}).immediate();diff --git a/src/server/db.ts b/src/server/db.tsindex 25fd8e1a..38847987 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -822,6 +822,11 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (principal TEXT,worker_id TEXT);+ CREATE TABLE IF NOT EXISTS catalog_processes (+ version TEXT PRIMARY KEY,+ started_at INTEGER NOT NULL,+ seen_at INTEGER NOT NULL+ );CREATE TABLE IF NOT EXISTS worker_jobs (id INTEGER PRIMARY KEY AUTOINCREMENT,at INTEGER NOT NULL,diff --git a/src/server/generations.ts b/src/server/generations.tsindex bb07dd77..ec0c461b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -98,7 +98,7 @@ import { renderPathVideo } from "./path-render";import { songFormat, songToolProblem } from "@/lib/lyrics";import { hostedUntested } from "@/lib/catalog/hosted-untested";import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";-import { pathOnWorker, startWorkerModelFinish, stopWorkerFinish, workersFinish } from "./computer/finish";+import { finishTask, pathOnWorker, startWorkerModelFinish, stopWorkerFinish, workersFinish } from "./computer/finish";import { PATH_FPS, PATH_FRAMES } from "@/lib/camera-path";import { cropPicture, isCropWindow } from "./crop-picture";import { convertMask, decodePng, encodePng } from "./png";@@ -107,7 +107,7 @@ import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError }import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";-import { placeInLine, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";+import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";import { poolLane } from "./computer/pool";import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";@@ -1629,9 +1629,9 @@ async function advanceDependents(): Promise<void> {const photo = withChainInputs({ ...request, chain: slots }, values as string[]).inputs?.images?.[0];const keys = request.params?.cameraPath ?? [];if (deps[i]!.provider === "mock" || !photo) values[i] = placeholderFor(slots[i]);- else if (account && stored.place === "pool" && workersFinish("path")) {+ else if (account && stored.place === "pool" && (workersFinish("path") || finishTask(r.id, "path", i))) {// A run on this install's GPUs: the path is drawn on a worker's CPU slot (computer/finish.ts), never here. The- // step waits for it, sweep by sweep.+ // step waits for it, sweep by sweep (once queued, it stays the worker's even while no CPU slot is about).const depth = values[i]!;const got = await asRun(() => pathOnWorker(r.id, i, { photo, depth, keys, frames: PATH_FRAMES, fps: PATH_FPS }));if (got.state === "failed") throw new Error(got.error);@@ -2688,8 +2688,10 @@ function resumeFinish(r: Row): void {const outputs = JSON.parse(r.outputs_json || "[]") as OutputFile[];// An account's model: one account finish at a time, and no turntable on the server (its browser records one).const account = accountOf(r);- // An account's run on this install's GPUs is finished on a worker's CPU slot, never here (computer/finish.ts).- const onWorker = !!account && (JSON.parse(r.request_json) as GenerationRequest).place === "pool" && workersFinish("model3d");+ // An account's run on this install's GPUs is finished on a worker's CPU slot, never here (computer/finish.ts): queued+ // there even while no CPU slot is about (it waits in line, and past its wait the model is kept as it is).+ const stored = JSON.parse(r.request_json) as GenerationRequest;+ const onWorker = !!account && stored.place === "pool" && poolOnWorkers();(onWorker ? startWorkerModelFinish : startModelFinish)(r.id, outputs, {op: r.op,provider: r.provider,@@ -2701,6 +2703,13 @@ function resumeFinish(r: Row): void {if (!now || now.status !== "running") return;const meta = JSON.parse(now.external_meta_json ?? "{}") as Record<string, unknown>;delete meta.finishing;+ // The moderation service asked to see this run's outputs first: the finished model and its turntable are held, and+ // the row waits ("Checking"), as any run's outputs are.+ if (stored.checkOutputs && moderationConfigured()) {+ update(r.id, { external_meta_json: JSON.stringify(meta) });+ holdForCheck(r.id, finished);+ return;+ }update(r.id, { status: "succeeded", outputs_json: JSON.stringify(finished), external_meta_json: JSON.stringify(meta), progress: 1, message: null, completed_at: Date.now() });// The model can be opened and downloaded now; its turntable is rendered after and added to the result.if (!account) startTurntable(r.id, outputStore(r.id));diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex f8a5228f..8405522e 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -29,7 +29,7 @@ import { PLACE_ASK_HEADER } from "@/lib/guest-access";import { createGenerations, outputKind, plannedSteps, previewGeneration, type PlannedStep } from "./generations";import { loadIndex } from "./gpu/index-file";import { poolLane } from "./computer/pool";-import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";+import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesFiles, poolTicketsReady, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";import { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";@@ -183,9 +183,9 @@ export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]/*** Why this install's GPUs won't take a run: a 3D model, a model or kind not offered there, a model their card can't run,- * LoRAs, or a kind of file.+ * LoRAs, a kind of file, or (`busy`) not right now: the GPUs that could run it are being updated.*/-export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs";+export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "busy";/** The words for a gate's reason: an account may connect its own GPU in Settings, a guest has nowhere to do that yet. */export function gateWords(reason: GateReason, guest: boolean): string {@@ -223,6 +223,10 @@ export function poolGate(const steps = planSteps();const problem = steps && p ? stepsProblem(p, steps) : null;if (problem) return { ok: false, reason: problem === HOSTED_WORDS.rtxCard ? "rtxCard" : "notOffered" };+ // A run its GPUs could take, but none of them can right now (every one that could is built from the catalog before+ // this studio's update): Run is off until one is updated, never a run that waits in line for nothing.+ const endpoints = [planned.route.endpoint, ...(steps ?? []).filter((s) => s.provider === "comfyui").map(stepEndpoint)];+ if (!endpoints.every((e) => poolTicketsReady(e))) return { ok: false, reason: "busy" };return { ok: true, steps };}@@ -325,6 +329,7 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wiif (!gate.ok) {if (ownFallback) return OWN;const error = gateWords(gate.reason, false);+ if (gate.reason === "busy") return { kind: "refuse", refusal: billingRefusal("busy", error) };return gate.reason === "model3d" ? { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } } : notOffered(error);}// Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.@@ -487,7 +492,9 @@ export async function poolQuote(const gate = poolGate(p, planned, req, () => stepsFor(account, req));if (!gate.ok) {if (hasGpu && wish !== "pool") return null;- return { planned, quote: notOfferedQuote(gateWords(gate.reason, !account)), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };+ const words = gateWords(gate.reason, !account);+ const quote = gate.reason === "busy" ? { ...notOfferedQuote(words), code: "busy" as const } : notOfferedQuote(words);+ return { planned, quote, line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };}// Light work only (joins, trims): free, and never counted against the policy's limits, so the service isn't asked.if (lightRun(gate.steps)) {diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 14e811bf..937c41bd 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -84,6 +84,18 @@ export function poolTakes(endpoint: string | undefined): boolean {return picks.length > 0 && picks.every((id) => workersCanRun(id));}+/**+ * Can this install's GPUs take this workflow's job tickets now (an account's run there goes as one): on the workers, one+ * built for this studio's catalog that may run it (a workflow that picks its graph at run time: every graph it may+ * pick). After an update of the studio, a worker built from the catalog before takes them once it is updated too:+ * meanwhile poolTakes still says the run could go there, and this says not yet. Not on the workers: yes.+ */+export function poolTicketsReady(endpoint: string | undefined): boolean {+ if (!endpoint || !poolOnWorkers()) return true;+ const picks = endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint];+ return picks.length > 0 && picks.every((id) => workersCanRun(id, { tickets: true }));+}+/*** The steps a run on this install's GPUs can carry out there: ComfyUI's. The price check, the run's admission and its* submit read this one table, so a run is refused before Run when a step of it couldn't run there (a text step, a step@@ -112,10 +124,12 @@ export const HOSTED_WORDS = {rtxCard: "This one needs an NVIDIA RTX card, and this studio's GPUs can't run it right now. Connect your own GPU in Settings, or pick another choice.",notHosted: "Runs on this studio's GPUs aren't open to this account. Connect your own GPU in Settings.",waitedTooLong: "This studio's GPUs were busy, so it didn't run. Not charged.",+ busy: "Busy right now. Try again in a little while.",};/** The same refusals for a guest, who has no Settings to connect a GPU in yet. */export const HOSTED_GUEST_WORDS = {+ busy: HOSTED_WORDS.busy,notOffered: "This one isn't offered here. Pick another model.",rtxCard: "This one isn't offered here right now. Pick another choice.",loras: "Extra LoRAs aren't offered here. Run without them.",diff --git a/src/server/media-clean.ts b/src/server/media-clean.tsindex e46bf1ed..4c926c0a 100644--- a/src/server/media-clean.ts+++ b/src/server/media-clean.ts@@ -56,13 +56,15 @@ export function patchStream(patches: Patch[], start: number): Transform {// ---------------------------------------------------------------------------// Reading+/** A file read by its descriptor, or a file already in memory (`fd` a Buffer). */class Reader {constructor(- private readonly fd: number,+ private readonly fd: number | Buffer,readonly size: number,) {}read(at: number, n: number): Buffer {const len = Math.max(0, Math.min(n, this.size - at));+ if (typeof this.fd !== "number") return Buffer.from(this.fd.subarray(at, at + len));const buf = Buffer.alloc(len);let got = 0;while (got < len) {@@ -514,3 +516,99 @@ export function cachedPatches(abs: string, stat: { size: number; mtimeMs: numbercache.set(key, patches);return patches;}++// ---------------------------------------------------------------------------+// Pictures sent on to another machine++/**+ * A JPEG's EXIF block made again with only its orientation (1 to 8): "Exif", a big-endian TIFF header and one IFD with+ * the one tag. 32 bytes: it fits in any EXIF segment that held an orientation.+ */+function orientationOnly(orientation: number): Buffer {+ const b = Buffer.alloc(32);+ b.write("Exif", 0, "latin1");+ b.write("MM", 6, "latin1");+ b.writeUInt16BE(42, 8);+ b.writeUInt32BE(8, 10);+ b.writeUInt16BE(1, 14);+ b.writeUInt16BE(0x0112, 16);+ b.writeUInt16BE(3, 18);+ b.writeUInt32BE(1, 20);+ b.writeUInt16BE(orientation, 24);+ return b;+}++/** A JPEG's EXIF orientation (other than 1), read from its first EXIF segment: the patches that keep only it there. */+function keepOrientation(r: Reader): Patch[] {+ let at = 2;+ for (;;) {+ const h = r.read(at, 4);+ if (h.length < 4 || h[0] !== 0xff) return [];+ const m = h[1];+ if (m === 0xff) {+ at += 1;+ continue;+ }+ if (m === 0xd9 || m === 0xda) return [];+ if (m === 0x01 || (m >= 0xd0 && m <= 0xd7)) {+ at += 2;+ continue;+ }+ const len = h.readUInt16BE(2);+ if (len < 2) return [];+ if (m === 0xe1 && len - 2 >= 32 && r.read(at + 4, 6).toString("latin1") === "Exif\0\0") {+ const exif = r.read(at + 4, len - 2);+ const o = tiffOrientation(exif);+ // After the patches that blank the segment: it stays EXIF, with the orientation alone in it.+ return o && o !== 1 ? [{ at: at + 1, bytes: Buffer.from([0xe1]) }, { at: at + 4, bytes: orientationOnly(o) }] : [];+ }+ at += 2 + len;+ }+}++/** The orientation tag (0x0112) of IFD0 in an EXIF block ("Exif\0\0" and a TIFF header), or null. */+function tiffOrientation(exif: Buffer): number | null {+ const start = 6;+ if (exif.length < start + 8) return null;+ const le = exif.toString("latin1", start, start + 2) === "II";+ if (!le && exif.toString("latin1", start, start + 2) !== "MM") return null;+ const u16 = (o: number) => (le ? exif.readUInt16LE(o) : exif.readUInt16BE(o));+ const u32 = (o: number) => (le ? exif.readUInt32LE(o) : exif.readUInt32BE(o));+ const ifd = start + u32(start + 4);+ if (ifd + 2 > exif.length) return null;+ const n = u16(ifd);+ for (let i = 0; i < n; i++) {+ const e = ifd + 2 + i * 12;+ if (e + 12 > exif.length) return null;+ if (u16(e) === 0x0112) {+ const v = u16(e + 8);+ return v >= 1 && v <= 8 ? v : null;+ }+ }+ return null;+}++/**+ * A picture with what it carries besides its pixels blanked, as the share files are (the same patches): a JPEG's EXIF,+ * XMP, comments and other application segments, a PNG's text and EXIF chunks, a WebP's EXIF and XMP, an SVG's+ * metadata. Nothing is decoded, and the size and every offset stay. A JPEG keeps its EXIF orientation (alone in its EXIF+ * segment), so it shows the way it did. The same bytes back when there was nothing to blank; null for any other kind of+ * picture (a GIF, say: it is made again from its pixels instead), or one that can't be read where such data lives.+ */+export function pictureWithoutMetadata(data: Buffer, contentType = ""): Buffer | null {+ try {+ const r = new Reader(data, data.length);+ const head = r.read(0, 16);+ const at = (s: string, i = 0) => head.toString("latin1", i, i + s.length) === s;+ let patches: Patch[] = [];+ if (head.length >= 8 && head.readUInt32BE(0) === 0x89504e47) patches = png(r);+ else if (head[0] === 0xff && head[1] === 0xd8) patches = [...jpeg(r), ...keepOrientation(r)];+ else if (at("RIFF") && at("WEBP", 8)) patches = riff(r, true);+ else if (contentType.split(";")[0].trim().toLowerCase() === "image/svg+xml") patches = svg(r);+ else return null;+ return patches.length ? overlay(data, 0, patches) : data;+ } catch (e) {+ if (e instanceof Unreadable || e instanceof RangeError) return null;+ throw e;+ }+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex ce32e804..fe03d934 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -29,6 +29,7 @@ import { probeMedia, type MediaInfo } from "@/lib/media-probe";import { ocrText, parseOcrFrame, parseOcrLines, type OcrFrame } from "@/lib/ocr";import { getSetting, isCandidate, savedSetting } from "../settings";import { decodePng } from "../png";+import { pictureWithoutMetadata } from "../media-clean";import { probeAvi } from "../avi-probe";import { probeWebm } from "../webm-probe";import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";@@ -212,18 +213,29 @@ export const workersTake = (kind: "image" | "video" | "audio"): boolean => poolM/*** A file for a job on the workers: refused when they don't take its kind. A picture is made again from its pixels here* (no EXIF, no GPS), unless `o.onWorker`: then the worker makes it again itself before its ComfyUI reads it, and this- * server only checks that it is a picture it can size.+ * server only checks that it is a picture it can size, and blanks what it carries besides its pixels (EXIF and GPS,+ * XMP, comments, text) without decoding it: none of that ever leaves for a worker. A JPEG keeps its orientation. A+ * kind of picture whose such parts this server can't blank that way (a GIF, say) is made again from its pixels here.*/export async function forWorkers(data: Buffer, contentType: string, name: string, o: { onWorker?: boolean } = {}): Promise<{ data: Buffer; contentType: string; name: string }> {const kind = contentType.split("/")[0];if (!poolMedia().has(kind)) throw new ProviderError(kind === "video" ? "The shared GPUs don't take clips yet." : kind === "audio" ? "The shared GPUs don't take sound yet." : "The shared GPUs don't take this kind of file.");if (kind !== "image") return { data, contentType, name };+ const refused = () => new ProviderError("The shared GPUs don't take this kind of file.");if (o.onWorker) {- if (!imageSize(data)) throw new ProviderError("The shared GPUs don't take this kind of file.");- return { data, contentType, name };+ if (!imageSize(data)) throw refused();+ const clean = pictureWithoutMetadata(data, contentType);+ if (clean) return { data: clean, contentType, name };}const sharp = (await import("sharp")).default;- const png = await sharp(data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 }).rotate().png().toBuffer();+ const png = await sharp(data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 })+ .rotate()+ .png()+ .toBuffer()+ .catch((e: unknown) => {+ if (o.onWorker) throw refused();+ throw e;+ });return { data: png, contentType: "image/png", name: name.replace(/\.[^.]*$/, "") + ".png" };}@@ -264,6 +276,12 @@ export function installComfyLocal(worker: ComfyWorker = "main"): boolean {/** Said when a run on this install's GPUs can't go where it was planned (its row's own words then say it plainly). */export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this machine, so runs of accounts don't go to it.";+/** Said to the owner when a job is larger than every worker's PC may ever run (its ceiling: `fuobe worker setup`). */+export const NO_WORKER_FOR_SIZE = "No worker may run a job this large: each PC's limits, set with fuobe worker setup, are lower. Pick a smaller size, a shorter clip or fewer results.";++/** Said to an account when its run is larger than this install's GPUs ever make (refused before it is queued). */+export const POOL_TOO_BIG = "This size isn't offered here yet. Pick a smaller size, a shorter clip or fewer results.";+/** Said to the owner when no worker is allowed the lane of a job sent to the workers. */export const NO_WORKER_FOR_LANE = "No worker can run this model yet. Allow its lane for a worker that has its model files, in Settings → Open-source engine · ComfyUI → Workers.";@@ -1005,14 +1023,15 @@ const mediaKey = (name: string) => {};/** What the server reads from a file it sends to ComfyUI (a clip's length and size, a picture's size), by its name there. */-function rememberSent(uploaded: string, data: Buffer, contentType: string, name: string) {+function rememberSent(uploaded: string, data: Buffer, contentType: string, name: string, oriented = false) {if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name) || /\.(webm|mkv|avi)$/i.test(name)) {const info = probeMedia(data) ?? webmInfo(data) ?? aviInfo(data);if (info) rememberMedia(uploaded, info);} else if (/^image\//.test(contentType)) {- // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape (as it shows, turned by its- // EXIF orientation: a worker makes the picture again upright).- const size = orientedImageSize(data);+ // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape. `oriented`: an account's+ // picture that a worker makes again upright (turned by its EXIF orientation) is sized as it shows; any other is sized+ // by its pixels, as the ComfyUI that gets it reads them.+ const size = oriented ? orientedImageSize(data) : imageSize(data);if (size) rememberMedia(uploaded, { container: "image", ...size, hasVideo: false, hasAudio: false });}}@@ -1325,7 +1344,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,// are made again here, as before.const sent = onWorkers(computer) ? await forWorkers(data, contentType, name, { onWorker: computer !== "owner" }) : { data, contentType, name };const staged = stageInput(computer, sent.data, sent.contentType, sent.name);- rememberSent(staged, sent.data, sent.contentType, sent.name);+ rememberSent(staged, sent.data, sent.contentType, sent.name, onWorkers(computer) && computer !== "owner");return staged;}// A run on this install's workers with no account behind it (a guest's price check) never sends anything.@@ -1661,6 +1680,9 @@ 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);+ // A job larger than every PC that could run it may ever make (its ceiling) would never be taken: refused now, the+ // owner's and an account's alike, before it waits in line.+ if (forPool && workersCanRun(manifest.id) && !workersCanRun(manifest.id, { size: prepared.size })) throw new ProviderError(computer === "owner" ? NO_WORKER_FOR_SIZE : POOL_TOO_BIG);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;diff --git a/tests/cpu-slot.test.ts b/tests/cpu-slot.test.tsindex e99ee9e0..4b0b7d37 100644--- a/tests/cpu-slot.test.ts+++ b/tests/cpu-slot.test.ts@@ -33,10 +33,11 @@ const finish = await import("@/server/computer/finish");const { onComputer } = await import("@/server/providers/comfyui");const { allLanes } = await import("@/lib/lanes");const { loadIndex } = await import("@/server/gpu/index-file");-const { finishProblem, FINISH_RUN_MS } = await import("@/lib/finish-ticket");+const { finishProblem } = await import("@/lib/finish-ticket");const { previewOf, PREVIEW_LIMITS } = await import("@/lib/relay");const { previewForReport } = await import("@/lib/computer-runner");const { exifOrientation, orientedImageSize } = await import("@/lib/image-size");+const { catalogVersion } = await import("@/server/computer/catalog-version");const ROOT = path.resolve(__dirname, "..");const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");@@ -73,14 +74,15 @@ function addWorker(): W {return w;}-/** A worker's beat as the program sends it, with its CPU slot (null: none) and what each slot runs. */-const beat = (w: W, o: { cpuSlot?: { finishes: string[] } | null; local?: { paused: boolean; why: string | null }; running?: string[]; cpuRunning?: string[] } = {}) =>+/** A worker's beat as the program sends it (built for this studio's catalog), with its CPU slot (null: none) and what each slot runs. */+const beat = (w: W, o: { cpuSlot?: { finishes: string[] } | null; local?: { paused: boolean; why: string | null }; running?: string[]; cpuRunning?: string[]; catalogVersion?: string | null; protocol?: number } = {}) =>pool.workerBeat(workerRow(w),pool.cleanBeat({device: `wkr-${w.id}`,- protocol: 3,+ protocol: o.protocol ?? 3,version: "1",+ catalogVersion: o.catalogVersion === undefined ? catalogVersion() : o.catalogVersion,local: { ...(o.local ?? { paused: false, why: null }), until: null },gpu: {},inventoryHash: null,@@ -144,7 +146,8 @@ describe("the CPU slot on the line", () => {const c = claim(w, "cpu");expect(c?.id).toBe(cpu);expect(c?.slot).toBe("cpu");- expect(c?.runLimitMs).toBeLessThanOrEqual(FINISH_RUN_MS);+ // Light CPU work has its lane's run limit in either slot, as on the GPU's.+ expect(c?.runLimitMs).toBe(pool.runLimitMs(null, row(cpu).lane));// One at a time in each slot.expect(claim(w, "gpu", [gpu])).toBeNull();expect(claim(w, "cpu", [cpu])).toBeNull();@@ -309,7 +312,8 @@ describe("live previews from a worker", () => {const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });const report = (body: Record<string, unknown>) => api(`/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fuobe-Lease": c.lease }, body: JSON.stringify(body) });expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);- const big = jpeg(70 * 1024).toString("base64");+ // Just over 64 KB: the report is kept, its preview dropped.+ const big = jpeg(PREVIEW_LIMITS.maxBytes + 1024).toString("base64");expect((await report({ event: "running", value: 2, max: 8, preview: big })).status).toBe(200);expect(tasks.taskProgress(id)).toMatchObject({ value: 2, max: 8 });expect(tasks.taskPreview(id)).toBeNull();@@ -320,8 +324,12 @@ describe("live previews from a worker", () => {// A beat never brings a preview.beat(w, { running: [id] });expect(tasks.taskPreview(id)?.jpeg.equals(ok)).toBe(true);- // A progress report with no preview stays a few KB.+ // A progress report with no preview stays a few KB; one with a preview, under about 91 KB in all (a 64 KB JPEG as+ // base64 and a few KB more).expect((await report({ event: "running", value: 4, max: 8, node: "x".repeat(20 * 1024) })).status).toBe(413);+ expect((await report({ event: "running", value: 5, max: 8, preview: jpeg(70 * 1024).toString("base64") })).status).toBe(413);+ expect((await report({ event: "running", value: 5, max: 8, preview: ok.toString("base64"), node: "x".repeat(8 * 1024) })).status).toBe(200);+ expect((await report({ event: "running", value: 6, max: 8, preview: jpeg(PREVIEW_LIMITS.maxBytes).toString("base64"), node: "x".repeat(8 * 1024) })).status).toBe(413);});});@@ -360,3 +368,495 @@ describe("pictures as they show", () => {expect(orientedImageSize(plain)).toEqual({ width: 40, height: 20 });});});++// ---------------------------------------------------------------------------+// Each slot's own line, its limits and its claims++/** A finishing job made straight in the line (no files), ahead of everything made after it. */+function bareFinish(rankAt: number) {+ const gid = generation(accountId, "image-to-3d");+ return tasks.createTask({+ principal: `acct:${accountId}`,+ generationId: gid,+ graph: {},+ finish: { v: 1, kind: "model3d", settings: { material: "auto", turntable: false }, inputs: [] },+ workflowId: "finish-model3d",+ pool: { pools: ["pool"], account: accountId, class: "free", rankAt, lane: "small", needs: { workflowId: "finish-model3d", files: [], packs: [], minVramBytes: 0 }, slot: "cpu" },+ }).id;+}++describe("each slot's own line", () => {+ it("a long line of CPU work ahead never hides a GPU job from a worker's GPU slot, nor from the count of people's jobs it may take", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ // More light CPU tasks than a slot looks at, every one ahead of the GPU job in line.+ for (let i = 0; i < 205; i++) accountTask(CPU_WORKFLOW);+ const gpu = accountTask(GPU_WORKFLOW);+ expect(pool.claimableNow(workerRow(w))).toBe(1);+ expect(claim(w)?.id).toBe(gpu);+ for (const t of db().prepare("SELECT id FROM relay_tasks WHERE state = 'waiting'").all() as { id: string }[]) tasks.endTask(t.id, "canceled");+ // A worker with no CPU slot: as many finishing jobs ahead, which only a CPU slot takes.+ const plain = addWorker();+ beat(plain);+ for (let i = 0; i < 205; i++) bareFinish(Date.now() - 3_600_000 + i);+ const next = accountTask(GPU_WORKFLOW);+ expect(pool.claimableNow(workerRow(plain))).toBe(1);+ expect(claim(plain)?.id).toBe(next);+ });++ it("light CPU work has its lane's run limits in a CPU slot too, and a finishing job its lane's run ceiling, which the owner sets", async () => {+ const { saveQueueSettings, QUEUE_DEFAULTS } = await import("@/server/queue-settings");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ const fin = modelFinish();+ expect(claim(w, "cpu")).toMatchObject({ id: fin, runLimitMs: 2700 * 1000 });+ tasks.endTask(fin, "canceled");+ saveQueueSettings({ ...QUEUE_DEFAULTS, runCeilingS: { default: 2700, lanes: { small: 3600 } } });+ try {+ const later = modelFinish();+ expect(claim(w, "cpu")).toMatchObject({ id: later, runLimitMs: 3600 * 1000 });+ tasks.endTask(later, "canceled");+ // Light CPU work given back once for running past its limit gets its lane's whole ceiling next, as on the GPU's slot.+ const cpu = ownerTask(CPU_WORKFLOW);+ expect(claim(w, "cpu")?.id).toBe(cpu);+ tasks.report(row(cpu), { event: "give-back", why: "run-limit" }, () => ({ error: "unused" }));+ expect(claim(w, "cpu")).toMatchObject({ id: cpu, runLimitMs: pool.runLimitMs(null, row(cpu).lane) });+ } finally {+ saveQueueSettings(QUEUE_DEFAULTS);+ }+ });++ it("each slot of a worker claims on its own count: two idle slots asking once a second are never turned away", async () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const ask = (slot?: "cpu") => api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "worker", running: [], ...(slot && { slot }) }) });+ for (let i = 0; i < 60; i++) {+ expect((await ask()).status).toBe(204);+ expect((await ask("cpu")).status).toBe(204);+ }+ // Each slot's own limit still holds.+ expect((await ask()).status).toBe(429);+ expect((await ask("cpu")).status).toBe(429);+ });++ it("after a claim that found nothing, a worker's slot asks again only a few seconds on, sooner while a person's job waits for it", async () => {+ const { claimDue, CLAIM_GAP_MS, IDLE_CLAIM_MS } = await import("../bin/lib/worker/run.mjs");+ expect(IDLE_CLAIM_MS).toBeGreaterThanOrEqual(2000);+ // Before any claim, and after a job: at once.+ expect(claimDue(1000, -Infinity)).toBe(true);+ const missed = 1000;+ expect(claimDue(missed + IDLE_CLAIM_MS - 1, missed)).toBe(false);+ expect(claimDue(missed + IDLE_CLAIM_MS, missed)).toBe(true);+ // A person's job waits: sooner, yet never once a second while the beat keeps saying so.+ expect(CLAIM_GAP_MS).toBeGreaterThan(1000);+ expect(claimDue(missed + 1000, missed, 1)).toBe(false);+ expect(claimDue(missed + CLAIM_GAP_MS, missed, 1)).toBe(true);+ // A loop that ticks every second, with two idle slots and a beat that always says a job waits: well under the+ // studio's 60 claims a minute for each slot.+ let gpu = -Infinity;+ let cpu = -Infinity;+ const claims = { gpu: 0, cpu: 0 };+ for (let t = 0; t < 60_000; t += 1000) {+ if (claimDue(t, gpu, 1)) {+ claims.gpu++;+ gpu = t;+ }+ if (claimDue(t, cpu)) {+ claims.cpu++;+ cpu = t;+ }+ }+ expect(claims.gpu).toBeLessThanOrEqual(40);+ expect(claims.cpu).toBeLessThanOrEqual(20);+ });+});++// ---------------------------------------------------------------------------+// Finishing jobs: once, with their run, and for no longer than its wait++/** A small PNG (1 by 1, whole and well formed). */+const smallPng = (): Buffer =>+ Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8ffffff7f0009fb03fd2a86e38a0000000049454e44ae426082", "hex");++/** An account's camera path step, queued as the studio queues it (its photo and depth staged as the account's). */+function pathFinish(photo = smallPng()) {+ const gid = generation(accountId, "image-to-video");+ const keys = finish.pathKeys([+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ]);+ const id = finish.queueFinish({+ kind: "path",+ generationId: gid,+ account: accountId,+ step: 0,+ inputs: [+ { slot: "photo", data: photo, contentType: photo[0] === 0xff ? "image/jpeg" : "image/png", name: "photo" },+ { slot: "depth", data: smallPng(), contentType: "image/png", name: "depth.png" },+ ],+ settings: { keys, frames: 9, fps: 16 },+ });+ return { id, gid };+}++describe("finishing jobs and their run", () => {+ it("are queued once for a run (and step), however often they are asked", () => {+ const gid = generation(accountId, "image-to-3d");+ const queue = () => finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: Buffer.from("glTF fake model bytes"), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });+ const a = queue();+ expect(queue()).toBe(a);+ expect(db().prepare("SELECT COUNT(*) FROM relay_tasks WHERE generation_id = ?").pluck().get(gid)).toBe(1);+ // One that was stopped makes room for another.+ tasks.endTask(a, "canceled");+ expect(queue()).not.toBe(a);+ });++ it("a canceled run's finish and a deleted run's camera path end at once, with their files, and no CPU slot gets them", async () => {+ const generations = await import("@/server/generations");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d", "path"] } });+ // A 3D finish waiting in line; its run is canceled.+ const fin = modelFinish();+ const gid = row(fin).generation_id;+ db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify({ finishing: true }), gid);+ expect(tasks.inputsOf(fin)).toHaveLength(1);+ await generations.cancelGeneration(gid);+ expect(row(fin).state).toBe("canceled");+ expect(tasks.inputsOf(fin)).toHaveLength(0);+ expect(claim(w, "cpu")).toBeNull();+ // A camera path a CPU slot already runs; its run is deleted. The CPU slot hears the stop in its next report.+ const path = pathFinish();+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(path.id);+ tasks.report(row(path.id), { event: "sent", promptId: c.promptId }, () => ({ error: "unused" }));+ generations.deleteGeneration(path.gid);+ expect(row(path.id).state).toBe("canceled");+ expect(tasks.inputsOf(path.id)).toHaveLength(0);+ expect(tasks.report(row(path.id), { event: "running", value: 5, max: 100 }, () => ({ error: "unused" }))).toMatchObject({ stop: true });+ expect(claim(w, "cpu", [path.id])).toBeNull();+ });++ it("wait for a CPU slot as long as their run may wait in line; a 3D model whose finish never came keeps its raw GLB", async () => {+ const { saveFile } = await import("@/server/storage");+ // Its run's own wait, else this install's.+ const fin = modelFinish();+ expect(row(fin).not_after).toBeGreaterThan(Date.now() + pool.poolWaitMs() - 60_000);+ const gid = generation(accountId, "image-to-3d");+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify({ account: accountId, place: "pool", waitMs: 120_000 }), gid);+ const raw = saveFile({ data: Buffer.from("glTF raw model"), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const t = finish.finishTask(gid, "model3d")!;+ expect(t.not_after).toBeGreaterThan(Date.now() + 60_000);+ expect(t.not_after).toBeLessThanOrEqual(Date.now() + 120_000);+ // While it waits, the run's place in line is the finish's.+ expect(pool.queueOfGeneration(gid)?.place).toBeGreaterThanOrEqual(1);+ // No CPU slot took it in time: it ends, and the run keeps its model as it is.+ db().prepare("UPDATE relay_tasks SET not_after = ? WHERE id = ?").run(Date.now() - 1, t.id);+ pool.sweepPool();+ expect(row(t.id).state).toBe("failed");+ const deadline = Date.now() + 10_000;+ while (!finished && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));+ const kept = finished as unknown as import("@/lib/catalog/types").OutputFile[];+ expect(kept[0]).toMatchObject({ assetId: raw.id, meta: { finish: { error: expect.stringContaining("kept as it is") } } });+ finish.stopWorkerFinish(gid);+ });++ it("count only a CPU slot heard from lately, on a worker built for this studio's catalog", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] }, catalogVersion: "e".repeat(64) });+ expect(finish.workersFinish("model3d")).toBe(false);+ beat(w, { cpuSlot: { finishes: ["model3d"] }, protocol: 2 });+ expect(finish.workersFinish("model3d")).toBe(false);+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ expect(finish.workersFinish("model3d")).toBe(true);+ expect(finish.workersFinish("path")).toBe(false);+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 11 * 60_000, w.id);+ expect(finish.workersFinish("model3d")).toBe(false);+ });+});++describe("CPU work is never metered as GPU time", () => {+ it("a 3D run's settle carries its GPU job's time only, never its finish's, and a lane's typical run leaves finishes out", async () => {+ const { queueReports } = await import("@/server/billing-outbox");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ const gid = generation(accountId, "image-to-3d");+ const graph = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/cpu-slot" } } };+ const gpu = tasks.createTask({ principal: `acct:${accountId}`, generationId: gid, graph, workflowId: GPU_WORKFLOW, pool: pool.poolFields(GPU_WORKFLOW, { account: accountId }) }).id;+ const done = () => ({ wanted: [], outputs: [], budget: 0 });+ const g = claim(w)!;+ expect(g.id).toBe(gpu);+ tasks.report(row(gpu), { event: "sent", promptId: g.promptId }, done);+ tasks.report(row(gpu), { event: "finished", entry: { status: { status_str: "success" }, outputs: {} }, execMs: 1000, device: "Test GPU" }, done);+ const fin = finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: Buffer.from("glTF fake model bytes"), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(fin);+ tasks.report(row(fin), { event: "sent", promptId: c.promptId }, done);+ tasks.report(row(fin), { event: "finished", entry: { status: { status_str: "success" }, outputs: {} }, execMs: 30_000, device: "cpu" }, done);+ expect(row(fin).state).toBe("done");+ expect(db().prepare("SELECT exec_ms, device FROM worker_jobs WHERE task_id = ? AND event = 'finished'").get(fin)).toEqual({ exec_ms: null, device: null });+ const now = Date.now();+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${gid}` }), gid);+ queueReports(now);+ const report = JSON.parse(db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").pluck().get(gid) as string) as { gpuMs: number; device: string };+ expect(report).toMatchObject({ gpuMs: 1000, device: "Test GPU" });+ expect(pool.typicalPoolMs("small")).not.toBe(30_000);+ });+});++// ---------------------------------------------------------------------------+// Pictures sent to the workers++describe("an account's pictures leave for a worker without what they carry besides their pixels", () => {+ /** A PNG with a text chunk (after its header). */+ async function pngWithText(text: string) {+ const zlib = await import("node:zlib");+ const sharp = (await import("sharp")).default;+ const png = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).png().toBuffer();+ const data = Buffer.from(`Comment\0${text}`, "latin1");+ const chunk = Buffer.alloc(12 + data.length);+ chunk.writeUInt32BE(data.length, 0);+ chunk.write("tEXt", 4, "latin1");+ data.copy(chunk, 8);+ chunk.writeUInt32BE(zlib.crc32(Buffer.concat([Buffer.from("tEXt", "latin1"), data])), 8 + data.length);+ return Buffer.concat([png.subarray(0, 33), chunk, png.subarray(33)]);+ }++ it("a JPEG keeps only its orientation, a PNG loses its text and a WebP its EXIF, each still the same picture", async () => {+ const { pictureWithoutMetadata } = await import("@/server/media-clean");+ const sharp = (await import("sharp")).default;+ const jpeg = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#c33" } })+ .jpeg()+ .withMetadata({ orientation: 6 })+ .withExif({ IFD0: { Artist: "someone private", Copyright: "a home address" } })+ .toBuffer();+ const clean = pictureWithoutMetadata(jpeg, "image/jpeg")!;+ expect(clean.length).toBe(jpeg.length);+ expect(clean.includes(Buffer.from("someone private"))).toBe(false);+ expect(clean.includes(Buffer.from("a home address"))).toBe(false);+ expect(exifOrientation(clean)).toBe(6);+ expect(orientedImageSize(clean)).toEqual({ width: 20, height: 40 });+ const meta = await sharp(clean).metadata();+ expect(meta.orientation).toBe(6);+ expect([meta.width, meta.height]).toEqual([40, 20]);+ // Upright already: nothing of its EXIF stays.+ const upright = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#c33" } }).jpeg().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const plain = pictureWithoutMetadata(upright, "image/jpeg")!;+ expect(plain.includes(Buffer.from("someone private"))).toBe(false);+ expect((await sharp(plain).metadata()).exif).toBeUndefined();+ const png = await pngWithText("a private note");+ expect((await sharp(png).metadata()).width).toBe(8);+ const cleanPng = pictureWithoutMetadata(png, "image/png")!;+ expect(cleanPng.includes(Buffer.from("a private note"))).toBe(false);+ expect((await sharp(cleanPng).metadata()).width).toBe(8);+ const webp = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).webp().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const cleanWebp = pictureWithoutMetadata(webp, "image/webp")!;+ expect(cleanWebp.includes(Buffer.from("someone private"))).toBe(false);+ expect((await sharp(cleanWebp).metadata()).width).toBe(8);+ // Not a picture it can read where such things live: refused.+ expect(pictureWithoutMetadata(Buffer.from([0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0x00]), "image/jpeg")).toBeNull();+ });++ it("an account's run on the workers stages its picture that way, sized as it shows; its own GPU gets it as it came, sized by its pixels", async () => {+ const { comfyProvider, mediaInfoFor } = await import("@/server/providers/comfyui");+ const hosted = await import("@/server/hosted");+ const sharp = (await import("sharp")).default;+ const sideways = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } })+ .jpeg()+ .withMetadata({ orientation: 6 })+ .withExif({ IFD0: { Artist: "someone private" } })+ .toBuffer();+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const pooled = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(sideways, "image/jpeg", "me.jpg", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ const staged = fs.readFileSync(path.join(dir, "relay", "in", pooled.name));+ expect(staged.length).toBe(sideways.length);+ expect(staged.includes(Buffer.from("someone private"))).toBe(false);+ expect(exifOrientation(staged)).toBe(6);+ expect(pooled.info).toMatchObject({ width: 20, height: 40 });+ // The account's own GPU gets the file as it came, sized by its pixels, as before.+ const own = await onComputer(`acct:${accountId}`, async () => {+ const name = (await comfyProvider.prepareFile!(sideways, "image/jpeg", "me.jpg", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ expect(fs.readFileSync(path.join(dir, "relay", "in", own.name)).equals(sideways)).toBe(true);+ expect(own.info).toMatchObject({ width: 40, height: 20 });+ });++ it("a camera path's photo goes to the worker the same way", async () => {+ const sharp = (await import("sharp")).default;+ const photo = await sharp({ create: { width: 16, height: 12, channels: 3, background: "#36c" } }).jpeg().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const { id } = pathFinish(photo);+ const staged = tasks.inputsOf(id).map((i) => fs.readFileSync(path.join(dir, "relay", "in", i.name)));+ expect(staged).toHaveLength(2);+ expect(staged.some((b) => b.includes(Buffer.from("someone private")))).toBe(false);+ expect(staged[0].length).toBe(photo.length);+ });+});++// ---------------------------------------------------------------------------+// A finish's results are stored once, and a 3D model waits for its check++/** The smallest binary glTF with every part inside it. */+function tinyGlb(): Buffer {+ let j = Buffer.from(JSON.stringify({ asset: { version: "2.0" } }));+ j = Buffer.concat([j, Buffer.alloc((4 - (j.length % 4)) % 4, 0x20)]);+ const header = Buffer.alloc(20);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + j.length, 8);+ header.writeUInt32LE(j.length, 12);+ header.writeUInt32LE(0x4e4f534a, 16);+ return Buffer.concat([header, j]);+}++/** A finishing job a worker finished: its one result file back, as `role`. */+function finishedOnWorker(id: string, role: string, data: Buffer, contentType: string) {+ const file = tasks.outputFile(id, 0);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, data);+ db()+ .prepare("UPDATE relay_tasks SET state = 'done', result_json = ?, received_json = ?, finished_at = ? WHERE id = ?")+ .run(JSON.stringify([{ files: [{ role, n: 0 }], stats: {} }]), JSON.stringify([{ n: 0, bytes: data.length, total: data.length, done: true, contentType }]), Date.now(), id);+}++/** Wait for `fn` to give something. */+async function until<T>(fn: () => T, ms = 15_000): Promise<NonNullable<T>> {+ const end = Date.now() + ms;+ for (;;) {+ const v = fn();+ if (v) return v as NonNullable<T>;+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);+ await new Promise((r) => setTimeout(r, 100));+ }+}++describe("a finish's results are kept once", () => {+ it("a 3D model's web GLB is stored once, however many app processes look at the finished job", async () => {+ const { saveFile } = await import("@/server/storage");+ expect(finish.glbSelfContained(tinyGlb())).toBe(true);+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ const id = finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: false } });+ finishedOnWorker(id, "web", tinyGlb(), "model/gltf-binary");+ const got: import("@/lib/catalog/types").OutputFile[][] = [];+ // Each look as another app process makes it (a deploy's overlap): a watch of its own, the same finished job.+ for (let i = 0; i < 2; i++) finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void got.push(o) });+ expect(got).toHaveLength(2);+ expect(got[1]).toEqual(got[0]);+ expect((got[0][0].meta as { web?: string }).web).toBeTruthy();+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'model-web.glb'").pluck().get(gid)).toBe(1);+ });++ it("a camera path's clip is stored once, however many app processes look at the finished job", async () => {+ const { runAsTenant } = await import("@/server/tenant");+ const { saveFile } = await import("@/server/storage");+ const photo = saveFile({ data: smallPng(), contentType: "image/png", name: "still.png", source: "upload", accountId });+ const depth = saveFile({ data: smallPng(), contentType: "image/png", name: "depth.png", source: "derived", accountId });+ const keys = [+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ];+ const gid = generation(accountId, "image-to-video");+ const step = () => runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }));+ expect(await step()).toEqual({ state: "waiting" });+ finishedOnWorker(finish.finishTask(gid, "path")!.id, "path", Buffer.from("....ftypisom path clip"), "video/mp4");+ const [a, b] = await Promise.all([step(), step()]);+ expect(a.state).toBe("done");+ expect(b).toEqual(a);+ expect(await step()).toEqual(a);+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").pluck().get(gid)).toBe(1);+ });+});++describe("pictures for a worker that this server can't blank in place", () => {+ /** A GIF with a comment in it. */+ async function gifWithComment(text: string) {+ const sharp = (await import("sharp")).default;+ const gif = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#c63" } }).gif().toBuffer();+ const packed = gif[10];+ const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0);+ const data = Buffer.from(text, "latin1");+ return Buffer.concat([gif.subarray(0, at), Buffer.from([0x21, 0xfe, data.length]), data, Buffer.from([0]), gif.subarray(at)]);+ }++ it("are made again from their pixels here, so nothing besides them leaves: a GIF's comment, a camera path's GIF photo", async () => {+ const { comfyProvider, mediaInfoFor } = await import("@/server/providers/comfyui");+ const { pictureWithoutMetadata } = await import("@/server/media-clean");+ const hosted = await import("@/server/hosted");+ const sharp = (await import("sharp")).default;+ const gif = await gifWithComment("a private note");+ expect((await sharp(gif).metadata()).width).toBe(8);+ expect(pictureWithoutMetadata(gif, "image/gif")).toBeNull();+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const pooled = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(gif, "image/gif", "me.gif", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ const staged = fs.readFileSync(path.join(dir, "relay", "in", pooled.name));+ expect(staged.subarray(1, 4).toString()).toBe("PNG");+ expect(staged.includes(Buffer.from("a private note"))).toBe(false);+ expect(pooled.info).toMatchObject({ width: 8, height: 6 });+ // A camera path's photo the same way.+ const { runAsTenant } = await import("@/server/tenant");+ const { saveFile } = await import("@/server/storage");+ const photo = saveFile({ data: gif, contentType: "image/gif", name: "still.gif", source: "upload", accountId });+ const depth = saveFile({ data: smallPng(), contentType: "image/png", name: "depth.png", source: "derived", accountId });+ const gid = generation(accountId, "image-to-video");+ const keys = [+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ];+ expect(await runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }))).toEqual({ state: "waiting" });+ const files = tasks.inputsOf(finish.finishTask(gid, "path")!.id).map((i) => fs.readFileSync(path.join(dir, "relay", "in", i.name)));+ expect(files[0].subarray(1, 4).toString()).toBe("PNG");+ expect(files.some((b) => b.includes(Buffer.from("a private note")))).toBe(false);+ });+});++describe("a 3D model finished on a worker, for a run whose outputs are checked first", () => {+ it("waits for the check, as any run's outputs do, and never shows before it", async () => {+ const generations = await import("@/server/generations");+ const { saveFile } = await import("@/server/storage");+ process.env.FUOBE_MODERATION_URL = "http://127.0.0.1:9/check";+ const gid = `cpu-slot-checked-3d-${++gens}`;+ try {+ const now = Date.now();+ const raw = saveFile({ data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d", contentType: "model/gltf-binary", assetId: raw.id }];+ // Its GPU job is done and its outputs are stored; the 3D finish comes next.+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, external_meta_json, created_at, updated_at) VALUES (?, 'image-to-3d', 'oss-pixal3d', 'open', 'comfyui', 'image-to-3d', 'model3d', 'running', ?, ?, 'job-1', ?, ?, ?)",+ )+ .run(gid, JSON.stringify({ account: accountId, place: "pool", checkOutputs: true }), JSON.stringify(outputs), JSON.stringify({ finishing: true }), now, now);+ generations.ensureRunner();+ await globalThis.__fuobeRunner?.tick();+ const t = await until(() => finish.finishTask(gid, "model3d"));+ // Its finish comes back (here: no CPU slot took it in time, so the model is kept as it is).+ db().prepare("UPDATE relay_tasks SET not_after = ? WHERE id = ?").run(Date.now() - 1, t.id);+ pool.sweepPool();+ const g = await until(() => {+ const r = db().prepare("SELECT status, stage FROM generations WHERE id = ?").get(gid) as { status: string; stage: string | null };+ return r.stage === "checking" && r;+ });+ expect(g).toMatchObject({ status: "running", stage: "checking" });+ expect(db().prepare("SELECT held FROM assets WHERE id = ?").pluck().get(raw.id)).toBe(1);+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ finish.stopWorkerFinish(gid);+ const r = globalThis.__fuobeRunner;+ if (r) {+ clearInterval(r.timer);+ if (r.fastTimer) clearInterval(r.fastTimer);+ globalThis.__fuobeRunner = undefined;+ }+ }+ });+});diff --git a/tests/job-tickets.test.ts b/tests/job-tickets.test.tsindex 19be3d88..74bae0fa 100644--- a/tests/job-tickets.test.ts+++ b/tests/job-tickets.test.ts@@ -253,6 +253,21 @@ describe("the PC's ceiling", () => {expect(await run({ maxMegapixels: s.size.megapixels / 2 }, { ...s.ticket, size: { ...s.ticket.size, megapixels: 0 } })).toMatchObject({ ok: false, reason: "outside-ceiling" });});+ it("a workflow that picks its graph at run time (a join of clips) is held to the graph it picks, as the studio offers it", async () => {+ const s = await studioSide({ endpoint: "video-concat-{n}", op: "concat" as Operation, kind: "video" }, "ceil-gen-2");+ expect(s.ticket.workflowId).toBe("video-concat-{n}");+ const lanes: Record<string, string> = { "video-concat-2": "join-lane-2", "video-concat-3": "join-lane-3" };+ const run = (ceiling: Parameters<typeof ceilingProblem>[0]) => composeTicket({ ticket: s.ticket, generationId: "ceil-gen-2", inputs: s.inputs }, { catalog, catalogVersion: VERSION, ceiling, laneOf: (id) => lanes[id] ?? "small" });+ // The two clips make the two-clip graph: a ceiling that names it, or its lane, lets it run.+ expect(await run({ workflows: ["video-concat-2"] })).toMatchObject({ ok: true, workflowId: "video-concat-2" });+ expect(await run({ lanes: ["join-lane-2"] })).toMatchObject({ ok: true });+ // One that names only another graph, or another lane, refuses it (after composing, by the graph it came out as).+ expect(await run({ workflows: ["video-concat-3"] })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ expect(await run({ lanes: ["small"] })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ // Its sizes are held before composing as for any ticket.+ expect(await run({ workflows: ["video-concat-2"], maxSeconds: 0.5 })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ });+it("a ceiling is kept the same way on the worker (worker.json) and in the studio", () => {const raw = { lanes: ["small", "0123456789ab", "nope"], workflows: ["selftest-image", "../x"], maxMegapixels: 4, maxSeconds: 0, maxOutputs: 2.7, other: true };expect(ceilingOf(raw)).toEqual(cleanCeiling(raw));diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex f1844187..f16dfb15 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -120,7 +120,7 @@ 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 = ?, catalog_version = ? WHERE id = ?")+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 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;}@@ -710,7 +710,7 @@ describe("graphs and results for the workers", () => {});describe("nothing of a run on the workers goes to a ComfyUI address", () => {- it("an account's picture is kept for its task as it came (the worker makes it again from its pixels), and never decoded here", async () => {+ it("an account's picture is kept for its task with only its pixels' parts (the worker makes it again from its pixels), and never decoded here", async () => {const sharp = (await import("sharp")).default;const jpeg = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#c33" } }).jpeg()@@ -723,7 +723,12 @@ describe("nothing of a run on the workers goes to a ComfyUI address", () => {expect(row).toEqual({ principal: `acct:${accountId}`, content_type: "image/jpeg" });const fs = await import("node:fs");const path = await import("node:path");- expect(fs.readFileSync(path.join(dir, "relay", "in", staged)).equals(jpeg)).toBe(true);+ // Never decoded here: the same JPEG, byte for byte the same size, with what it carried besides its pixels blanked.+ const kept = fs.readFileSync(path.join(dir, "relay", "in", staged));+ expect(kept.length).toBe(jpeg.length);+ expect(kept.subarray(0, 2).equals(jpeg.subarray(0, 2))).toBe(true);+ expect(kept.includes(Buffer.from("private note"))).toBe(false);+ expect((await sharp(kept).metadata()).exif).toBeUndefined();// Its size as it shows (turned by its orientation), as the worker's upright copy has it.expect(hosted.runOnPool(accountId, () => mediaInfoFor(staged))).toMatchObject({ width: 8, height: 8 });// Something that isn't a picture is never kept as one.diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex fc03d0d6..c0bb0006 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -98,16 +98,23 @@ const poolRuns = (id: string) =>const ownRuns = (id: string) =>(db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') IS NULL").get(id) as { n: number }).n;+/** A worker as the owner adds it, connected once: it said its build (one that takes this studio's job tickets). */function standInWorker() {const w = pool.addWorker(`stand-in-${++n}`);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 });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 = ?, protocol = 3 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;}+/** A worker's beat, as its program sends it, built for this catalog version. */+function beatWith(w: { id: string }, version: string | null) {+ const row = db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;+ pool.workerBeat(row, pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: version }));+}+const withBilling = (policy: Record<string, unknown> = {}) => {process.env.FUOBE_BILLING_URL = fake.url;process.env.FUOBE_BILLING_TOKEN = "test-billing-token";@@ -787,6 +794,34 @@ describe("the price check before Run and the run itself", async () => {}});+ it("while every worker that could run it is built from the catalog before the studio's update, Run is off with plain words, never a run that waits for nothing", async () => {+ const a = account();+ const acct = auth.accountById(a.id)!;+ withBilling({ limits: NO_LIMITS });+ const req = { ...IMAGE, account: a.id } as never;+ const endpoint = getModel(IMAGE.modelId)!.routes!.find((r) => r.provider === "comfyui")!.endpoint;+ beatWith(worker, catalogVersion());+ expect((await hostedRun.decidePlace(acct, req, undefined)).kind).toBe("pool");+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(1);+ // The studio was updated; its only worker not yet.+ beatWith(worker, "e".repeat(64));+ const before = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();+ const run = await hostedRun.decidePlace(acct, req, undefined);+ expect(run.kind).toBe("refuse");+ expect(run.kind === "refuse" && run.refusal).toMatchObject({ status: 503, body: { code: "busy", error: HOSTED_WORDS.busy } });+ expect((await hostedRun.poolQuote(acct, req, undefined))?.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.busy });+ expect((await hostedRun.poolQuote(null, IMAGE as never, undefined))?.quote).toMatchObject({ allowed: false, text: HOSTED_GUEST_WORDS.busy });+ // Its place in line and the workers there count only a worker that takes the run now.+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(0);+ expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(before);+ // The owner's own jobs still go to it: a worker built from another catalog takes those.+ expect(pool.workersCanRun(endpoint)).toBe(true);+ // Updated: Run is on again.+ beatWith(worker, catalogVersion());+ expect((await hostedRun.poolQuote(acct, req, undefined))?.quote.allowed).toBe(true);+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(1);+ });+it("a guest's price check plans every step of a chain too, and words its refusals for someone with no Settings yet", async () => {withBilling({ limits: NO_LIMITS });expect((await hostedRun.poolQuote(null, EFFECT as never, undefined))?.quote.allowed).toBe(true);diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex 348d8b76..89d77c6f 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -99,9 +99,10 @@ function standInWorker(name = "stand-in") {const w = pool.addWorker(name);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 });+ // Connected once: it said its build (one that takes this studio's job tickets).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 = ?, protocol = 3 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;}type WorkerRow = import("@/server/computer/workers").WorkerRow;diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex fe105d7e..ea9c5306 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -56,6 +56,7 @@ const { resetRates } = await import("@/server/rate");const { setSetting } = await import("@/server/settings");const { getGeneration, ensureRunner } = await import("@/server/generations");const pool = await import("@/server/computer/pool");+const { catalogVersion } = await import("@/server/computer/catalog-version");const tasks = await import("@/server/computer/tasks");const billing = await import("@/server/billing");const outbox = await import("@/server/billing-outbox");@@ -149,9 +150,10 @@ function standInWorker(name = "stand-in", o: { paused?: boolean; lanes?: string[const w = pool.addWorker(name);const lanes = o.lanes ?? allLanes(loadIndex(), sha).map((l) => l.lane);pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });+ // Connected once: it said its build (one that takes this studio's job tickets).db()- .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")- .run(JSON.stringify({ lanes, 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 = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes, workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);return w;}diff --git a/tests/recovery-worker.test.ts b/tests/recovery-worker.test.tsindex 920782c3..c54c6edd 100644--- a/tests/recovery-worker.test.ts+++ b/tests/recovery-worker.test.ts@@ -164,7 +164,8 @@ describe("the worker program's recovery (accounts' runs, end to end)", () => {const w = studio.pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);const lanes = studio.lanes();studio.pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });- studio.db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes, workflows: studio.workflows() }), JSON.stringify({ vramBytes: 32 * 2 ** 30 }), w.id);+ // Connected once: it said its build (one that takes this studio's job tickets).+ studio.db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?").run(JSON.stringify({ lanes, workflows: studio.workflows() }), JSON.stringify({ vramBytes: 32 * 2 ** 30 }), program.catalogVersion, w.id);return w;}diff --git a/tests/worker-cpu-slot.test.ts b/tests/worker-cpu-slot.test.tsindex c9a34af3..484a9dcd 100644--- a/tests/worker-cpu-slot.test.ts+++ b/tests/worker-cpu-slot.test.ts@@ -380,6 +380,67 @@ describe("the 3D finish on the worker", () => {expect(db().prepare("SELECT account_id FROM assets WHERE id = ?").pluck().get(clip.assetId)).toBe(accountId);});+ it("a turntable that didn't come back leaves the account's words on the model, never the worker's", async () => {+ const { ACCOUNT_TURNTABLE } = await import("@/server/model3d-finish");+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const id = finish.finishTask(gid, "model3d")!.id;+ // A turntable render that fails, naming things of its PC.+ const failing = path.join(tempDir("fuobe-cpu-slot-turntable-"), "turntable.mjs");+ fs.writeFileSync(failing, 'console.error("no browser at C:/Users/someone-private/browsers/chrome.exe"); process.exit(1);');+ start(w, s, p, { finishers: finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: null, scripts: { turntable: failing } }) });+ const t = await ended(id);+ expect(t.state, t.error ?? "").toBe("done");+ const got = await until(() => finished, 30_000);+ const mesh = got.find((o) => o.kind === "model3d")!;+ const meta = mesh.meta as { web?: string; finish: { turntable: string } };+ expect(meta.web).toBeTruthy();+ expect(meta.finish.turntable).toBe(ACCOUNT_TURNTABLE);+ expect(JSON.stringify(got)).not.toMatch(/someone-private|chrome|browsers/);+ });++ it("a finish its run no longer wants stops on the worker while it runs: the run was deleted", async () => {+ const { deleteGeneration } = await import("@/server/generations");+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: () => {} });+ const id = finish.finishTask(gid, "model3d")!.id;+ // A finish that goes on until it is told to stop, saying how far it got now and then.+ let started = false;+ let stopped = false;+ const slow = {+ kinds: ["model3d"],+ finish: async (_t: unknown, _inputs: unknown, o: { signal: AbortSignal; progress: (f: number) => void }) => {+ started = true;+ for (let i = 0; i < 600 && !o.signal.aborted; i++) {+ o.progress(i / 600);+ await sleep(100);+ }+ stopped = o.signal.aborted;+ return { refused: "finish-failed" };+ },+ };+ start(w, s, p, { finishers: slow });+ await until(() => started, 30_000);+ expect(row(id).state).toBe("running");+ deleteGeneration(gid);+ expect(row(id).state).toBe("canceled");+ // Its next progress report hears the stop, and the finish's processes are stopped at once.+ await until(() => stopped, 15_000);+ await sleep(500);+ expect(s.reports.filter((r) => r.task === id && ["finished", "failed"].includes(String(r.event)))).toEqual([]);+ });+it("the studio keeps an account's 3D model from the workers only as a binary glTF with every part inside it", async () => {const { outputType } = await import("@/server/computer/http");const want = { n: 0, filename: "m.glb", subfolder: "", type: "output" as const, kind: "model3d" as const, maxBytes: 1e6 };@@ -479,8 +540,10 @@ describe("an account's pictures on the worker", () => {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);- // The studio keeps it as it came.- expect(fs.readFileSync(path.join(dir, "relay", "in", picture)).equals(jpeg)).toBe(true);+ // The studio keeps it undecoded, its EXIF blanked.+ const kept = fs.readFileSync(path.join(dir, "relay", "in", picture));+ expect(kept.length).toBe(jpeg.length);+ expect(kept.includes(Buffer.from("private note"))).toBe(false);start(w, s, p);const t = await ended(id);expect(t.state, t.error ?? "").toBe("done");diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.tsindex 39e9f71c..17d49910 100644--- a/tests/worker-tickets.test.ts+++ b/tests/worker-tickets.test.ts@@ -284,6 +284,73 @@ describe("the line hands out tickets inside each PC's ceiling", () => {expect(row(mine.id)).toMatchObject({ state: "waiting", claimed_at: first, requeues: 0 });});+ it("a run that started keeps its claim's time when its worker, back after a restart, refuses its ticket, as an attempt", async () => {+ const w = addWorker();+ beat(w);+ const mine = await accountTask();+ const got = claim(w)!;+ expect(got.id).toBe(mine.id);+ const first = row(mine.id).claimed_at;+ tasks.report(row(mine.id), { event: "sent", promptId: got.promptId }, () => ({ error: "unused" }));+ tasks.report(row(mine.id), { event: "running", value: 1, max: 4 }, () => ({ error: "unused" }));+ // Its wait limit has passed since: it no longer applies to a run that started.+ db().prepare("UPDATE relay_tasks SET not_after = ? WHERE id = ?").run(Date.now() - 60_000, mine.id);+ // The worker starts again (an update), takes its own job back, and its new build refuses the ticket.+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "give-back", why: "update-worker" }, () => ({ error: "unused" }));+ // Not on the claim that took it from the line: an attempt, as any other give-back.+ expect(row(mine.id)).toMatchObject({ state: "waiting", claimed_at: first, requeues: 1 });+ pool.sweepPool();+ expect(row(mine.id)).toMatchObject({ state: "waiting", claimed_at: first });+ // A worker that refuses it on the claim that took it from the line, before anything ran, leaves that claim's time+ // as it was too, at no cost.+ const b = addWorker();+ beat(b);+ 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: 1 });+ });++ it("refusals that come after anything ran count as attempts, so they can never keep a run in line for good", async () => {+ const w = addWorker();+ beat(w);+ const mine = await accountTask();+ for (let i = 0; i < pool.MAX_ATTEMPTS; i++) {+ // Each time a build of its own it says it has (its refusal is then never the same one twice).+ beat(w, { ceiling: { maxOutputs: 4 + i } });+ const got = claim(w)!;+ expect(got.id).toBe(mine.id);+ tasks.report(row(mine.id), { event: "sent", promptId: got.promptId }, () => ({ error: "unused" }));+ tasks.report(row(mine.id), { event: "give-back", why: "outside-ceiling" }, () => ({ error: "unused" }));+ }+ expect(row(mine.id)).toMatchObject({ state: "failed", error: pool.GAVE_BACK_WORDS });+ });++ it("a job larger than every PC may ever make is refused before it is queued, the owner's and an account's alike", async () => {+ const { NO_WORKER_FOR_SIZE, POOL_TOO_BIG } = await import("@/server/providers/comfyui");+ const w = addWorker();+ // The picture is about 1.9 MP; the only PC makes at most 1 MP.+ beat(w, { ceiling: { maxMegapixels: 1 } });+ expect(pool.workersCanRun("selftest-image")).toBe(true);+ expect(pool.workersCanRun("selftest-image", { size: { megapixels: 1.9, seconds: 0, outputs: 1 } })).toBe(false);+ const before = db().prepare("SELECT COUNT(*) FROM relay_tasks").pluck().get() as number;+ await expect(accountTask()).rejects.toThrow(POOL_TOO_BIG);+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const ownerJob = async () => {+ const name = (await comfyProvider.prepareFile!(PICTURE, "image/png", "me.png", route))!;+ return comfyProvider.submit({ route, input: { images: [name], seed: 5 }, generationId: generation(null), model: getModel("oss-selftest-image") } as never);+ };+ await expect(ownerJob()).rejects.toThrow(NO_WORKER_FOR_SIZE);+ // Nothing waits in line for nothing.+ expect(db().prepare("SELECT COUNT(*) FROM relay_tasks").pluck().get()).toBe(before);+ // A PC that makes it: both go in line.+ beat(w, { ceiling: { maxMegapixels: 4 } });+ const mine = await accountTask();+ expect(row(mine.id).state).toBe("waiting");+ const own = await ownerJob();+ expect(row(String((own.meta as { relay: string }).relay)).state).toBe("waiting");+ });+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();@@ -312,6 +379,97 @@ describe("the line hands out tickets inside each PC's ceiling", () => {expect(await refreshTickets()).toEqual({ refreshed: 0, ended: 0 });expect(claim(w)?.id).toBe(mine.id);});++ it("while a deploy's two app processes share the line, only the newest makes tickets again, and an older one never ends a run", async () => {+ const { refreshTickets } = await import("@/server/computer/ticket-refresh");+ db().prepare("DELETE FROM catalog_processes").run();+ try {+ const w = addWorker();+ beat(w);+ const mine = await accountTask();+ // A ticket the older process's catalog has no workflow for: only the newest catalog knows it.+ const newer = await accountTask();+ db().prepare("UPDATE relay_tasks SET ticket_json = ? WHERE id = ?").run(JSON.stringify({ ...JSON.parse(row(newer.id).ticket_json!), workflowId: "a-workflow-only-the-new-catalog-has" }), newer.id);+ const was = { mine: row(mine.id), newer: row(newer.id) };+ const t0 = Date.now();+ // The new process (this studio's version) started a minute after the old one, and says so.+ expect(await refreshTickets({ version: VERSION, startedAt: t0, now: t0 })).toEqual({ refreshed: 0, ended: 0 });+ // The old one, still serving claims, leaves both tickets as they are: never made for its older catalog, never ended.+ expect(await refreshTickets({ version: OTHER, startedAt: t0 - 60_000, now: t0 + 1000 })).toEqual({ refreshed: 0, ended: 0 });+ for (const id of [mine.id, newer.id]) {+ const now = row(id);+ const before = id === mine.id ? was.mine : was.newer;+ expect(now).toMatchObject({ state: "waiting", ticket_json: before.ticket_json, needs_json: before.needs_json });+ }+ // A worker built for the new catalog still takes the run.+ expect(claim(w)?.id).toBe(mine.id);+ tasks.endTask(mine.id, "canceled");+ // A rollback: a process of the older version that started later is the newest now, and only it makes tickets again.+ const back = await accountTask();+ expect(await refreshTickets({ version: OTHER, startedAt: t0 + 60_000, now: t0 + 61_000 })).toMatchObject({ refreshed: 1 });+ expect(JSON.parse(row(back.id).ticket_json!).catalogVersion).toBe(OTHER);+ expect(await refreshTickets({ version: VERSION, startedAt: t0, now: t0 + 62_000 })).toEqual({ refreshed: 0, ended: 0 });+ expect(JSON.parse(row(back.id).ticket_json!).catalogVersion).toBe(OTHER);+ // A process that went quiet for minutes has stopped: the one left makes them again for its catalog.+ expect(await refreshTickets({ version: VERSION, startedAt: t0, now: t0 + 61_000 + 6 * 60_000 })).toMatchObject({ refreshed: 1 });+ expect(JSON.parse(row(back.id).ticket_json!).catalogVersion).toBe(VERSION);+ } finally {+ db().prepare("DELETE FROM catalog_processes").run();+ }+ });++ it("a ticket made again for a new catalog gets the files its graph makes made again, and its lane and needs from the new catalog", async () => {+ const { refreshTickets } = await import("@/server/computer/ticket-refresh");+ db().prepare("DELETE FROM catalog_processes").run();+ try {+ const w = addWorker();+ beat(w);+ // A palette transfer: the composer makes the palette's swatch picture itself, and the ticket names it.+ const gid = generation(accountId);+ const route = { provider: "comfyui", endpoint: "palette-transfer-image", op: "color-match" } as never;+ const sent = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(PICTURE, "image/png", "me.png", route))!;+ return comfyProvider.submit({ route, input: { images: [name], palette: ["#112233", "#ddeeff", "#884422"], seed: 7 }, generationId: gid, model: getModel("oss-palette-image") } as never);+ });+ const id = String((sent.meta as { relay: string }).relay);+ const fresh = row(id);+ const ticket = JSON.parse(fresh.ticket_json!) as import("@/lib/job-ticket").JobTicket;+ const made = ticket.inputs.find((i) => i.slot.startsWith("made."))!;+ expect(made).toBeTruthy();+ const want = { lane: fresh.lane, needs: JSON.parse(fresh.needs_json!) };+ // As it was before an update that changed how the swatch is drawn: other bytes, staged under its name, another+ // catalog, and a lane and needs from that catalog.+ const old = tasks.inputsOf(id).find((i) => i.name === made.name)!;+ const oldBytes = Buffer.from("a swatch drawn by an older composer");+ fs.writeFileSync(path.join(dir, "relay", "in", made.name), oldBytes);+ db().prepare("UPDATE relay_inputs SET sha256 = ? WHERE name = ?").run(sha(oldBytes.toString()), old.name);+ const before = { ...ticket, catalogVersion: OTHER, inputs: ticket.inputs.map((i) => (i.name === made.name ? { ...i, sha256: sha(oldBytes.toString()) } : i)) };+ db()+ .prepare("UPDATE relay_tasks SET ticket_json = ?, needs_json = ?, lane = ? WHERE id = ?")+ .run(JSON.stringify(before), JSON.stringify({ workflowId: "palette-transfer-image", files: [], packs: [], minVramBytes: 0, catalogVersion: OTHER }), "small", id);+ expect(claim(w)).toBeNull();+ expect(await refreshTickets()).toEqual({ refreshed: 1, ended: 0 });+ const after = row(id);+ const next = JSON.parse(after.ticket_json!) as import("@/lib/job-ticket").JobTicket;+ const swatch = next.inputs.find((i) => i.slot === made.slot)!;+ // The swatch as this catalog draws it, staged as the task's in place of the old one.+ expect(swatch.sha256).toBe(made.sha256);+ expect(tasks.inputsOf(id).map((i) => i.name)).toContain(swatch.name);+ if (swatch.name !== made.name) expect(fs.existsSync(path.join(dir, "relay", "in", made.name))).toBe(false);+ expect(crypto.createHash("sha256").update(fs.readFileSync(path.join(dir, "relay", "in", swatch.name))).digest("hex")).toBe(made.sha256);+ // Its lane and what it needs, from this catalog; its place as it was.+ expect(after.lane).toBe(want.lane);+ expect(JSON.parse(after.needs_json!)).toEqual(want.needs);+ expect(after.rank_at).toBe(fresh.rank_at);+ // A worker built for this catalog takes it, and composes the very same swatch.+ const got = claim(w)!;+ expect(got.id).toBe(id);+ const out = await composer.composeTicket({ ticket: got.ticket, generationId: gid, inputs: tasks.inputsOf(id).map((i) => ({ name: i.name, sha256: i.sha256 })) }, { catalog: { has: () => true, get: (await import("@/server/providers/comfyui")).getWorkflow } as never, catalogVersion: VERSION });+ expect(out.ok, out.ok ? "" : out.detail).toBe(true);+ } finally {+ db().prepare("DELETE FROM catalog_processes").run();+ }+ });});// ---------------------------------------------------------------------------@@ -373,7 +531,7 @@ afterEach(async () => {});/** 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 } = {}) {+function start(w: W, s: Studio, p: Pc, o: { ceiling?: unknown; acceptGraphs?: boolean; pictures?: boolean } = {}) {const ctrl = new AbortController();const cfg = {site: SITE,@@ -406,6 +564,7 @@ function start(w: W, s: Studio, p: Pc, o: { ceiling?: unknown; acceptGraphs?: bocomposer,catalogVersion: VERSION,allLanes,+ ...(o.pictures === false && { canCleanPictures: false }),});const r = { ctrl, done };running.push(r);@@ -485,6 +644,51 @@ describe("the worker program composes tickets and keeps to its PC's ceiling", ()expect(prompts(p)).toBe(0);});+ it("a studio older than job tickets, whose graphs name no class, still gets the owner's own jobs run", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const own = ownerTask();+ // As such a studio answers: no catalog version in its beat answer, and no class on its jobs.+ s.rewrite = (q, body) => {+ if (q === "/api/gpu/computer/beat") {+ const b = body as { worker?: Record<string, unknown> };+ if (b.worker) delete b.worker.catalogVersion;+ return b;+ }+ if (q !== "/api/gpu/computer/claim") return body;+ const { task } = body as { task: Record<string, unknown> };+ const { class: _c, ...rest } = task;+ void _c;+ return { task: rest };+ };+ start(w, s, p);+ const t = await ended(own.id);+ expect(t.state, t.error ?? "").toBe("done");+ expect(prompts(p)).toBe(1);+ });++ it("with no picture tool in its checkout, it says an older protocol, so it takes the owner's own jobs and no account's ticket", async () => {+ const { MIN_PROTOCOL, TICKET_PROTOCOL } = pool;+ const { protocolOf, PROTOCOL } = await import("../bin/lib/worker/config.mjs");+ expect(protocolOf(true)).toBe(PROTOCOL);+ expect(protocolOf(false)).toBeLessThan(TICKET_PROTOCOL);+ expect(protocolOf(false)).toBeGreaterThanOrEqual(MIN_PROTOCOL);+ const w = addWorker();+ const s = studio();+ const p = pc();+ const mine = await accountTask();+ const own = ownerTask();+ start(w, s, p, { pictures: false });+ const t = await ended(own.id);+ expect(t.state, t.error ?? "").toBe("done");+ expect(workerRow(w).protocol).toBe(protocolOf(false));+ // The account's run was never offered to it: it waits in line, with no attempt counted.+ expect(row(mine.id)).toMatchObject({ state: "waiting", requeues: 0, claimed_at: null });+ expect(s.reports).not.toContainEqual(expect.objectContaining({ event: "give-back" }));+ expect(p.logs.some((l) => /pnpm install/.test(l))).toBe(true);+ });+it("with acceptGraphs off, the owner's own whole graph is refused too", async () => {const w = addWorker();const s = studio();