Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Merge the worker program's hardening (branch pool-worker)

Adarsh29348236cc5b
diff --cc docs/admin-api.md
index e862ca83,f34c6760..7feb8129
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@@ -37,23 -37,18 +37,23 @@@ Keep the token out of URLs, logs and sh
| `accounts:read` | `GET /api/admin/accounts` (JSON or CSV), `GET /api/admin/accounts/{id}` |
| `accounts:write` | `PATCH /api/admin/accounts/{id}` with `{ "disabled": true \| false }` or `{ "signOut": true }` (its paired ComfyUIs stop too) |
| `accounts:delete` | `DELETE /api/admin/accounts/{id}`: its runs, files and record go. It can't be undone |
-| `runs:read` | `GET /api/admin/generations`: accounts' runs, prompts included (never the owner's own runs) |
+| `runs:read` | `GET /api/admin/generations`: accounts' runs, each one's facts only (when, which model and app, how it ended, how many results). Never the owner's own runs |
| `runs:delete` | `DELETE /api/admin/generations/{id}`: a run still going is canceled first |
-| `outputs:view` | `GET /api/admin/files/{path}`: an account's stored file, held ones too (never the owner's own). Each view is logged |
+| `outputs:view` | `GET /api/admin/files/{path}`: an account's stored file, held ones too (never the owner's own). Each view is logged. With `runs:read`, the runs' prompts, inputs and results too |
| `outputs:hide` | `POST /api/admin/outputs/hide` |
| `outputs:moderate` | `POST /api/admin/outputs/hide`, `/unhide` and `/remove` |
-| `reports:read` | `GET /api/admin/reports` (reporters' emails included) |
-| `workers:read` | `GET /api/admin/workers` |
+| `reports:read` | `GET /api/admin/reports` (reporters' emails only with `accounts:read`) |
- | `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/download` |
++| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs` |
| `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke |
| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those |
-| `queue:read` | `GET /api/admin/queue` |
+| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings` |
+| `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share and the pick allowance |
| `audit:read` | `GET /api/admin/audit` |
+The read-only preset in Settings ticks `runs:read`, `reports:read`, `workers:read`, `queue:read` and `audit:read`:
+no emails, no prompts and no results. With `runs:read`, an account's email in a run needs `accounts:read`. Without it a
+run's `account` is `{ id, emailHidden: true }`; `email: null` always means the account was deleted.
+
Any valid admin token may call `GET /api/admin/tokens/self`, which says the token's name and scopes, so a tool can
offer only what it may do. `/api/admin/tokens` itself (make, list, revoke) is the owner's signed-in browser's only.
@@@ -116,23 -109,16 +116,22 @@@ Times are epoch milliseconds and sizes
| `GET /api/admin/workers` | | `{ workers, lanes }` |
| `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once |
| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |
-| `GET /api/admin/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner` or `token`), `token` (a token id), `action`, `changes=1` (changes only: no reads, file views or refusals) | `{ items, next }` |
+| `GET /api/admin/workers/jobs` | `before`, `limit` (1 to 200, 50), `worker`, `generation` | `{ items, next }`: the workers' log, newest first. Each item: `{ id, at, event, workerId, workerName, taskId, generationId, principal, lane, execMs, device }` ([gpu-workers.md](gpu-workers.md)) |
- | `GET /api/admin/workers/download` | | the worker program, `fuobe-worker.zip` |
+| `GET /api/admin/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner`, `token` or `system`), `token` (a token id), `action`, `changes=1` (changes only: no reads, file views or refusals) | `{ items, next }` |
| `GET /api/admin/tokens/self` | | `{ id, name, prefix, scopes, expiresAt, createdAt }` |
-A log row is `{ id, at, actor: "owner" | "token", token: { id, name } | null, action, target, detail, status }`.
+A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name } | null, action, target, detail, status }`.
`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,
`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,
-`worker.rotate`, `worker.revoke`, `token.create`, `token.revoke`, `token.revoke_all`; a token's reads `accounts.list`, `accounts.csv`,
-`account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and action every 10 minutes) and
-`file.view` (one row per token and file every hour); and refusals `scope.denied` and `rate.limited`. The owner's own
-reads in the browser aren't logged. Rows go after a year.
+`worker.rotate`, `worker.revoke`, `queue.settings` (with the values before and after), `token.create`, `token.revoke`,
+`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after); a token's reads
+`accounts.list`, `accounts.csv`, `account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and action
+every 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and account
+every 10 minutes, the account as its target) and `file.view` (one row per reader and file every hour); refusals
+`scope.denied` and `rate.limited`; and the studio's own alerts `worker.alert` (actor `system`: a worker's token used
+from a new country, a new network, or two networks at once; [gpu-workers.md](gpu-workers.md#the-protocol)). The
+owner's other reads in the browser aren't logged. Rows go after a year. `actor` can be `system`, and the `actor` filter
+takes it.
A row is written once the change is made. If the server can't write it (a full disk, say), the change still stands and
the server's own log notes the missing row.
diff --cc docs/gpu-workers.md
index 1bbbde98,83a0e227..b662d18a
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@@ -105,12 -185,86 +188,89 @@@ The worker obeys any one of these pause
- **Hours:** outside its hours, the worker takes nothing new. Near the end of a window, it takes only a job that its
estimate says will finish in time.
+ On Windows, the pause shortcut (Ctrl+Alt+P, from `fuobe worker install`) runs `fuobe worker pause --choose`. It asks
+ for 1, 2 or 4 hours, or until you resume, and then pauses at once: the job goes back to the queue at no cost, and its
+ ComfyUI stops.
+
+ ### Studio jobs first
+
+ A PC can also run ComfyUI work of its own: a ComfyUI that you use by hand, or a queue of your own renders. With
+ **studio jobs first**, the studio's jobs go before that local ComfyUI work, in the order they were sent. Your local
+ ComfyUI work runs whenever no studio job waits. Any other program (a game, Blender, a video editor) still pauses the
+ worker, as above.
+
+ The worker never connects to your other ComfyUIs. It reads three things only:
+
+ 1. **Windows' table of listening ports** (`Get-NetTCPConnection -State Listen`). Reading the table connects to
+ nothing. A python process that listens on a port in `localComfyPorts` (8188 to 8199) is local ComfyUI work. The
+ worker's own ComfyUI (by its process id and its port) never counts. Neither do the ports and process ids in
+ `localComfyExcludePorts` and `localComfyExcludePids`. The worker reads the table every 30 seconds, and sooner when
+ a process that it doesn't know holds GPU memory.
+ 2. **Windows' GPU counters** (`\GPU Process Memory(pid_<n>_*)\Dedicated Usage`, read with `typeperf`). These are the
+ numbers that Task Manager shows for each process. `nvidia-smi` gives the total only, because its per-process memory
+ reads `[N/A]` on Windows. The worker reads the graphics card whose processes hold the most memory. On a PC with
+ more than one card, set `gpuLuid` to the card's part of the counter name (for example
+ `0x00000000_0x0000d1b5_0`, the luid and the phys number).
+ 3. **A GPU lock file** (`gpuLockFile`), only when the counters or the port table can't be read. If the first word of
+ the lock names an owner in `gpuLockComfyOwners`, the GPU's memory counts as local ComfyUI work. Any other owner
+ counts as another program, and so does no lock at all.
+
+ Every 5 seconds, the worker splits the GPU's used memory three ways. **Others** are the total, minus its own ComfyUI,
+ minus local ComfyUI work, minus the desktop's usual share (`desktopBaselineMb`). Run `fuobe worker baseline` once,
+ with no game open, to measure that share. Local ComfyUI work may stay open while you measure, and the worker may keep
+ running: its own ComfyUI is not counted (the process in `comfyui.pid` in the worker folder, and the process that
+ listens on its port). The command shows what it counted, with the biggest programs by name. It saves at most 4096 MB.
+ More than that means that another GPU program was open: it says so, and you can close that program and measure again.
+
+ - If others are above `busyVramMb` in two readings in a row, the worker pauses as before ("Your GPU is busy"). After
+ one such reading, it starts no new job, and a turn stays as it is: it doesn't begin, and it doesn't end.
+ - If only local ComfyUI work holds more than `busyVramMb`, the worker asks for a turn and waits. While it waits, its
+ jobs keep their place in the line. This is not a pause: there is no cool-down, and the studio does not send its jobs
+ back.
+
+ **The turn files.** Set `yieldFolder` in `worker.json` to a folder for two small files. The PC's setup makes the
+ folder. The worker never makes it, so the folder keeps the rights that the setup gave it. If the folder isn't there,
+ local ComfyUI work counts as another program.
+
+ - `site.json` is written by the worker on every beat, and at least every 5 seconds:
+ `{ siteWaiting, oldestWaitS, interrupt, interruptAt, at }`. `siteWaiting` is the number of studio jobs that this
+ worker may take now (from the beat's `claimableNow`), plus the job that it runs. During a turn it is at least 1. It
+ goes to 0 when no studio job has come for a minute, when the worker is paused, or when a local cap is reached. When
+ the worker stops, it writes 0. `oldestWaitS` is how long the worker has seen people's jobs waiting for it, by its
+ own clock.
+ - `yielded.json` is written by a helper on the PC's side: `{ state, at, startsAt }`. The state `"yielding"` can carry
+ the helper's estimate of the start time (`startsAt`, in ms). The worker passes it on in its beat. The state
+ `"yielded"` means that local ComfyUI work has made room. A "yielded" counts when it was written after the turn began,
+ or in the last 15 seconds. The worker then starts at once.
+
+ When no studio job has come for a minute, the worker frees its own ComfyUI's memory (`/free`) and writes
+ `siteWaiting: 0`, so your local work can go on. If no "yielded" comes within 3 minutes, the worker says so in its log
+ and in its beat (`waiting-for-yield:no-answer`). It goes on waiting, with the jobs kept in line.
+
+ **Limits that only the PC sets.** The studio can never change these:
+
+ - `yieldMaxHoursPerDay` (20): the most hours of turns in one day, on the PC's clock. After that, local ComfyUI work
+ counts as another program until the next day. A restart doesn't reset the count.
+ - `interruptGapMin` (30): a request to stop your current local job instead of letting it finish passes on at most
+ once in this many minutes, as one interrupt: `interrupt: true` with `interruptAt`, the time the worker allowed it.
+ The helper stops at most one local job for each `interruptAt` value. Both go back to `false` and `null` as soon as
+ the helper writes `yielded.json` after that time. The beat's answer has no such request yet, so today `interrupt`
+ is always false and the helper lets your local job finish.
+ - `neverInterrupt` (false): when it is true, `interrupt` is always false.
+
+ **You first.** A pause by hand always wins. While the worker is paused, `siteWaiting` is 0. With a plain
+ `fuobe worker pause`, a job that is still finishing keeps `siteWaiting` at 1 until it ends. The shortcut's choice
+ (`--choose`) and `--now` give the GPU back at once.
+
+ Turns need the studio to send `claimableNow` in the beat's answer. A studio that doesn't send it gets today's
+ behaviour: local ComfyUI work pauses the worker like any other program. With no `yieldFolder`, nothing changes.
+
### The queue
-A job for the workers belongs to the owner. It names the pools that may take it (`pool` by default). It also keeps:
+A job for the workers belongs to the owner or, with hosted runs on ([public-signup.md](public-signup.md#hosted-runs)),
+to an account. An account's job is the account's task (`acct:<id>`): only a worker of its pool takes it, and the
+account's own session never reaches it through the computer routes. It names the pools that may take it (`pool` by
+default). It also keeps:
- its lane: the first 12 hex digits of the SHA-256 of the sorted names of the workflow's files over 2 GB. A workflow
with no big file is in the lane `small`.
@@@ -131,51 -277,20 +291,53 @@@ A worker gets a job only when all of th
- it is paused in neither place, it is not draining, it is inside its hours, and the studio heard from it in the last
30 seconds;
++- its worker program speaks protocol 2 or later (an older one takes nothing until it is updated);
- the job is in its pool, in a lane that the owner allows for it, after the lane's delay and `claim_after_ms`;
- - it has the workflow's files and packs (from its inventory) and enough VRAM;
+ - it has the workflow's files and packs (from its inventory) and enough VRAM. A workflow's need is its whole GB less
+ 3%, because a card reports a little less than its size (a 32 GB card shows about 31.8 GiB);
- the retry rule allows it: a worker that lost or failed the job gets it again only when no other worker that can run
the job was heard from in the last 10 minutes;
-- near the end of its hours, the job's estimate fits before the window closes.
-
-The lowest `rank_at` goes first. A worker keeps to its warm lane (the models that it has loaded) until another lane's
-best job has waited longer than `switch_after_ms` (30 minutes) and is older.
-
-If a worker stops answering for 2 minutes, or its ComfyUI is down for 2 minutes, its job goes back to the queue. The
-worker is added to the job's `tried_json` list, and the input reads start again. The old worker's late calls get 409,
-and it deletes that prompt. After the third lost attempt, the job fails. A job that is put back because of a pause
-does not count as an attempt.
+- near the end of its hours, the job's estimate fits before the window closes;
+- it holds no other job. A worker runs one job at a time: while it holds one, a claim gives it that job again when
+ it lost track of it, and nothing new.
+
+Jobs go by class (`paid`, then `free`, then `owner`), then by the lowest `rank_at` (then the oldest). With the
+pick allowance at 0 (the default), that is the whole rule. Above 0, a worker may take a job in its warm lane (the
+models it has loaded) ahead of the best job, in the same class, while the best job has waited less than the pick
+allowance (or the worker's own `switch_after_ms`, if that is lower). With fair share on, each class goes round its
+accounts: an account's next run goes after every other account's run that is an earlier turn of its own. An account's
+turns count the runs a worker holds for it now and those a worker finished for it since the oldest run still waiting
+in that class came.
+
+**The queue's settings.** The owner sets these with `GET` and `PATCH /api/admin/queue/settings`
+([admin-api.md](admin-api.md)). They apply at once, with no restart:
+
+| Setting | What it does | Default |
+|---|---|---|
+| `runCeilingS` | `{ default, lanes }`: the longest one attempt at a job may run, in seconds, with a value per lane that overrides the default. It ends the run's own clock, and a worker's run limit is never longer | `{ "default": 2700, "lanes": {} }` (45 minutes) |
+| `ownerWaitLimitS` | How long the owner's own jobs may wait before a worker first takes them, in seconds. `null`: no limit | `null` |
+| `fairShare` | Each class goes round its accounts (above). Off: strict order | `false` |
+| `pickAllowanceMs` | How long a job in a worker's warm lane may go ahead of an older one (above). 0: strict order | `0` |
+
+A worker's run limit for one attempt is 3 times the lane's 90th percentile on that worker plus its model load, at
+least 10 minutes and never past the lane's run ceiling. With no measured run in the lane yet, it is the ceiling.
+
+If a worker stops answering for 2 minutes, its ComfyUI is down for 2 minutes, or the job is still sending its files
+15 minutes after the worker claimed it (or after its ComfyUI lost the job and the worker sent it again), its job goes
+back to the queue. The worker is added to the job's
+`tried_json` list, and the input reads start again. The old worker's late calls get 409, and it deletes that prompt.
+After the third lost attempt, the job fails. A job that is put back because of a pause does not count as an attempt.
+The run's own clocks follow the queue's: each attempt gets its own running time.
+
+**The place in line.** A waiting job's place counts every job that a worker able to run it would serve first, whatever
+its lane: one GPU serves every lane it has in this order. The wait adds the rest of the jobs those workers run now,
+the lane's load time when none has it warm, and the job's own run (the lane's median on the quickest worker, else the
+median of the workers' measured runs). The billing service's line facts (`QueueFacts`) read the same line.
+
+**The workers' log.** `worker_jobs` keeps which worker took which job, when, and how it ended (`claimed`,
+`finished` with the measured run, `requeued`, `done`, `failed`, `canceled`). It holds ids, times and those facts
+only. Rows are only added, and each is kept a year, like the admin API's log. The owner reads it at
+`GET /api/admin/workers/jobs` ([admin-api.md](admin-api.md)).
### What the worker checks itself
@@@ -184,19 -299,120 +346,126 @@@ Before its ComfyUI gets a graph, the wo
1. Every node type is on the allowlist that is built into the worker (`bin/lib/worker/dist/allowed-nodes.json`, made
by `scripts/build-worker.mjs` from the catalog's workflows and the graph builders). For your own workflows, pass
a file with `allowNodesFile` in `worker.json`. The studio can never send a file like that.
- 2. Every file that the graph reads was sent with the job.
- 3. No string input names a path (an absolute path, a drive letter, a network share or a `..` step).
- 4. Every model file that the graph names is one that the worker verified.
-
- After each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from its
- ComfyUI's history. At start, it empties its folders.
+ 2. Every file that the graph reads was sent with the job, under the name the studio gave it.
+ 3. Every input keeps to its rule (`bin/lib/worker/dist/input-rules.json`). The build gives a rule to each input that
+ could name a file, a folder, a download or code, from the values in the catalog's own workflows:
+ - a fixed value, or one of a list (a subtitle node writes no file; a timeline node reads no clip by path; a format
+ string, a download name and a save folder stay the catalog's);
+ - a number range;
+ - a file that this job sent;
+ - a save name that the studio makes (plain name parts, no path);
+ - a model file that the worker verified, in the model folder that its loader reads.
+
+ No link from another node may reach an input that has a rule, so a value cannot be built from pieces. A node that
+ has such an input takes only the inputs that the catalog gives it.
+ 4. Inputs with no rule that do not take free text hold no path. A name is refused if it has a `:`, `%`, `~` or `..`.
+ Any value is refused if it starts with `/`, `\`, `~` or a drive (`C:`), or if it holds an address (`://`), an
+ encoded or variable part (`%2e`, `%TEMP%`), a `..` step or a Windows device name (`CON`, `NUL`, `COM1`…).
+ Prompts, lyrics and captions keep any text.
+ 5. Every model file that the graph names is one that the worker verified, by its exact name. A file with the same
+ name in another folder does not count.
+
+ The worker reports a model file only when its SHA-256 matches the hash that the catalog pins for it
+ (`bin/lib/worker/dist/file-pins.json`, from `requirements.json` and `model-pins.json`). A file that has no pinned hash
+ is not reported, so no job that needs it comes to the worker. The worker keeps the hashes it computed, so a restart
+ does not read the files again. The catalog's files that still have no pin are listed in `UNPINNED_FILES`
+ (`scripts/lib/worker-catalog.mjs`). A test fails when a workflow for workers needs a file that has no pin and is not on
+ that list, and when a file on the list gets a pin, so the list only gets shorter.
+
+ The worker checks the copy that its ComfyUI loads:
+
+ - Its ComfyUI looks in the worker's model folders first, in the order that `worker.json` gives (`is_default` in the
+ worker's `extra_model_paths.yaml`), and takes the first folder that has the file. So the worker checks only that
+ first copy. If that copy has the wrong size or hash, the file is not reported, even when a later folder has a good
+ copy.
+ - Some node packs read ComfyUI's own `models` folder directly. And an older ComfyUI that does not know `is_default`
+ looks in its own folders first. So a copy with the same name in ComfyUI's own `models` folder (`unet` and `clip`
+ count for `diffusion_models` and `text_encoders`), or in a folder that ComfyUI's own `extra_model_paths.yaml` adds,
+ must be the same file too. If it is not, the file is not reported.
+
+ After each job, however it ended, nothing of it stays in its ComfyUI: the worker empties the queue, stops a prompt that
+ still runs, and clears the whole history (a meta-batch's passes too). It also deletes the job's inputs and results from
+ its folders, and its copies of the inputs. At start, and whenever it stops, it empties these folders too. Before it
+ starts a job that its ComfyUI did not have last, it clears its ComfyUI the same way.
-Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). Clips and sound go to workers
-only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default; `image,video,audio` for all). The worker then makes
-each one again before its ComfyUI reads it (see "Clips and sound").
+Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS), the owner's and accounts'
+alike. 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. Every
- VideoHelperSuite save node of a graph for the workers is sent with `save_metadata` off, so no prompt rides inside a
- result. An account's run is shaped by the workers' own facts (the least VRAM and RAM of the workers allowed its lane),
- never by the account's own computer.
++`image,video,audio` for all); an account's run with a kind it doesn't allow is refused before it is queued. The worker
++then makes each one again before its ComfyUI reads it (see "Clips and sound"). Every VideoHelperSuite save node of a
++graph for the workers is sent with `save_metadata` off, so no prompt rides inside a result. An account's run is shaped
++by the workers' own facts (the least VRAM and RAM of the workers allowed its lane), never by the account's own computer.
+
+ ### Clips and sound
+
+ Set `ffmpeg` in `worker.json` to the path of ffmpeg (setup asks for it). The worker then makes every clip and every
+ sound that a job sends again, into a fresh file, before its ComfyUI sees it:
+
+ - a clip keeps its first picture stream and its first sound stream, encoded again in the format that its name says
+ (H.264 and AAC in MP4 for most names, VP9 and Opus for WebM);
+ - a sound keeps its first sound stream, in the format that its name says (WAV for any other name);
+ - nothing else of the file is kept: no metadata, chapters, subtitles, attachments or data streams.
+
+ The worker knows a clip or a sound by its type, by its name, or by the loader that reads it in the graph. ffmpeg runs
+ in its own process, at low priority, for at most 20 minutes. It reads the file only as a local file
+ (`-protocol_whitelist file`), and only as one of these container formats (`-format_whitelist`): MP4 and MOV (with M4A
+ and 3GP), Matroska and WebM, AVI, GIF, MPEG-TS, MPEG-PS, FLV, ASF, WAV, MP3, FLAC, Ogg, AAC and AIFF. A playlist, a
+ list or any other format that would make ffmpeg open other files or addresses is refused.
+
+ What ffmpeg writes has limits too: at most one hour, at most 4096 pixels on the long side (a bigger picture is made
+ smaller, in the same shape), and at most 8 times the input's size (at least 256 MB, at most 2 GB). A result that
+ reaches the size cap is refused before the worker reads it. If ffmpeg cannot read a file, or its result is too big,
+ the job fails with plain words ("A clip or a sound in this run couldn't be read").
+
+ Without `ffmpeg`, the worker takes pictures only. Its inventory says so (`media: ["image"]`), and the studio sends it no
+ workflow that reads a clip or a sound. If such a job comes anyway, the worker gives it back to the line.
+
+ ### When something goes wrong
+
+ The worker keeps its jobs going by itself:
+
+ - **Results are kept until the studio has them.** When its ComfyUI finishes a job, the worker copies every result into
+ `hold/<job>/` in the worker folder before it tells the studio. The copy stays until the studio has every file. If
+ the worker or its ComfyUI stops in between, the next claim gives the job back to this worker, and it uploads the
+ kept files from where the studio's copy got to. The job never runs twice. Kept results go up even while the worker
+ is paused, because they need no GPU. Each beat names the jobs whose results the worker keeps (`held`), so a pause,
+ even a pause now, leaves those jobs with this worker instead of sending them back in line. Kept results are deleted
+ when the studio has them all, when the worker takes another job, when the studio no longer has the job, or after a
+ day. A claim that finds nothing for the worker keeps them: their job may still come back to it.
+ - **One retry policy for the studio.** A studio that restarts, a proxy that answers 502, 503 or 52x, a network that
+ drops, or a busy studio that says when to come back is waited out. The pause grows from 1 second to at most 30
+ seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a call
+ again only when that is safe. A proxy's page in place of the studio's answer (a 403 that is not JSON) never stops
+ the worker.
-- **A job that stalls goes back to the line.** If a job makes no progress for `stallMin` minutes (10), or runs past the
- run limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps
++- **A job that stalls goes back to the line.** If a job makes no progress for the stall limit that the claim gives (10
++ minutes, never more than its lane's run ceiling; `stallMin` in `worker.json` wins), or runs past the run limit that
++ the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps
+ its place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and
+ starts it again. A job that is given back counts as an attempt; the third time, it fails.
+ - **The run limit** counts from when its ComfyUI starts running the job (the model load included), not while the job
+ waits. The studio gives 3 times the lane's 90th-percentile time on that worker plus the lane's model load, at least
- 10 minutes and at most the run ceiling (45 minutes). For a lane with no times on that worker yet, it gives the run
- ceiling, so a first long job can finish. The worker ignores a run limit under 10 minutes.
++ 10 minutes and at most the lane's run ceiling (the queue's `runCeilingS`, 45 minutes unless the owner sets another).
++ For a lane with no times on that worker yet, it gives the run ceiling, so a first long job can finish. A job given
++ back once for running past its limit gets the whole run ceiling on its next try; past that, it fails. The worker
++ ignores a run limit under 10 minutes.
+ - **A ComfyUI that stops answering** for `hungMin` minutes (3) is stopped and started again.
+ - **A job that the studio took back** (its token for the job no longer works, for example after the worker was out of
+ touch) is stopped in its ComfyUI at once, so it never keeps the GPU busy for nothing.
+ - **Out of memory.** The worker frees its ComfyUI's memory (`/free`) and sends the job once more. Only a second time
+ fails the job. The execution time that it reports is the retry's only.
+ - **Inputs are read once.** The worker keeps a copy of each input (by its SHA-256) while its job runs, so a job that
+ is sent again reads nothing from the studio twice. If the studio will not send an input again (429 with no
+ `Retry-After`), the job fails at once instead of looping. The copies go when the job ends, and also when a claim
+ brings another job or none, however the last job ended.
+ - **The PC stays awake** while the worker holds a job, has results to send, or waits for work. A small helper asks the
+ system to stay awake (`SetThreadExecutionState` on Windows, `caffeinate` on macOS, `systemd-inhibit` on Linux). The
+ screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.
+ - **Its model folders are read again** every 10 minutes, and whenever a job needs a model file that the worker has not
+ found yet. A drive that comes back after a restart is noticed, and the studio gets the new list.
+ - **When the studio stops the worker.** If the studio no longer knows the worker's token, `fuobe worker run` ends with
+ exit code 3; any other stop that you did not ask for ends with exit code 1. The sign-in task that
+ `fuobe worker install` adds then starts the worker again after a minute. Ctrl+C ends with 0. On Ctrl+C, and on a
+ stop from the system (SIGTERM), the worker stops its ComfyUI and empties its folders before it ends. Kept results
+ stay for its next start.
### The protocol
@@@ -204,36 -420,42 +473,60 @@@ Every worker call carries `Authorizatio
gets 403 everywhere else. It is never the owner, and an owner API token can never act as a worker. The studio reads the
token on every call, so a revoked token stops at once.
-- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {
- otherApps, tempC }, inventoryHash, warmLane, held }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
- insideHours, nextChangeAt, lanes, minProtocol, sendInventory }`.
+**A token's lifetime.** With `FUOBE_WORKER_TOKEN_DAYS` set (unset or 0: a token never expires, as before), a pool
+worker's token lasts that many days. A worker added before the lifetime was set gets it from its first call after. Once
+half of it is gone, the beat answer of a worker that says it saves tokens (`canRotateToken: true` in its beat) gives it
+the next token (`worker.token: { value, expiresAt }`). The worker saves it and uses it from its next call on. The old
+token stops at the new one's first use. A next token that is never used is given again, as a new one, after 10
+minutes. A paired ComfyUI's token keeps no lifetime. Set the lifetime only once every pool worker sends
+`canRotateToken: true`: the token of a worker that doesn't expires at the end of its lifetime, and the worker stops
+until you rotate its token in Settings → Workers.
+
+**Where a token is used from.** For a pool worker, the studio remembers the countries (Cloudflare's `cf-ipcountry`)
+and the networks (an IPv4 address's /24 or an IPv6 address's /64, read only with `FUOBE_TRUST_PROXY=1`) its token was
+used from, as short hashes, never as addresses. A call from a new country or a new network, and calls from two networks
+within 10 minutes of each other, each write an alert to the admin log (`worker.alert`, actor `system`, the worker as
+its target), at most once an hour each.
+
+- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,
- until }, gpu: { otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
- insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token, above) and
- `claimableNow`: how many people's jobs (an
- account's, never the owner's) this worker may claim right now by its lanes, files, VRAM and hours, its own pause aside.
- - `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }] }` →
- `{ lanes, workflows, missing }`.
- - `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,
- models }`.
++ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held }`. The answer adds `worker: { paused, pauseNow,
++ drain, autoResume, insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token,
++ above).
+ - `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUI
+ behind the guard.
+ - `held` (optional) names the jobs whose finished results the worker keeps on its disk. A pause now sends those
+ jobs back in line only when the worker doesn't name them.
+ - While the worker waits for its turn (see "Studio jobs first"), `local` is `{ paused: false, why:
+ "waiting-for-yield", until }`, where `until` is the helper's estimate of the start time, or null. After 3 minutes
+ with no answer, `why` is `"waiting-for-yield:no-answer"`. The worker may still take jobs, and its jobs keep their
+ place.
+ - The answer also carries `claimableNow`, for studio jobs first: the number of people's jobs (never the owner's own)
+ that this worker may take now. It counts the jobs in the worker's pool that it can run (its lanes, files and VRAM)
+ and that end before its hours do. It is 0 while the worker is paused on the website, drains, is outside its hours
+ or runs an older worker program. The worker's own pause on the PC does not change it. The answer has no wait time
+ and no request to interrupt local work: the worker measures `oldestWaitS` itself.
+ - `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }], media }`
+ → `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,
+ `audio`). With no `media` (a worker from before it was added, which doesn't make clips and sound again), the studio
+ counts pictures only.
-- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,
- models }`. See "The run limit" above for `runLimitMs`.
++- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, stallMs, notAfter,
++ attempt, models }`. See "The run limit" above for `runLimitMs`, and "A job that stalls" for `stallMs`.
- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finished
job also count: the last 20 jobs in each lane give the median and the 90th percentile.
- - Reports, inputs and results work as they do for the browser. `failed` can also give `unknown-node`, `unsafe-path`
- or `model-unverified` as the reason. `finished` (and the last `passes`) can add `execMs`, the time its ComfyUI
- spent running the job (not waits, files or the upload), and `device`, its GPU's name. The billing service gets
- them as `gpuMs` and `device`. A job that ran more than once counts once: the attempt whose result was kept.
+ - 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, from
- ComfyUI's own timestamps: no waits, no uploads) and `device` (the GPU's name). The studio keeps both with the job.
- It keeps at most the job's run ceiling, and at most the time since the job was sent to its ComfyUI (plus a minute,
- because ComfyUI starts a job a moment before the studio hears that it was sent).
++ ComfyUI'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
++ than 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 moment
++ before the studio hears that it was sent).
+ - `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and
+ counts as an attempt. Only a worker's job can be given back.
+ - `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
+ `input-crashed` (its ComfyUI stopped twice on the job) or `input-unreadable` (ffmpeg could not read a clip or a
+ sound) as the reason. The worker's own log names the node and the input, never the value. For
+ `input-crashed` and `input-unreadable`, and for a job that a worker gave back for the last time, the person who
+ started the run sees one plain sentence with no technical detail.
Each worker counts against its own rate limits, so three workers that beat every 5 seconds never hold each other up.
@@@ -256,7 -477,18 +549,20 @@@ routes
## Tests
- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,
- `tests/worker-queue.test.ts`, `tests/pool-account-runs.test.ts`)
++ `tests/worker-queue.test.ts`, `tests/worker-tokens.test.ts`, `tests/pool-account-runs.test.ts`,
++ `tests/pool-line-order.test.ts`, `tests/pool-limits.test.ts`,
+ `tests/worker-input-rules.test.ts`, `tests/worker-environment.test.ts`, `tests/worker-guard.test.ts`,
+ `tests/worker-runner.test.ts`, `tests/worker-recovery.test.ts`, `tests/worker-parts.test.ts`,
+ `tests/worker-turns.test.ts`, `tests/worker-turns-run.test.ts`). The turn tests use a fake port table, fake GPU
+ counters and a fake lock file. With only local ComfyUI work on the GPU, the worker writes `siteWaiting` and claims
+ within 5 seconds of the answer; with a game, it pauses and asks for no turn. The input-rule tests
+ send graphs that try to write or read files outside the worker's folders, and check that the worker refuses them.
+ They also prepare every catalog workflow the way the studio does, and check that the worker accepts each one. The
+ recovery tests run the worker against the studio's routes and a stand-in ComfyUI that the worker starts: they kill
+ its ComfyUI halfway, stop the worker before an upload, make its ComfyUI hang, and check that the output arrives
+ each time, once. The guard tests run the real guard in front of a stand-in ComfyUI when a Python with aiohttp is
+ there (`FUOBE_TEST_PYTHON`, else `python3` or `python`), also through a venv's Python (that Python itself when it is
+ a venv's, else a venv made from it); the clip tests need `ffmpeg` on the `PATH`.
- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). These
use a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.
- `python -m unittest discover -s tests` in `integrations/fuobe-connect`
diff --cc src/app/api/gpu/computer/tasks/[id]/report/route.ts
index c8b0580a,98075b0c..d2ca0b42
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@@ -102,11 -108,9 +108,9 @@@ export async function POST(request: Req
// Where the job is now (it may have moved while the body arrived).
const t = leased(principal, id, lease);
const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => planRelayOutputs(t, entries, passes)));
- // A worker's finished job counts toward its lane's times there, and the workers' log keeps its measured run.
- if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running") {
- noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
- if (t.worker_id) logWorkerJob("finished", t, t.worker_id, Date.now(), { execMs: event.execMs, device: event.device });
- }
+ // A worker's finished job counts toward its lane's times there (not results kept from an earlier try: their time
- // there would be only the upload's).
++ // there would be only the upload's). The workers' log keeps its measured run (tasks.ts report).
+ if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running" && !event.kept) noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
return Response.json(answer, { headers: { "Cache-Control": "no-store" } });
} catch (e) {
return relayAnswer(e);
diff --cc src/lib/relay.ts
index b7130dab,7223d849..39e1cf6d
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@@ -174,11 -199,6 +199,11 @@@ export interface WorkerAnswer
minProtocol: number;
/** Its inventory is unknown or changed: send it (PUT /api/gpu/computer/inventory). */
sendInventory: boolean;
+ /**
- * Its next token (protocol 2), when its token has a lifetime and half of it is gone: save it and use it from the next
++ * Its next token (to a worker that says `canRotateToken`), when its token has a lifetime and half of it is gone: save it and use it from the next
+ * call on. The old token stops at the new one's first use. Given again after 10 minutes if it was never used.
+ */
+ token?: { value: string; expiresAt: number };
}
/** What a worker says in its beat, on top of a browser's. */
@@@ -186,11 -206,9 +211,15 @@@ export interface WorkerBeat
device: string;
protocol: number;
version: string;
+ /** It saves the next token a beat answer gives it (`worker.token`) and uses it from its next call on. */
+ canRotateToken?: boolean;
ready: boolean;
why: string | null;
-- /** Its own pause switch: by hand ("here", "here-until:<ms>"), by itself ("gpu-busy:<process>", "comfy-crashes", "port-busy"). */
++ /**
++ * Its own pause switch: by hand ("here", "here-until:<ms>", "here-now"), by itself ("gpu-busy:<process>",
++ * "comfy-crashes", "port-busy"). Not paused, `why` may say that it
++ * waits for local ComfyUI work to make room ("waiting-for-yield", "waiting-for-yield:no-answer").
++ */
local: { paused: boolean; why: string | null; until: number | null };
gpu: { otherApps: { pid: number; name: string; vramBytes: number }[]; tempC: number | null };
facts?: ComputerFacts;
diff --cc src/server/computer/pool.ts
index 03e01de9,135e632c..686174b9
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@@ -5,9 -5,8 +5,9 @@@ import { RELAY_TIMES, SENT_STATES, typ
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
- import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setTask, takeTask, taskById, type TaskRow } from "./tasks";
-import { cleanFacts, endTask, getTask, json, noteProgress, setPoolCeiling, setPoolClocks, setPoolGiveBack, setTask, takeTask, type TaskRow } from "./tasks";
-import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
++import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setTask, takeTask, taskById, type TaskRow } from "./tasks";
+import { queueSettings, runCeilingMs } from "../queue-settings";
+import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
/**
* Workers (docs/gpu-workers.md): the owner's GPUs on other machines, each running `fuobe worker`, which pulls jobs from
@@@ -25,10 -27,21 +28,17 @@@ export const RETRY_WINDOW_MS = 10 * 60_
export const MAX_ATTEMPTS = 3;
/** A worker that beat this recently may claim. */
const FRESH_BEAT_MS = 30_000;
-/** The longest one attempt at a job may run on a worker (the generation's own clock is the same 45 minutes). */
-export const RUN_CEILING_MS = 45 * 60_000;
-/** Run ceilings of their own for some lanes (none yet: every lane has RUN_CEILING_MS). */
-const LANE_CEILINGS: Readonly<Record<string, number>> = {};
-/** A lane's run ceiling. */
-export const runCeilingMs = (lane?: string | null) => (lane && LANE_CEILINGS[lane]) || RUN_CEILING_MS;
+ /** A job that makes no progress for this long goes back in line (a worker's own worker.json may set another). */
+ export const STALL_MS = 10 * 60_000;
-/** Stall limits of their own for some lanes (none yet: every lane has STALL_MS). */
-const LANE_STALLS: Readonly<Record<string, number>> = {};
-/** A lane's stall limit, which the claim gives the worker. */
-export const stallLimitMs = (lane?: string | null) => (lane && LANE_STALLS[lane]) || STALL_MS;
++/**
++ * A lane's stall limit, which the claim gives the worker: STALL_MS, and never past the lane's run ceiling
++ * (queue-settings.ts).
++ */
++export const stallLimitMs = (lane?: string | null) => Math.min(STALL_MS, runCeilingMs(lane));
/**
* The run limit of one attempt: 3 × the lane's p90 on that worker plus its model load, at least 10 minutes, and never
- * past the lane's run ceiling (queue-settings.ts; 45 minutes unless the owner sets another). With no p90 yet, the
- * ceiling.
- * past the lane's run ceiling. With no p90 yet (a new worker, a new lane), the ceiling: a first long job finishes.
++ * past the lane's run ceiling (queue-settings.ts; 45 minutes unless the owner sets another). With no p90 yet (a new
++ * worker, a new lane), the ceiling: a first long job finishes.
*/
export const runLimitMs = (p90?: number | null, lane?: string | null, loadMs?: number | null) => {
const ceiling = runCeilingMs(lane);
@@@ -212,13 -211,13 +227,13 @@@ export function workerBeat(w: WorkerRow
/**
* People's tasks (an account's, never the owner's own) this worker may claim right now: in its pool, in a lane it is
* allowed and able to run, with the files and VRAM they need, past their delays, and ending before its hours do. Its
- * own pause doesn't count here (its machine reads this to know whether a person's run waits for it); a pause on the website,
- * a drain or being outside its hours does.
- * own pause doesn't count here (its PC reads this to know whether a person's run waits for it); a pause on the website,
- * a drain, an older worker program or being outside its hours does.
++ * own pause doesn't count here (its machine reads this to know whether a person's run waits for it); a pause on the
++ * website, a drain, an older worker program or being outside its hours does.
*/
export function claimableNow(w: WorkerRow, now = Date.now()): number {
- if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || !hoursAt(hoursOf(w), now).inside) return 0;
+ if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;
const rows = db()
- .prepare("SELECT * 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 rank_at 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 ORDER BY ${LINE_ORDER} LIMIT ?`)
.all(`,${w.pool},`, LOOK_AT) as TaskRow[];
return rows.filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;
}
@@@ -470,9 -411,32 +491,29 @@@ export function sweepPool(now = Date.no
setPoolClocks((t, now) => {
sweepPool(now);
- return getTask(t.principal, t.id) ?? t;
+ return taskById(t.id) ?? t;
});
+ /** The words of a run that a worker gave back for the last time. */
+ export const GAVE_BACK_WORDS = "This run couldn't finish.";
+
+ /** A task a worker gave back for running past its run limit (its next try gets the whole run ceiling). */
+ const runLimitedOf = (t: TaskRow) => json<{ runLimited?: boolean }>(t.extra_json, {}).runLimited === true;
+
+ /**
+ * A worker gives its task back (it stalled, ran past its run limit, or takes clips or sound the worker can't make
+ * again): it goes back in line with its place kept, and counts as an attempt, so another worker that can run it is
+ * preferred and the third time fails it. Past its run limit a second time (that try had the whole run ceiling), it
+ * fails at once: one more try would only hold a GPU as long again.
+ */
+ setPoolGiveBack((t, why) => {
+ if (why === "run-limit") {
+ if (runLimitedOf(t)) return backInLine(t, { blame: true, why: GAVE_BACK_WORDS, last: true });
+ setTask(t.id, { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), runLimited: true }) });
+ }
+ backInLine(t, { blame: true, why: GAVE_BACK_WORDS });
+ });
+
-/** A worker's reported execution time is never more than its task's run ceiling. */
-setPoolCeiling((t) => runCeilingMs(t.lane));
-
// ---------------------------------------------------------------------------
// Place in line and the wait (4.4)
diff --cc src/server/computer/tasks.ts
index 431444a0,5f98cefd..2c9ae13b
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@@ -22,7 -23,7 +23,8 @@@ import
type TaskInput,
type WantedFile,
} from "@/lib/relay";
-import { DATA_DIR, db } from "../db";
+import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";
++import { runCeilingMs } from "../queue-settings";
/**
* "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a
@@@ -673,7 -570,10 +676,9 @@@ function reportOnce(t: TaskRow, e: Repo
}
const 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");
- // A worker's measured execution time and GPU, kept with the task for metering.
- const exec = execFields(e, t);
- const extra = (more: Record<string, unknown> = {}) => ({ ...(exec || Object.keys(more).length ? { extra_json: JSON.stringify({ ...extraOf(t), ...(exec && { exec }), ...more }) } : {}) });
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) ?? {});
if ("follow" in p) {
if (!t.meta_batch) {
endTask(t.id, "failed", { error: "This run finished without a result. Press Retry." });
@@@ -701,10 -601,14 +706,15 @@@
});
return { ok: true, wanted: p.wanted };
}
+ case "give-back":
+ // Only a worker's task goes back to the line (a person's own computer keeps its jobs).
+ if (!t.pools || !poolGiveBack) throw new RelayError(409, "That doesn't fit this run now");
+ poolGiveBack(t, e.why);
+ return { ok: true };
case "gone":
if (t.attempts < 2 && t.state !== "sending") {
- setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null });
+ // A worker's task sends its files again: its sending clock (pool.ts SENDING_MS) starts again too.
+ setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null, ...(t.pools && { claimed_at: now }) });
rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
return { ok: true };
}
@@@ -905,9 -809,47 +915,43 @@@ export function checkClocks(t: TaskRow
let poolClocks: ((t: TaskRow, now: number) => TaskRow) | null = null;
export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (poolClocks = fn);
+ /** A worker gives its task back to the line (pool.ts sets this too). */
+ let poolGiveBack: ((t: TaskRow, why: GiveBackWhy) => void) | null = null;
+ export const setPoolGiveBack = (fn: (t: TaskRow, why: GiveBackWhy) => void) => (poolGiveBack = fn);
+
-/** A task's run ceiling (pool.ts sets this): the most a worker's reported execution time may be. */
-let poolCeiling: ((t: TaskRow) => number) | null = null;
-export const setPoolCeiling = (fn: (t: TaskRow) => number) => (poolCeiling = fn);
-
-/** The execution time (ms) and GPU name a worker reported with a finished job, as kept. */
++/** The execution time (ms) and GPU name a worker reported with a finished job, as the workers' log keeps them. */
+ export interface ExecFacts {
+ ms: number;
+ device?: string;
+ }
+
+ /** ComfyUI starts a job as soon as it takes it, a little before the studio hears "sent": the time allowed for that. */
+ const SENT_SLACK_MS = 60_000;
+
+ /**
- * The execution time a worker reports, held to what is possible: at most a day, at most the task's run ceiling, and at
- * most the time since it sent the job to its ComfyUI (or, with no send noted, since the task was made). Results kept from
- * an earlier try ran before their "sent" (it notes only the upload): for them, the time since the task was made.
++ * The execution time a worker reports, held to what is possible: at most a day, at most the run ceiling of the task's
++ * lane (queue-settings.ts), and at most the time since it sent the job to its ComfyUI (or, with no send noted, since the
++ * task was made). Results kept from an earlier try ran before their "sent" (it notes only the upload): for them, the
++ * time since the task was made. With its GPU's name, as the workers' log keeps them (none reported: empty).
+ */
-function execFields(e: ReportEvent, t: TaskRow, now = Date.now()): ExecFacts | null {
++function execFields(e: ReportEvent, t: TaskRow, now = Date.now()): { execMs?: number; device?: string } | null {
+ if (e.event !== "finished" && e.event !== "passes") return null;
+ const since = e.kept ? t.created_at : (t.sent_at ?? t.created_at);
- const most = Math.max(0, Math.min(24 * 3_600_000, poolCeiling?.(t) ?? Infinity, now - since + SENT_SLACK_MS));
++ const most = Math.max(0, Math.min(24 * 3_600_000, runCeilingMs(t.lane), now - since + SENT_SLACK_MS));
+ const ms = typeof e.execMs === "number" && Number.isFinite(e.execMs) && e.execMs >= 0 ? Math.min(Math.round(e.execMs), most) : null;
- if (ms === null) return null;
+ const device = typeof e.device === "string" && e.device.trim() ? e.device.trim().slice(0, FACT_LIMITS.text) : undefined;
- return { ms, ...(device && { device }) };
++ return { ...(ms !== null && { execMs: ms }), ...(ms !== null && device && { device }) };
+ }
+
-/** What a worker measured for a task's run: its ComfyUI's execution time and its GPU, or null (none reported). */
-export const execOf = (t: TaskRow): ExecFacts | null => {
- const x = json<{ exec?: ExecFacts }>(t.extra_json, {}).exec;
- return x && typeof x.ms === "number" ? x : null;
-};
++/** What a worker measured for a task's last finished run (the workers' log): its execution time and its GPU, or null. */
++export function execOf(t: Pick<TaskRow, "id">): ExecFacts | null {
++ const r = rdb().prepare("SELECT exec_ms, device FROM worker_jobs WHERE task_id = ? AND event = 'finished' ORDER BY id DESC LIMIT 1").get(t.id) as { exec_ms: number | null; device: string | null } | undefined;
++ return r && r.exec_ms !== null ? { ms: r.exec_ms, ...(r.device && { device: r.device }) } : null;
++}
+
/** The file of a received output, for the principal whose task it is (anyone else: null). */
export function receivedFile(principal: Principal, taskId: string, n: number): { path: string; contentType?: string } | null {
- const t = getTask(principal, taskId);
+ const t = ownTask(principal, taskId);
if (!t) return null;
const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);
if (!r?.done) return null;
diff --cc src/server/providers/comfyui.ts
index 9a731871,5b85363a..bd7cd2fa
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@@ -2425,23 -2318,14 +2425,24 @@@ function relayFailure(t: TaskRow, manif
/** A run on someone's computer: where its task is, in the words its tile shows. */
async function pollComputer(principal: Principal, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {
- const found = typeof meta.relay === "string" ? getTask(principal, meta.relay) : null;
+ const found = typeof meta.relay === "string" ? ownTask(principal, meta.relay) : null;
if (!found) return { state: "failed", error: "This run was lost. Press Retry." };
const t = checkClocks(found);
+ if (!t.pools) return pollTask(principal, t, meta, manifest, made);
// A run on the workers: while it waits, its place in line; once a worker has it, that worker's reports (a worker that
- // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer"). Back in line after an attempt
- // (a worker paused, went quiet, gave it back), it shows its kept place as any waiting run does, and once a worker has
- // it again, the usual words: never a restart.
- if (t.pools && t.state === "waiting") return { state: "queued", message: poolWaitWords(t) };
+ // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer"). It keeps its task's clocks
- // (pool.ts): its wait limit until a worker first takes it, then each attempt's own running time; back in line after
- // an attempt (a worker paused, went quiet, restarted), it keeps its place.
- const res: PollResult = t.state === "waiting" ? { state: "queued", message: t.note === "resent" ? "Back in line for another GPU" : poolWaitWords(t) } : await pollTask(principal, t, meta, manifest, made);
++ // (pool.ts): its wait limit until a worker first takes it, then each attempt's own running time. Back in line after an
++ // attempt (a worker paused, went quiet, gave it back), it shows its kept place as any waiting run does, and once a
++ // worker has it again, the usual words: never a restart.
++ const res: PollResult = t.state === "waiting" ? { state: "queued", message: poolWaitWords(t) } : await pollTask(principal, t, meta, manifest, made);
+ if (res.state !== "queued" && res.state !== "running") return res;
+ // An account's run says only where it is: in line, or working on it (the owner's own runs keep the workers' words).
+ if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ownClocks: true };
+ return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ownClocks: true } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ownClocks: true };
+}
+
+/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */
+async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {
const p = taskProgress(t.id);
const kind = extraOf(t).made ?? made ?? "image";
const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;
diff --cc tests/admin-tokens.test.ts
index 830eee33,95744690..1a7dcffc
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@@ -29,10 -29,8 +29,9 @@@ const routes =
run: await import("@/app/api/admin/generations/[id]/route"),
outputs: await import("@/app/api/admin/outputs/[action]/route"),
queue: await import("@/app/api/admin/queue/route"),
+ queueSettings: await import("@/app/api/admin/queue/settings/route"),
workers: await import("@/app/api/admin/workers/route"),
worker: await import("@/app/api/admin/workers/[id]/route"),
- download: await import("@/app/api/admin/workers/download/route"),
reports: await import("@/app/api/admin/reports/route"),
audit: await import("@/app/api/admin/audit/route"),
files: await import("@/app/api/admin/files/[...path]/route"),
@@@ -247,10 -245,7 +246,9 @@@ describe("admin tokens: every admin rou
{ name: "POST remove", scope: "outputs:moderate", run: (o) => routes.outputs.POST(req("/api/admin/outputs/remove", { ...o, method: "POST", body: { assetIds: ["nope"] } }), ctx({ action: "remove" })) },
{ name: "GET files", scope: "outputs:view", run: (o) => routes.files.GET(req("/api/admin/files/outputs/nope.png", o), ctx({ path: ["outputs", "nope.png"] })) },
{ name: "GET queue", scope: "queue:read", run: (o) => routes.queue.GET(req("/api/admin/queue", o)) },
+ { name: "GET queue settings", scope: "queue:read", run: (o) => routes.queueSettings.GET(req("/api/admin/queue/settings", o)) },
+ { name: "PATCH queue settings", scope: "queue:write", run: (o) => routes.queueSettings.PATCH(req("/api/admin/queue/settings", { ...o, method: "PATCH", body: { fairShare: false } })) },
{ name: "GET workers", scope: "workers:read", run: (o) => routes.workers.GET(req("/api/admin/workers", o)) },
- { name: "GET download", scope: "workers:read", run: (o) => routes.download.GET(req("/api/admin/workers/download", o)) },
{ name: "POST workers", scope: "workers:tokens", run: (o) => routes.workers.POST(req("/api/admin/workers", { ...o, method: "POST", body: { name: `w${++n}` } })) },
{ name: "PATCH worker", scope: "workers:write", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { paused: true } }), ctx({ id: "nope" })) },
{ name: "PATCH worker rotate", scope: "workers:tokens", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { rotate: true } }), ctx({ id: "nope" })) },
diff --cc tests/pool-account-runs.test.ts
index 81301e72,00000000..b2fc67c9
mode 100644,000000..100644
--- a/tests/pool-account-runs.test.ts
+++ b/tests/pool-account-runs.test.ts
@@@ -1,615 -1,0 +1,615 @@@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";
+import { apiAs, loadRoutes, sha256, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Account runs on this install's GPUs go through the workers' line: each job of an account's run is a task for the
+ * workers that belongs to the account, never a request to a ComfyUI address. The account sees only "In line", "Working"
+ * and its result; an account's own session can never take or read such a task; a task back in line keeps its place and
+ * shows "In line" again; and with hosted runs off nothing changes. (The line's own rules for every job, one job per
+ * worker among them: tests/worker-queue.test.ts.)
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-account-runs-");
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing answers here: no test may reach a real ComfyUI on this machine. (Not port 9: the tests point local AI
+// helpers there.)
+const DEAD = "http://127.0.0.1:7";
+process.env.COMFYUI_URL = DEAD;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// The server's own fetch: recorded. Anything but the stand-ins answers 599 at once (no real network).
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ fetched.push(url);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const { getGeneration, toGeneration } = await import("@/server/generations");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const hosted = await import("@/server/hosted");
+const billing = await import("@/server/billing");
+const { listAccountRuns } = await import("@/server/account-admin");
+const { loadManifest, withoutSaveMetadata, planRelayOutputs, onComputer } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { ComputerRunner } = await import("@/lib/computer-runner");
+const { POOL_WORDS } = await import("@/lib/relay");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const MIN = 60_000;
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+let comfy: LocalComfy;
+let routes: ComputerRoutes;
+let fake: FakeBilling;
+let accountId = "";
+let cookie = "";
+let computerAccount = "";
+let computerCookie = "";
+
+beforeAll(async () => {
+ comfy = await startLocalComfy({ cors: "*", steps: 2, stepMs: 10, latencyMs: 10 });
+ allowed = [comfy.url];
+ routes = await loadRoutes();
+ fake = await startFakeBilling();
+ allowed.push(fake.url);
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;
+ // An account whose own GPU is "this computer": its session reaches the computer routes as acct:<id>.
+ computerAccount = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(computerAccount, { mode: "computer" });
+ computerCookie = `${auth.SESSION_COOKIE}=${auth.createSession(computerAccount).value}`;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await comfy.close();
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ process.env.COMFYUI_URL = DEAD;
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ fetched.length = 0;
+});
+
+/** A worker the owner added and resumed, allowed every lane, able to run every workflow. */
+function standInWorker(name = "stand-in", o: { paused?: boolean } = {}) {
+ const w = pool.addWorker(name);
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);
+ return w;
+}
+
+/** The worker program's side, as `fuobe worker run` drives it: the shared runner with the worker's token and its own ComfyUI. */
+function workerRunner(token: string) {
+ const api = apiAs(routes, null, { authorization: `Bearer ${token}` });
+ return new ComputerRunner(
+ {
+ api,
+ local: (url, init) => realFetch(url, init),
+ socket: (url) => new WebSocket(url) as never,
+ sha256,
+ origin: "http://localhost:3000",
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),
- beatExtra: () => ({ protocol: 1, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),
++ beatExtra: () => ({ protocol: 2, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),
+ },
+ { device: "worker", port: comfy.port, clientId: "worker-test" },
+ );
+}
+
+const request = (url: string, o: { method?: string; body?: unknown; cookie?: string | null; headers?: Record<string, string> } = {}) => {
+ const text = o.body === undefined ? undefined : JSON.stringify(o.body);
+ const headers: Record<string, string> = { ...SITE_HEADERS, ...(o.cookie !== null && { cookie: o.cookie ?? cookie }), ...(text && { "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), ...o.headers };
+ return new Request(`http://${HOST}${url}`, { method: o.method ?? (text ? "POST" : "GET"), headers, body: text });
+};
+const run = async (body: Record<string, unknown>, c = cookie) => {
+ const r = await generationsRoute.POST(request("/api/generations", { body, cookie: c }));
+ return { status: r.status, body: (await r.json()) as { items?: { id: string }[]; code?: string; error?: string } };
+};
+const tick = () => globalThis.__fuobeRunner?.tick();
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+async function until<T>(fn: () => T | Promise<T>, tries = 200, everyMs = 25): Promise<T> {
+ let v = await fn();
+ for (let i = 0; i < tries && !v; i++) {
+ await tick();
+ await new Promise((r) => setTimeout(r, everyMs));
+ v = await fn();
+ }
+ return v;
+}
+/** Requests to a ComfyUI address the server made itself (the stand-in worker's own ComfyUI is the worker's, not the server's). */
+const serverComfyCalls = () => fetched.filter((u) => u.startsWith(`${DEAD}/`) || /:818[89]\b|:819[01]\b/.test(u) || /\/(prompt|upload\/image|system_stats|history|view|queue|object_info)\b/.test(u));
+
+/** An account's task made straight in the line (no run route), for the queue's own rules. */
+let gens = 0;
+function accountTask(o: { lane?: string; account?: string; rankAt?: number; notAfter?: number; workflow?: string } = {}) {
+ const gid = `pool-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(gid, JSON.stringify({ account: o.account ?? accountId, place: "pool" }), now, now);
+ const lanes = allLanes(loadIndex(), sha);
+ const t = tasks.createTask({
+ principal: `acct:${o.account ?? accountId}`,
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], account: o.account ?? accountId, rankAt: o.rankAt ?? now, lane: o.lane ?? lanes[0]?.lane ?? "small", needs: { workflowId: o.workflow ?? loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 }, notAfter: o.notAfter },
+ });
+ return { id: t.id, generationId: gid };
+}
+
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+const beatAs = (w: { id: string }, now = Date.now()) =>
- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
++ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
+const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);
+
+describe("with hosted runs off, nothing changes", () => {
+ it("an account with no GPU of its own gets today's answer, and no task is made", async () => {
+ delete process.env.FUOBE_HOSTED_RUNS;
+ standInWorker();
+ expect(hosted.poolReady()).toBe(false);
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;
+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("connect-gpu");
+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);
+ expect(serverComfyCalls()).toEqual([]);
+ });
+
+ it("switched on with nothing to answer for the runs (no billing service, no free runs), they stay closed", async () => {
+ delete process.env.FUOBE_HOSTED_FREE;
+ standInWorker();
+ expect(hosted.poolReady()).toBe(false);
+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("connect-gpu");
+ // A billing service that answers opens them.
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ expect(hosted.poolReady()).toBe(true);
+ });
+});
+
+describe("where hosted runs may go", () => {
+ it("on the workers: a worker the owner allowed a lane, paused or not; none at all closes them", () => {
+ expect(hosted.poolReady()).toBe(false);
+ const w = standInWorker("paused one", { paused: true });
+ expect(hosted.poolReady()).toBe(true);
+ pool.patchWorker(w.id, { revoke: true });
+ expect(hosted.poolReady()).toBe(false);
+ });
+
+ it("on this install's own ComfyUI server: only an address on this machine", () => {
+ setSetting("comfyWhere", "server");
+ setSetting("comfyUrl", "http://127.0.0.1:3399");
+ expect(hosted.poolReady()).toBe(true);
+ for (const url of ["http://10.0.0.5:8188", "https://comfy.example.com", "http://studio:3399"]) {
+ setSetting("comfyUrl", url);
+ expect(hosted.poolReady(), url).toBe(false);
+ }
+ setSetting("comfyWhere", "computer");
+ setSetting("comfyUrl", "http://127.0.0.1:3399");
+ expect(hosted.poolReady()).toBe(false);
+ });
+});
+
+describe("an account's run on the workers", () => {
+ it("with no ComfyUI address the server could reach, it becomes the account's task, and a stand-in worker renders it", async () => {
+ const w = standInWorker();
+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" });
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const id = r.body.items![0].id;
+ const t = await until(() => taskOf(id));
+ expect(t).toBeDefined();
+ expect(t!.principal).toBe(`acct:${accountId}`);
+ expect(t!.pools).toBe("pool");
+ expect(t!.account).toBe(accountId);
+ // It waits in line, in plain words, with its place.
+ await until(() => getGeneration(id)?.message === POOL_WORDS.inLine);
+ const waiting = getGeneration(id)!;
+ expect(waiting.message).toBe(POOL_WORDS.inLine);
+ expect(waiting.queue?.place).toBe(1);
+ expect(waiting.place).toBe("pool");
+
+ // The worker takes it through the same routes as every worker, and renders it on its own ComfyUI.
+ const worker = workerRunner(w.token);
+ const beat = await worker.beat();
+ expect(beat?.claimableNow).toBe(1);
+ await worker.claimAndRun();
+ expect(rowOf(t!.id).state).toBe("done");
+ const g = await until(() => {
+ const x = getGeneration(id);
+ return x && x.status !== "queued" && x.status !== "running" ? x : null;
+ });
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(g!.outputs.length).toBeGreaterThan(0);
+ // The server never called a ComfyUI address for it.
+ expect(serverComfyCalls()).toEqual([]);
+ // The workers' log: who took it, and how it ended.
+ const log = db().prepare("SELECT event, worker_id, principal FROM worker_jobs WHERE task_id = ? ORDER BY id").all(t!.id) as { event: string; worker_id: string; principal: string }[];
+ expect(log.map((x) => x.event)).toEqual(["claimed", "finished", "done"]);
+ expect(log.every((x) => x.worker_id === w.id && x.principal === `acct:${accountId}`)).toBe(true);
+ });
+
+ it("an account's own session can never claim or read a task for the workers, even one of its own runs", async () => {
+ standInWorker();
+ const mine = accountTask({ account: computerAccount });
+ const api = apiAs(routes, computerCookie);
+ // Claim: nothing (a task for the workers is never a computer's own).
+ const claim = await api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "device-own-1", running: [] }) });
+ expect(claim.status).toBe(204);
+ // A worker takes it; the account then names it with any lease: unknown.
+ const w = db().prepare("SELECT * FROM relay_workers LIMIT 1").get() as { id: string };
+ beatAs(w);
+ const got = claimAs(w)!;
+ expect(got.id).toBe(mine.id);
+ for (const [path, init] of [
+ [`/api/gpu/computer/tasks/${mine.id}/report`, { method: "POST", headers: { "x-fuobe-lease": got.lease, "Content-Type": "application/json" }, body: JSON.stringify({ event: "running", value: 1, max: 2 }) }],
+ [`/api/gpu/computer/tasks/${mine.id}/inputs/0`, { headers: { "x-fuobe-lease": got.lease } }],
+ [`/api/gpu/computer/tasks/${mine.id}/outputs/0`, { headers: { "x-fuobe-lease": got.lease } }],
+ [`/api/gpu/computer/tasks/${mine.id}/release`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: got.lease }) }],
+ ] as [string, RequestInit][]) {
+ const res = await api(path, init);
+ expect(res.status, path).toBe(404);
+ }
+ // A beat that names it (even under the worker's device) touches nothing of it, and hears no stop of it.
+ tasks.setTask(mine.id, { stop: 1 });
+ const beat = await api("/api/gpu/computer/beat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: `wkr-${w.id}`, running: [{ task: mine.id, value: 9, max: 9 }], stopped: [mine.id] }) });
+ expect(beat.status).toBe(200);
+ expect(((await beat.json()) as { stops: unknown[] }).stops).toEqual([]);
+ expect(rowOf(mine.id).stop).toBe(1);
+ expect(tasks.getTask(`acct:${computerAccount}`, mine.id)).toBeNull();
+ // The server's own reads, as the run's account, still find it.
+ expect(tasks.ownTask(`acct:${computerAccount}`, mine.id)?.id).toBe(mine.id);
+ });
+
+ it("refuses a run that no worker would ever take, before anything is queued", async () => {
+ const w = standInWorker();
+ pool.patchWorker(w.id, { allow: {} });
+ pool.addWorker("lane-less");
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;
+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });
+ expect(r.status).toBe(403);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);
+ });
+
+ it("a file input in params.extra is one the run sent, never a name in the workers' folders", async () => {
+ standInWorker();
+ const uploadsRoute = await import("@/app/api/uploads/route");
+ const { TINY_PNG } = await import("./helpers/fake-comfy-runner");
+ const up = await uploadsRoute.POST(
+ new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }),
+ );
+ expect(up.status).toBe(201);
+ const { url } = (await up.json()) as { url: string };
+ // A workflow that loads a picture: the name in params.extra would replace the picture the run sent.
+ const r = await run({ feature: "image", modelId: "oss-rmbg", op: "bg-remove", inputs: { images: [url] }, params: { extra: { image: "fuobe_someone_elses.png" } } });
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const t = await until(() => taskOf(r.body.items![0].id));
+ expect(t).toBeDefined();
+ expect(t!.graph_json ?? "").not.toContain("fuobe_someone_elses.png");
+ // The picture its graph loads is the one this run sent, kept for its task.
+ const graph = JSON.parse(t!.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+ const loaded = Object.values(graph)
+ .filter((x) => x.class_type === "LoadImage")
+ .map((x) => String(x.inputs.image));
+ expect(loaded).toHaveLength(1);
+ const staged = db().prepare("SELECT principal, task_id FROM relay_inputs WHERE name = ?").get(loaded[0]) as { principal: string; task_id: string | null } | undefined;
+ expect(staged).toEqual({ principal: `acct:${accountId}`, task_id: t!.id });
+ });
+
+ it("a graph that names a file the run didn't send is refused before it is queued", async () => {
+ const { graphProblem } = await import("@/lib/local-comfy");
+ const graph = { "1": { class_type: "LoadImage", inputs: { image: "fuobe_someone_elses.png" } }, "2": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "x" } } };
+ expect(graphProblem(graph as never, ["fuobe_mine.png"])).toBeTruthy();
+ expect(graphProblem({ ...graph, "1": { class_type: "LoadImage", inputs: { image: "fuobe_mine.png" } } } as never, ["fuobe_mine.png"])).toBeNull();
+ });
+});
+
+describe("the line", () => {
+ it("a requeue keeps the run's place (rank_at), it shows In line again, and its wait limit is over", async () => {
+ const w = standInWorker();
+ const first = accountTask({ rankAt: Date.now() - 5 * MIN, notAfter: Date.now() + MIN });
+ const later = accountTask({ rankAt: Date.now() });
+ const rank = rowOf(first.id).rank_at;
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(first.id);
+ // The worker pauses at once (another program on the GPU): the job goes back in line at no cost.
+ pool.workerBeat(
+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,
- pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: true, why: "gpu-busy:game.exe", until: null }, gpu: {}, running: [{ task: first.id }], stopped: [] }),
++ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: true, why: "gpu-busy:game.exe", until: null }, gpu: {}, running: [{ task: first.id }], stopped: [] }),
+ );
+ const back = rowOf(first.id);
+ expect(back.state).toBe("waiting");
+ expect(back.rank_at).toBe(rank);
+ expect(back.requeues).toBe(0);
+ // First in line again, ahead of the later run, and past its wait limit it still waits: a worker took it once.
+ expect(pool.queueOfGeneration(first.generationId)?.place).toBe(1);
+ expect(pool.queueOfGeneration(later.generationId)?.place).toBe(2);
+ pool.sweepPool(Date.now() + 10 * MIN);
+ expect(rowOf(first.id).state).toBe("waiting");
+ // A run no worker has taken yet still fails at its wait limit, not charged.
+ const never = accountTask({ notAfter: Date.now() + MIN });
+ pool.sweepPool(Date.now() + 2 * MIN);
+ expect(rowOf(never.id).state).toBe("failed");
+ // Its row says In line, never a pause or a GPU word.
+ const g = toGeneration(db().prepare("SELECT * FROM generations WHERE id = ?").get(first.generationId) as never);
+ expect(g.message).toBe(POOL_WORDS.inLine);
+ });
+
+ it("place and wait count every task ahead in the order the workers serve them, whatever its lane", () => {
+ const w = standInWorker();
+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
+ expect(lanes.length).toBeGreaterThan(1);
+ const now = Date.now();
+ accountTask({ lane: lanes[0], rankAt: now - 3 * MIN });
+ accountTask({ lane: lanes[1], rankAt: now - 2 * MIN });
+ const mine = accountTask({ lane: lanes[0], rankAt: now - MIN });
+ beatAs(w);
+ const place = pool.queueOfGeneration(mine.generationId);
+ expect(place?.place).toBe(3);
+ expect(place?.etaSeconds).toBeGreaterThan(0);
+ // The billing service's line facts read the same line.
+ const facts = hosted.queueFacts(accountId, loadManifest().workflows[0].id);
+ expect(facts.ahead).toBe(3);
+ expect(facts.workersOnline).toBe(1);
+ expect(facts.mine.waiting).toBe(3);
+ });
+
+});
+
+describe("what an account reads about its run", () => {
+ it("a failed run on this install's GPUs shows one plain sentence and no Fix it; the owner reads the reason", () => {
+ const now = Date.now();
+ const id = `plain-${now}`;
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, fix_json, created_at, updated_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', 'failed', ?, '[]', ?, ?, ?, ?)",
+ )
+ .run(id, JSON.stringify({ account: accountId, place: "pool", feature: "image", modelId: "oss-z-image-turbo" }), "Can't reach ComfyUI at http://10.0.0.5:8188 (C:\\Users\\x\\ComfyUI)", JSON.stringify({ code: "comfy_missing_node", items: [] }), now, now);
+ const g = getGeneration(id)!;
+ expect(g.error).toBe(POOL_WORDS.failed);
+ expect(g.fix).toBeUndefined();
+ const owner = listAccountRuns({ account: accountId }).items.find((x) => x.id === id);
+ expect(owner?.detail).toContain("Can't reach ComfyUI");
+ // Fuobe's own words about the account's side stay as they are.
+ db().prepare("UPDATE generations SET error = ? WHERE id = ?").run("Your files have reached 3 GB. Delete some runs to make room.", id);
+ expect(getGeneration(id)!.error).toBe("Your files have reached 3 GB. Delete some runs to make room.");
+ });
+
+ it("its output check is part of Working, and a stopped run says Not charged only when its hold set something aside", () => {
+ const now = Date.now();
+ const insert = (id: string, status: string, request: Record<string, unknown>, stage: string | null = null) =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, stage, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', ?, ?, ?, '[]', ?, ?)")
+ .run(id, status, stage, JSON.stringify({ account: accountId, ...request }), now, now);
+ insert(`check-pool-${now}`, "running", { place: "pool" }, "checking");
+ insert(`check-own-${now}`, "running", {}, "checking");
+ const pooled = getGeneration(`check-pool-${now}`)!;
+ expect(pooled.stage).toBeUndefined();
+ expect(pooled.message).toBe(POOL_WORDS.working);
+ // On the account's own GPU, as before.
+ expect(getGeneration(`check-own-${now}`)!.stage).toBe("checking");
+ insert(`charged-${now}`, "canceled", { place: "pool", hold: "h_1", charged: true });
+ insert(`free-${now}`, "failed", { place: "pool", hold: "h_2" });
+ expect(getGeneration(`charged-${now}`)!.notCharged).toBe(true);
+ expect(getGeneration(`free-${now}`)!.notCharged).toBeUndefined();
+ // Neither field ever reaches the page's copy of the request.
+ expect("charged" in getGeneration(`charged-${now}`)!.request).toBe(false);
+ });
+
+ it("while it goes, only In line or Working, whatever the technical words were", () => {
+ const now = Date.now();
+ const id = `words-${now}`;
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, message, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'running', ?, '[]', ?, ?, ?)")
+ .run(id, JSON.stringify({ account: accountId, place: "pool" }), "In ComfyUI's queue · 2 ahead", now, now);
+ expect(getGeneration(id)!.message).toBe(POOL_WORDS.working);
+ db().prepare("UPDATE generations SET status = 'queued', message = 'Back in line for another GPU' WHERE id = ?").run(id);
+ expect(getGeneration(id)!.message).toBe(POOL_WORDS.inLine);
+ });
+});
+
+describe("graphs and results for the workers", () => {
+ it("every VideoHelperSuite save node saves no metadata", () => {
+ const wf = withoutSaveMetadata({
+ "1": { class_type: "VHS_VideoCombine", inputs: { save_metadata: true, filename_prefix: "x" } },
+ "2": { class_type: "VHS_VideoCombine", inputs: {} },
+ "3": { class_type: "SaveImage", inputs: {} },
+ "4": { class_type: "VHS_SaveImageSequence", inputs: { save_metadata: true } },
+ "5": { class_type: "VHS_LoadVideo", inputs: { video: "x.mp4" } },
+ "6": { class_type: "SomeOtherSave", inputs: { save_metadata: true } },
+ } as never) as unknown as Record<string, { inputs: Record<string, unknown> }>;
+ expect(wf["1"].inputs.save_metadata).toBe(false);
+ expect(wf["2"].inputs.save_metadata).toBe(false);
+ expect(wf["3"].inputs.save_metadata).toBeUndefined();
+ expect(wf["4"].inputs.save_metadata).toBe(false);
+ expect(wf["5"].inputs).toEqual({ video: "x.mp4" });
+ expect(wf["6"].inputs.save_metadata).toBe(true);
+ });
+
+ it("an account's clip run on the workers is queued with no metadata in its clip saves", async () => {
+ standInWorker();
+ const { comfyProvider } = await import("@/server/providers/comfyui");
+ const { TINY_MP4 } = await import("./helpers/fake-comfy-runner");
+ const prior = process.env.FUOBE_POOL_MEDIA_INPUTS;
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";
+ try {
+ const route = { provider: "comfyui", endpoint: "interpolate-rife-vfi", op: "interpolate" } as never;
+ const sent = await hosted.runOnPool(accountId, async () => {
+ const video = (await comfyProvider.prepareFile!(TINY_MP4, "video/mp4", "clip.mp4", route))!;
+ return comfyProvider.submit({ route, input: { video, extra: { multiplier: 2 } } as never, generationId: `vhs-${Date.now()}` } as never);
+ });
+ const t = rowOf(String((sent.meta as { relay: string }).relay));
+ expect(t.principal).toBe(`acct:${accountId}`);
+ expect(t.pools).toBe("pool");
+ const graph = JSON.parse(t.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+ const saves = Object.values(graph).filter((n) => n.class_type === "VHS_VideoCombine");
+ expect(saves.length).toBeGreaterThan(0);
+ for (const node of saves) expect(node.inputs.save_metadata).toBe(false);
+ expect(serverComfyCalls()).toEqual([]);
+ } finally {
+ if (prior === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;
+ else process.env.FUOBE_POOL_MEDIA_INPUTS = prior;
+ }
+ });
+
+ it("an owner's job on the workers keeps no more results than its workflow makes, and nothing past the disk's free floor", () => {
+ const entry = { status: { status_str: "success", completed: true }, outputs: { "9": { images: Array.from({ length: 40 }, (_, i) => ({ filename: `x_${i}.png`, subfolder: "", type: "output" })) } } };
+ const t = { id: "owner-task-0001x", workflow_id: loadManifest().workflows.find((x) => x.outputs.length === 1)!.id, meta_batch: 0, prefix: null, extra_json: JSON.stringify({ outputs: 1 }), pools: "pool" };
+ const plan = onComputer("owner", () => planRelayOutputs(t, [entry], false));
+ expect("wanted" in plan && plan.wanted.length).toBe(16);
+ // The owner's own computer keeps every result, as before.
+ const own = onComputer("owner", () => planRelayOutputs({ ...t, pools: null }, [entry], false));
+ expect("wanted" in own && own.wanted.length).toBe(40);
+ globalThis.__fuobeTestDiskFree = 1;
+ try {
+ const full = onComputer("owner", () => planRelayOutputs(t, [entry], false));
+ expect("error" in full && full.error).toMatch(/no room/);
+ } finally {
+ globalThis.__fuobeTestDiskFree = 1e13;
+ }
+ });
+});
+
+describe("nothing of a run on the workers goes to a ComfyUI address", () => {
+ it("an account's picture is made again from its pixels (no EXIF) and kept for its task", async () => {
+ const sharp = (await import("sharp")).default;
+ const jpeg = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#c33" } })
+ .jpeg()
+ .withExif({ IFD0: { Copyright: "private note", Artist: "someone" } })
+ .toBuffer();
+ expect((await sharp(jpeg).metadata()).exif).toBeDefined();
+ const { comfyProvider } = await import("@/server/providers/comfyui");
+ const staged = await hosted.runOnPool(accountId, () => comfyProvider.prepareFile!(jpeg, "image/jpeg", "me.jpg"));
+ const row = db().prepare("SELECT principal, content_type FROM relay_inputs WHERE name = ?").get(staged) as { principal: string; content_type: string };
+ expect(row).toEqual({ principal: `acct:${accountId}`, content_type: "image/png" });
+ const fs = await import("node:fs");
+ const path = await import("node:path");
+ const kept = fs.readFileSync(path.join(dir, "relay", "in", staged));
+ const meta = await sharp(kept).metadata();
+ expect(meta.format).toBe("png");
+ expect(meta.exif).toBeUndefined();
+ expect(serverComfyCalls()).toEqual([]);
+ });
+
+ it("a run on the workers with no account behind it never sends a file or a prompt", async () => {
+ const { comfyProvider } = await import("@/server/providers/comfyui");
+ const png = Buffer.from("89504e470d0a1a0a", "hex");
+ await expect(hosted.runOnPool(null, () => comfyProvider.prepareFile!(png, "image/png", "x.png"))).rejects.toThrow();
+ const route = { provider: "comfyui", endpoint: loadManifest().workflows[0].id, op: "t2i" } as never;
+ await expect(hosted.runOnPool(null, () => comfyProvider.submit({ route, input: { prompt: "a lighthouse" } as never, generationId: "guest-run-0001" } as never))).rejects.toThrow();
+ expect(serverComfyCalls()).toEqual([]);
+ });
+
+ it("a run sent to this install's own ComfyUI before Settings moved to the workers is still followed there", async () => {
+ const { comfyProvider } = await import("@/server/providers/comfyui");
+ setSetting("comfyUrl", DEAD);
+ // (It answers nothing here: the poll says so, and never goes round in circles.)
+ await hosted
+ .runOnPool(accountId, () => comfyProvider.poll({ externalId: crypto.randomUUID(), meta: { workflowId: loadManifest().workflows[0].id, generationId: "moved-0001" }, model: undefined } as never))
+ .catch((e: Error) => expect(e.message).not.toMatch(/call stack/i));
+ // Asked of the address it was sent to, not of the workers' line.
+ expect(fetched.some((u) => u.startsWith(`${DEAD}/`))).toBe(true);
+ });
+});
+
+describe("what a run on the workers is shaped by", () => {
+ it("the workers' facts (the least VRAM and RAM of those allowed its lane), never the account's own computer's", async () => {
+ const big = standInWorker("big");
+ const small = standInWorker("small");
+ const facts = (w: { id: string }, f: Record<string, unknown>) => db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify(f), w.id);
+ facts(big, { vramBytes: 96 * 2 ** 30, ramBytes: 128 * 2 ** 30, device: "cuda:0 Test GPU" });
+ facts(small, { vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Other GPU" });
+ expect(pool.poolFacts(null)).toEqual({ vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Test GPU" });
+ // A lane only the big one is allowed: its facts alone.
+ const lane = allLanes(loadIndex(), sha)[0].lane;
+ pool.patchWorker(small.id, { allow: {} });
+ expect(pool.poolFacts(lane).vramBytes).toBe(96 * 2 ** 30);
+ // Workers that name different kinds of device: none is assumed.
+ pool.patchWorker(small.id, { allow: { [lane]: { delayMs: 0 } } });
+ facts(small, { vramBytes: 24 * 2 ** 30, device: "mps" });
+ expect(pool.poolFacts(null).device).toBeUndefined();
+ facts(small, { vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Other GPU" });
+
+ // The account's own computer said something else: a run on the workers never reads it; a run on that computer does.
+ tasks.beat(`acct:${computerAccount}`, { device: "device-own-facts", takeover: true, facts: { ramBytes: 2 ** 30, vramBytes: 2 ** 30, device: "mps" } });
+ const { comfyRam, comfyDevice } = await import("@/server/providers/comfyui");
+ expect(hosted.runOnPool(computerAccount, () => comfyRam())).toBe(64 * 2 ** 30);
+ expect(await hosted.runOnPool(computerAccount, () => comfyDevice())).toBe("cuda");
+ expect(onComputer(`acct:${computerAccount}`, () => comfyRam())).toBe(2 ** 30);
+ expect(await onComputer(`acct:${computerAccount}`, () => comfyDevice())).toBe("mps");
+ expect(serverComfyCalls()).toEqual([]);
+ });
+});
+
+describe("files for runs on the workers", () => {
+ it("an account may add only the kinds of file the workers take, whatever the policy allows", async () => {
+ const uploadsRoute = await import("@/app/api/uploads/route");
+ const { TINY_MP4, TINY_PNG } = await import("./helpers/fake-comfy-runner");
+ standInWorker();
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ const before = fake.policy;
+ fake.policy = { ...before, hosted: true, uploads: { image: true, video: true, audio: true }, ttlS: 0 };
+ const prior = process.env.FUOBE_POOL_MEDIA_INPUTS;
+ delete process.env.FUOBE_POOL_MEDIA_INPUTS;
+ try {
+ const up = (bytes: Buffer, type: string, name: string) =>
+ uploadsRoute.POST(new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }, body: new Uint8Array(bytes) }));
+ expect((await up(TINY_PNG, "image/png", "me.png")).status).toBe(201);
+ expect((await up(TINY_MP4, "video/mp4", "me.mp4")).status).toBe(403);
+ // The workers take clips too: so may the account.
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";
+ expect((await up(TINY_MP4, "video/mp4", "me.mp4")).status).toBe(201);
+ } finally {
+ fake.policy = before;
+ if (prior === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;
+ else process.env.FUOBE_POOL_MEDIA_INPUTS = prior;
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ }
+ });
+});
diff --cc tests/pool-limits.test.ts
index 881f5fdd,00000000..c8a753d9
mode 100644,000000..100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@@ -1,566 -1,0 +1,566 @@@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Limits on runs on this install's GPUs: the policy's runs at once, runs waiting, runs an hour and runs from one address
+ * an hour count those runs only, together with making the run's rows (requests that arrive together never pass them
+ * together); runs on an account's own GPU keep the studio's own limits. Also where a run goes: the policy's default
+ * place, an own GPU that doesn't answer (asked, never moved), the kinds a policy allows, a guest's policy, every step of
+ * a chain checked and priced once, and the real size of a picture in its price facts.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-limits-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+delete process.env.FUOBE_TRUST_PROXY;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const hostedRun = await import("@/server/hosted-run");
+const limits = await import("@/server/pool-limits");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { PLACE_ASK_HEADER } = await import("@/lib/guest-access");
+const hosted = await import("@/server/hosted");
+const { getGeneration } = await import("@/server/generations");
+const { ACCOUNT_MESSAGES } = await import("@/server/account-files");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const IMAGE = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" };
+
+let fake: FakeBilling;
+let n = 0;
+/** The stand-in worker of the test that runs. */
+let worker: { id: string };
+
+/** A new account and its cookie (each test gets its own, so counts never carry over). */
+function account(o: { gpu?: "online" | "offline" } = {}) {
+ const a = auth.createAccount(`limits-${++n}@example.com`, "long enough");
+ if (o.gpu) {
+ auth.setAccountGpu(a.id, { mode: "computer" });
+ if (o.gpu === "online") tasks.beat(`acct:${a.id}`, { device: `device-${n}`, takeover: true, facts: { vramBytes: 24 * 2 ** 30 } });
+ }
+ return { id: a.id, cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` };
+}
+
+const post = async (body: Record<string, unknown>, cookie: string, headers: Record<string, string> = {}) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...headers }, body: text }),
+ );
+ return { status: r.status, headers: r.headers, body: (await r.json()) as { items?: { id: string; place?: string }[]; code?: string; error?: string } };
+};
+
+/** Runs on this install's GPUs an account has made. */
+const poolRuns = (id: string) =>
+ (db().prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') = 'pool'").get(id) as { n: number }).n;
+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;
+
+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);
+ return w;
+}
+
+const withBilling = (policy: Record<string, unknown> = {}) => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...FAKE_POLICY, ...policy, limits: { ...FAKE_POLICY.limits, outputsPerRun: 4, ...((policy.limits as object) ?? {}) }, ttlS: 0 };
+ billing.resetBillingCache();
+};
+
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ allowed = [fake.url];
+ auth.setPassword("install password");
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_TRUST_PROXY"]) delete process.env[k];
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ delete process.env.FUOBE_TRUST_PROXY;
+ fake.policy = { ...FAKE_POLICY };
+ fake.guestPolicy = null;
+ fake.price = { amount: 7, version: "v7" };
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ // Nothing of an earlier test waits in line.
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ worker = standInWorker();
+});
+
+const tick = () => globalThis.__fuobeRunner?.tick();
+async function until<T>(fn: () => T | Promise<T>, tries = 200, everyMs = 25): Promise<T> {
+ let v = await fn();
+ for (let i = 0; i < tries && !v; i++) {
+ await tick();
+ await new Promise((r) => setTimeout(r, everyMs));
+ v = await fn();
+ }
+ return v;
+}
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as { id: string; state: string } | undefined;
+const workerRow = () => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(worker.id) as import("@/server/computer/workers").WorkerRow;
+/** The stand-in worker takes the next task in line, as the worker program does. */
+function workerTakes() {
- pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
++ pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
+ return pool.workerClaim(workerRow(), [], Date.now());
+}
+const started = (generationId: string) => !!(db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").get(generationId) as { started_at: number | null } | undefined)?.started_at;
+const preview = async (body: Record<string, unknown>, cookie: string) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(new Request(`http://${HOST}/api/generations?preview=1`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }));
+ return { status: r.status, body: (await r.json()) as { place?: string; quote?: { amount: number } } };
+};
+
+const SHOWN = { shown: { amount: 7, priceVersion: "v7" } };
+
+describe("runs at once on this install's GPUs", () => {
+ it("10 requests sent together against a limit of 2 make exactly 2 runs, and every other hold goes back", async () => {
+ withBilling({ limits: { activeRuns: 2, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const before = fake.holds.size;
+ const answers = await Promise.all(Array.from({ length: 10 }, () => post({ ...IMAGE, ...SHOWN }, a.cookie)));
+ const made = answers.filter((r) => r.status === 201);
+ expect(made.length, JSON.stringify(answers.map((r) => [r.status, r.body.error]))).toBe(2);
+ expect(poolRuns(a.id)).toBe(2);
+ for (const r of answers.filter((x) => x.status !== 201)) {
+ expect(r.status).toBe(429);
+ expect(r.body.code).toBe("active-runs");
+ expect(r.body.error).toBe(limits.POOL_LIMIT_WORDS.active(2));
+ }
+ // Each request that got a hold and made nothing gives it back (an outbox release).
+ const holds = fake.holds.size - before;
+ const releases = (db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE kind = 'release'").get() as { n: number }).n;
+ expect(holds - 2).toBe(releases);
+ });
+
+ it("the count and the rows are one transaction: a second count inside it sees the first run", () => {
+ const a = account();
+ const p = { limits: { activeRuns: 1, waiting: 0, runsPerHour: 0, outputsPerRun: 0, maxMegapixels: 0, maxSeconds: 0, keepDays: 0, spaceBytes: 0 } };
+ const insert = () =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(`tx-${++n}`, JSON.stringify({ account: a.id, place: "pool" }), Date.now(), Date.now());
+ const first = limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null } }, insert);
+ expect(first.ok).toBe(true);
+ const second = limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null } }, insert);
+ expect(second.ok).toBe(false);
+ // A refusal thrown inside keeps nothing it wrote.
+ const p2 = { ...p, limits: { ...p.limits, activeRuns: 5 } };
+ const r = limits.admitRun({ accountId: a.id, pool: { policy: p2, addr: null } }, () => {
+ insert();
+ throw new limits.AdmitRefused({ status: 403, error: "no", code: "not-offered" });
+ });
+ expect(r.ok).toBe(false);
+ expect(poolRuns(a.id)).toBe(1);
+ });
+
+ it("runs on the account's own GPU never count against the policy, and keep the studio's own limit of 4", async () => {
+ withBilling({ limits: { activeRuns: 1, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ for (let i = 0; i < 3; i++) {
+ const r = await post(IMAGE, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBeUndefined();
+ }
+ expect(ownRuns(a.id)).toBe(3);
+ // One on this install's GPUs still fits its policy's 1.
+ const pooled = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(pooled.status, JSON.stringify(pooled.body)).toBe(201);
+ expect(poolRuns(a.id)).toBe(1);
+ // The studio's own 4 counts every run, as before.
+ const fifth = await post(IMAGE, a.cookie);
+ expect(fifth.status).toBe(429);
+ });
+
+ it("with a free install (no billing service) the policy's limits apply to runs there too", async () => {
+ const a = account();
+ const p = await billing.policy(a.id);
+ expect(p).toBe(billing.OPEN_POLICY);
+ // Lower than the studio's own limits, so only the policy's own count can stop these runs.
+ const was = { ...billing.OPEN_POLICY.limits };
+ try {
+ billing.OPEN_POLICY.limits.activeRuns = 1;
+ expect((await post(IMAGE, a.cookie)).status).toBe(201);
+ const second = await post(IMAGE, a.cookie);
+ expect(second.status).toBe(429);
+ expect(second.body.error).toBe(limits.POOL_LIMIT_WORDS.active(1));
+ expect(second.body.error).not.toBe(ACCOUNT_MESSAGES.activeRuns);
+ billing.OPEN_POLICY.limits.activeRuns = 0;
+ billing.OPEN_POLICY.limits.runsPerHour = 2;
+ expect((await post(IMAGE, a.cookie)).status).toBe(201);
+ const third = await post(IMAGE, a.cookie);
+ expect(third.status).toBe(429);
+ expect(third.body.code).toBe("limit");
+ expect(third.body.error).toBe(limits.POOL_LIMIT_WORDS.hourly);
+ } finally {
+ Object.assign(billing.OPEN_POLICY.limits, was);
+ }
+ expect(poolRuns(a.id)).toBe(2);
+ });
+});
+
+describe("runs waiting, runs an hour, runs from one address", () => {
+ it("a run that hasn't started counts as waiting", async () => {
+ withBilling({ limits: { activeRuns: 5, waiting: 1, runsPerHour: 0 } });
+ const a = account();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ const second = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(second.status).toBe(429);
+ expect(second.body.error).toBe(limits.POOL_LIMIT_WORDS.waiting(1));
+ // Once a worker has taken it (its run has started), the next one may wait.
+ const id = (db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') = ?").get(a.id) as { id: string }).id;
+ const t = await until(() => taskOf(id));
+ expect(workerTakes()?.id).toBe(t!.id);
+ expect(await until(() => started(id))).toBe(true);
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ });
+
+ it("runs an hour are counted in the database, one per press of Run, with a time to try again", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 2 } });
+ const a = account();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ const third = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(third.status).toBe(429);
+ expect(third.body.code).toBe("limit");
+ expect(Number(third.headers.get("retry-after"))).toBeGreaterThan(3000);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM pool_admissions WHERE account = ?").get(a.id) as { n: number }).n).toBe(2);
+ // A restart (new in-memory counts) changes nothing.
+ resetRates();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(429);
+ });
+
+ it("runs from one client address an hour, across accounts, only behind a trusted proxy, kept as a hash", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, addressRunsPerHour: 2 } });
+ const from = { "x-forwarded-for": "203.0.113.9" };
+ const a = account();
+ const b = account();
+ // No trusted proxy: clients can't be told apart, so no address count.
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie, from)).status).toBe(201);
+ process.env.FUOBE_TRUST_PROXY = "1";
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie, from)).status).toBe(201);
+ expect((await post({ ...IMAGE, ...SHOWN }, b.cookie, from)).status).toBe(201);
+ const third = await post({ ...IMAGE, ...SHOWN }, b.cookie, from);
+ expect(third.status).toBe(429);
+ expect(third.body.error).toBe(limits.POOL_LIMIT_WORDS.address);
+ expect((await post({ ...IMAGE, ...SHOWN }, b.cookie, { "x-forwarded-for": "198.51.100.4" })).status).toBe(201);
+ const kept = db().prepare("SELECT addr FROM pool_admissions WHERE addr IS NOT NULL").all() as { addr: string }[];
+ expect(kept.length).toBeGreaterThan(0);
+ expect(kept.every((r) => /^[0-9a-f]{32}$/.test(r.addr) && !r.addr.includes("203"))).toBe(true);
+ });
+});
+
+describe("where a run goes", () => {
+ it("the policy's default place: this install's GPUs first, even with the account's own GPU online; a named place wins", async () => {
+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBe("pool");
+ // The request a page gets back (and sends again on Retry) never says where it ran.
+ expect((r.body.items![0] as { request?: Record<string, unknown> }).request?.place).toBeUndefined();
+ const own = await post({ ...IMAGE, place: "own" }, a.cookie);
+ expect(own.status).toBe(201);
+ expect(own.body.items![0].place).toBeUndefined();
+ // Without it, the own GPU first as before.
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const again = await post(IMAGE, a.cookie);
+ expect(again.body.items![0].place).toBeUndefined();
+ // The status tells the pages.
+ const status = await visitorStatus(auth.accountById(a.id)!);
+ expect(status.viewer.prefer).toBeUndefined();
+ withBilling({ prefer: "pool" });
+ expect((await visitorStatus(auth.accountById(a.id)!)).viewer.prefer).toBe("pool");
+ });
+
+ it("with this install's GPUs first, a run that names no place and that they don't take runs on the account's own GPU", async () => {
+ withBilling({ prefer: "pool", pool: { deny: ["oss-z-image-turbo"] }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ const r = await post(IMAGE, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBeUndefined();
+ // Named, it is a refusal (the person asked for that place).
+ const named = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(named.status).toBe(403);
+ expect(named.body.code).toBe("not-offered");
+ });
+
+ it("an own GPU that doesn't answer: a run that named no place is asked about, never moved and charged", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "offline" });
+ const holds = fake.holds.size;
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe("own-gpu-offline");
+ expect(r.headers.get(PLACE_ASK_HEADER)).toBe("1");
+ expect(fake.holds.size).toBe(holds);
+ expect(poolRuns(a.id)).toBe(0);
+ // Asked for this install's GPUs, it runs there.
+ const yes = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(yes.status, JSON.stringify(yes.body)).toBe(201);
+ expect(poolRuns(a.id)).toBe(1);
+ });
+
+ it("an own GPU that doesn't answer: a run this install's GPUs wouldn't take goes to that GPU, as before, never asked about", async () => {
+ const a = account({ gpu: "offline" });
+ const own = (r: Awaited<ReturnType<typeof post>>, why: string) => {
+ expect(r.body.code, why).not.toBe("own-gpu-offline");
+ expect(r.headers.get(PLACE_ASK_HEADER), why).toBeNull();
+ expect(r.status, `${why}: ${JSON.stringify(r.body)}`).toBe(201);
+ expect(r.body.items![0].place, why).toBeUndefined();
+ // Stopped, so the studio's own limit of runs at once leaves room for the next.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE json_extract(request_json, '$.account') = ? AND status IN ('queued', 'running')").run(a.id);
+ };
+ const holds = fake.holds.size;
+ // Closed to the account.
+ withBilling({ hosted: false, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ own(await post(IMAGE, a.cookie), "hosted runs closed");
+ // A model the policy doesn't offer there.
+ withBilling({ pool: { allow: ["oss-qwen-image-21-turbo"] }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ own(await post(IMAGE, a.cookie), "a model not offered");
+ // A kind the policy leaves out.
+ withBilling({ kinds: { image: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ own(await post(IMAGE, a.cookie), "a kind left out");
+ // Extra LoRAs.
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const lora = await post({ ...IMAGE, loras: [{ file: "a-look.safetensors", strength: 0.8 }] }, a.cookie);
+ expect(lora.body.code).not.toBe("own-gpu-offline");
+ expect(lora.status, JSON.stringify(lora.body)).not.toBe(403);
+ // The billing service not answering (and no earlier answer kept).
+ billing.resetBillingCache();
+ fake.down = "error";
+ try {
+ own(await post(IMAGE, a.cookie), "the service down");
+ } finally {
+ fake.down = false;
+ }
+ expect(poolRuns(a.id)).toBe(0);
+ expect(fake.holds.size).toBe(holds);
+ expect(ownRuns(a.id)).toBeGreaterThanOrEqual(3);
+ });
+
+ it("asked for this install's GPUs by name while they are closed to the account: said so, never run on its own GPU", async () => {
+ withBilling({ hosted: false, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ const r = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("not-offered");
+ expect(ownRuns(a.id) + poolRuns(a.id)).toBe(0);
+ });
+
+ it("an own GPU that answers: its run never waits for the billing service once its policy is known", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ fake.policy = { ...fake.policy, ttlS: 60 };
+ const a = account({ gpu: "online" });
+ await billing.policy(a.id);
+ const asked = () => fake.calls_of("/v1/policy").length;
+ const before = asked();
+ const r = await post(IMAGE, a.cookie);
+ expect(r.status).toBe(201);
+ expect(r.body.items![0].place).toBeUndefined();
+ expect(asked()).toBe(before);
+ // A service that doesn't answer is waited for once, then not again for a while.
+ billing.resetBillingCache();
+ fake.down = "hang";
+ try {
+ const t0 = Date.now();
+ expect((await post(IMAGE, a.cookie)).status).toBe(201);
+ expect(Date.now() - t0).toBeLessThan(billing.BILLING_TIMEOUTS.policy + 1500);
+ const after = asked();
+ const t1 = Date.now();
+ expect((await post(IMAGE, a.cookie)).status).toBe(201);
+ expect(Date.now() - t1).toBeLessThan(billing.BILLING_TIMEOUTS.policy);
+ expect(asked()).toBe(after);
+ } finally {
+ fake.down = false;
+ }
+ });
+
+ it("a kind the policy leaves out is not offered here", async () => {
+ withBilling({ kinds: { image: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("not-offered");
+ expect(hostedRun.kindAllowed({ kinds: { image: false } }, "video")).toBe(true);
+ expect(hostedRun.kindAllowed({}, "model3d")).toBe(true);
+ });
+
+ it("a guest's policy that gets no answer isn't asked for again on every page for a while", async () => {
+ withBilling();
+ fake.down = "error";
+ try {
+ const before = fake.calls_of("/v1/policy").length;
+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();
+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();
+ expect(fake.calls_of("/v1/policy").length).toBe(before + 1);
+ expect(billing.cachedPolicy(null)).toBeNull();
+ } finally {
+ fake.down = false;
+ }
+ billing.resetBillingCache();
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ });
+
+ it("a guest is told what the billing service's policy for guests says", async () => {
+ withBilling();
+ fake.guestPolicy = { ...FAKE_POLICY, hosted: false, ttlS: 0 };
+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();
+ expect(fake.calls_of("/v1/policy").at(-1)!.path).toBe("/v1/policy");
+ fake.guestPolicy = { ...FAKE_POLICY, hosted: true, ttlS: 0 };
+ billing.resetBillingCache();
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ // No billing service: as any account.
+ delete process.env.FUOBE_BILLING_URL;
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ });
+});
+
+describe("a run's price facts", () => {
+ it("send the real size of a picture, and every step of a chain once", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const r = await post({ ...IMAGE, params: { aspectRatio: "16:9", resolution: "1K" }, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const run = (fake.calls_of("/v1/reserve").at(-1)!.body as { run: { megapixels: number | null; steps?: { model: string; jobs: number }[] } }).run;
+ expect(run.megapixels).toBeGreaterThan(0.9);
+ expect(run.megapixels).toBeLessThan(1.2);
+ expect(run.steps).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 1 })]);
+ // A film of two shots: its two clips priced together with one hold; the join costs nothing.
+ const film = await post({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN }, a.cookie);
+ expect(film.status, JSON.stringify(film.body)).toBe(201);
+ const reserves = fake.calls_of("/v1/reserve");
+ const filmRun = (reserves.at(-1)!.body as { run: { steps?: { model: string; jobs: number }[] } }).run;
+ expect(filmRun.steps?.find((s) => s.model === "oss-wan22-14b-fast")?.jobs).toBe(2);
+ expect(filmRun.steps?.every((s) => s.model === "oss-wan22-14b-fast"), JSON.stringify(filmRun.steps)).toBe(true);
+ expect(poolRuns(a.id)).toBe(2);
+ });
+
+ it("under the policy's cap on outputs, the price check and the run plan, price and make the same run", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, outputsPerRun: 1 } });
+ const a = account();
+ const asked = { ...IMAGE, params: { numOutputs: 4 } };
+ const q = await preview(asked, a.cookie);
+ expect(q.body.place).toBe("pool");
+ const quoted = (fake.calls_of("/v1/quote").at(-1)!.body as { run: { jobs: number; steps?: { jobs: number }[] } }).run;
+ const r = await post({ ...asked, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const reserved = (fake.calls_of("/v1/reserve").at(-1)!.body as { run: { jobs: number; steps?: { jobs: number }[] } }).run;
+ expect(quoted.jobs).toBe(1);
+ expect(reserved.jobs).toBe(1);
+ expect(reserved.steps).toEqual(quoted.steps);
+ expect(reserved.steps?.[0].jobs).toBe(1);
+ expect(r.body.items).toHaveLength(1);
+ expect((r.body as { notes?: string[] }).notes).toContain(ACCOUNT_MESSAGES.outputsCapped);
+ });
+
+ it("the account's runs in the line facts count one per press of Run, however many jobs", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const r = await post({ ...IMAGE, params: { numOutputs: 3 }, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items!.length).toBeGreaterThan(1);
+ await until(() => r.body.items!.every((g) => taskOf(g.id)));
+ expect(hosted.queueFacts(a.id, "z-image-turbo-t2i").mine).toEqual({ waiting: 1, running: 0 });
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ const sent = (fake.calls_of("/v1/reserve").at(-1)!.body as { queue: { mine: { waiting: number } } }).queue;
+ expect(sent.mine.waiting).toBe(1);
+ });
+
+ it("a run whose hold set nothing aside never says it wasn't charged", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const stopped = async () => {
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const id = r.body.items![0].id;
+ db().prepare("UPDATE generations SET status = 'canceled', completed_at = ? WHERE id = ?").run(Date.now(), id);
+ return getGeneration(id)!;
+ };
+ expect((await stopped()).notCharged).toBe(true);
+ fake.price = { amount: 0, version: "v0" };
+ const free = await stopped();
+ expect(free.place).toBe("pool");
+ expect(free.notCharged).toBeUndefined();
+ });
+
+ it("a chain whose join no worker takes is refused before anything is made", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const film = { feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN };
+ // Every lane but the joins'.
+ const joins = new Set(hosted.workflowPicks("video-concat-{n}").map((id) => pool.poolLane(id)));
+ expect(joins.size).toBeGreaterThan(0);
+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
+ expect(lanes.some((l) => !joins.has(l))).toBe(true);
+ pool.patchWorker(worker.id, { allow: Object.fromEntries(lanes.filter((l) => !joins.has(l)).map((l) => [l, { delayMs: 0 }])) });
+ const holds = fake.holds.size;
+ const r = await post(film, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(403);
+ expect(r.body.code).toBe("not-offered");
+ expect(poolRuns(a.id)).toBe(0);
+ expect(fake.holds.size).toBe(holds);
+ // Its price check says the same: not here.
+ expect((await preview(film, a.cookie)).body.place).toBeUndefined();
+ });
+
+ it("every step must be one the policy allows: a later step's model it leaves out stops the run before anything is made", () => {
+ const steps = (models: [string, string][]) => models.map(([modelId, provider], i) => ({ id: `s${i}`, modelId, op: "t2i", provider, kind: "image", presetId: null, waits: i > 0 }));
+ const p = { ...billing.OPEN_POLICY, pool: { deny: ["oss-qwen-image-edit"] } };
+ expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"]]))).toBeNull();
+ expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"], ["oss-qwen-image-edit", "comfyui"]]))).not.toBeNull();
+ // A cloud step can't run here; a text step costs nothing and is always allowed.
+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps([["oss-z-image-turbo", "comfyui"], ["fal-flux", "fal"]]))).not.toBeNull();
+ expect(hostedRun.stepsProblem({ ...billing.OPEN_POLICY, pool: { allow: ["oss-z-image-turbo"] } }, steps([["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toBeNull();
+ expect(hostedRun.pricedSteps(steps([["oss-z-image-turbo", "comfyui"], ["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 2 })]);
+ });
+});
diff --cc tests/pool-line-order.test.ts
index f9a76951,00000000..983bfcbf
mode 100644,000000..100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@@ -1,402 -1,0 +1,402 @@@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The order of the line on this install's GPUs and its install-wide settings: people's paid runs, then their free runs,
+ * then the owner's own jobs, each class in the order its jobs came; fair share and the pick allowance; the run ceiling
+ * per lane on both clocks; the owner's own wait limit; and GET and PATCH /api/admin/queue/settings.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-line-order-");
+process.env.FUOBE_DATA_DIR = dir;
+const DEAD = "http://127.0.0.1:7";
+process.env.COMFYUI_URL = DEAD;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const admin = await import("@/server/admin-tokens");
+const generationsRoute = await import("@/app/api/generations/route");
+const settingsRoute = await import("@/app/api/admin/queue/settings/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const { getGeneration } = await import("@/server/generations");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const qs = await import("@/server/queue-settings");
+const { loadManifest, comfyProvider, onComputer } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const MIN = 60_000;
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+let fake: FakeBilling;
+let accountId = "";
+let cookie = "";
+let other = "";
+
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ allowed = [fake.url];
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;
+ other = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ fake.reserveExtra = {};
+ fake.policy = { ...fake.policy, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7_000_000 } };
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ // (Finished ones too: fair share counts the runs a worker finished while others waited.)
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state != 'canceled'").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+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 });
+ 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);
+ return w;
+}
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+const beatAs = (w: { id: string }, now = Date.now()) =>
- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
++ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
+const claimAs = (w: { id: string }, now = Date.now()) => pool.workerClaim(workerRow(w), [], now);
+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
+const done = (id: string) => db().prepare("UPDATE relay_tasks SET state = 'done', finished_at = ? WHERE id = ?").run(Date.now(), id);
+
+let gens = 0;
+/** A task in the line: a person's (with `account`) or the owner's, in a class, made `agoMs` ago. */
+function lineTask(o: { account?: string; class?: "paid" | "free" | "owner"; agoMs?: number; lane?: string } = {}) {
+ const gid = `line-gen-${++gens}`;
+ const at = Date.now() - (o.agoMs ?? 0);
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(gid, JSON.stringify(o.account ? { account: o.account, place: "pool" } : {}), at, at);
+ const lane = o.lane ?? allLanes(loadIndex(), sha)[0].lane;
+ const t = tasks.createTask({
+ principal: o.account ? `acct:${o.account}` : "owner",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], account: o.account, class: o.class, rankAt: at, lane, needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 } },
+ });
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(at, t.id);
+ return t.id;
+}
+
+/** Every waiting task, claimed one by one by a worker that finishes each at once: the order the line serves them. */
+function served(w: { id: string }): string[] {
+ const out: string[] = [];
+ for (;;) {
+ beatAs(w);
+ const t = claimAs(w);
+ if (!t) return out;
+ out.push(t.id);
+ done(t.id);
+ }
+}
+
+describe("classes", () => {
+ it("the owner's own job waits behind every person's run, even ones sent long after it", () => {
+ const w = standInWorker();
+ const owner = lineTask({ agoMs: 60 * MIN });
+ const a = lineTask({ account: accountId, agoMs: 10 * MIN });
+ const b = lineTask({ account: other, agoMs: 5 * MIN });
+ const c = lineTask({ account: accountId, agoMs: 0 });
+ expect(rowOf(owner).class).toBe("owner");
+ expect(rowOf(a).class).toBe("free");
+ // Its place counts every person's run ahead of it.
+ expect(pool.placeInLine(rowOf(owner)).place).toBe(4);
+ expect(served(w)).toEqual([a, b, c, owner]);
+ });
+
+ it("paid runs go before free ones, and each class goes in the order its runs came", () => {
+ const w = standInWorker();
+ const free1 = lineTask({ account: accountId, agoMs: 30 * MIN });
+ const paid1 = lineTask({ account: other, class: "paid", agoMs: 20 * MIN });
+ const free2 = lineTask({ account: other, agoMs: 10 * MIN });
+ const paid2 = lineTask({ account: accountId, class: "paid", agoMs: 0 });
+ expect(pool.placeInLine(rowOf(free1)).place).toBe(3);
+ expect(served(w)).toEqual([paid1, paid2, free1, free2]);
+ });
+
+ it("a task from before classes reads as the owner's with no account and as a person's free run with one", () => {
+ const w = standInWorker();
+ const old = lineTask({ agoMs: 20 * MIN });
+ const person = lineTask({ account: accountId, agoMs: 10 * MIN });
+ db().prepare("UPDATE relay_tasks SET class = NULL WHERE id IN (?, ?)").run(old, person);
+ expect(served(w)).toEqual([person, old]);
+ });
+
+ it("only people's runs count as runs this worker may take now", () => {
+ const w = standInWorker();
+ lineTask({ agoMs: 1 * MIN });
+ lineTask({ account: accountId });
+ expect(beatAs(w).claimableNow).toBe(1);
+ });
+
+ it("the owner's ComfyUI job on the workers is the owner's class, with no wait limit unless the owner sets one", async () => {
+ standInWorker();
+ const route = { provider: "comfyui", endpoint: loadManifest().workflows[0].id, op: "t2i" } as never;
+ const submit = (gid: string) => onComputer("owner", () => comfyProvider.submit({ route, input: { prompt: "a lighthouse" } as never, generationId: gid } as never));
+ const first = rowOf(String(((await submit("owner-gen-1")).meta as { relay: string }).relay));
+ expect(first.class).toBe("owner");
+ expect(first.account).toBeNull();
+ expect(first.not_after).toBeNull();
+ qs.saveQueueSettings({ ...qs.queueSettings(), ownerWaitLimitS: 3600 });
+ const second = rowOf(String(((await submit("owner-gen-2")).meta as { relay: string }).relay));
+ expect(second.not_after! - second.created_at).toBeGreaterThanOrEqual(3600_000 - 1000);
+ expect(second.not_after! - second.created_at).toBeLessThanOrEqual(3600_000 + 1000);
+ });
+});
+
+describe("the billing service's class and head start", () => {
+ it("an account's run takes the class and head start the reserve answer gives", async () => {
+ standInWorker();
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...fake.policy, hosted: true, ttlS: 0 };
+ fake.reserveExtra = { class: "paid", boostMs: 60_000 };
+ const before = Date.now();
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, {
+ method: "POST",
+ headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" },
+ body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse", shown: { amount: 7, priceVersion: "v7" } }),
+ }),
+ );
+ const body = (await r.json()) as { items?: { id: string }[] };
+ expect(r.status, JSON.stringify(body)).toBe(201);
+ const id = body.items![0].id;
+ let t = taskOf(id);
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf(id);
+ }
+ expect(t?.class).toBe("paid");
+ expect(t!.rank_at!).toBeLessThanOrEqual(t!.created_at - 60_000);
+ expect(t!.rank_at!).toBeGreaterThanOrEqual(before - 60_000 - 1000);
+ // The stored run carries its class for its later steps, and the browser never sees it.
+ const stored = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json) as Record<string, unknown>;
+ expect(stored.class).toBe("paid");
+ expect(stored.boostMs).toBe(60_000);
+ const seen = getGeneration(id) as unknown as { request?: Record<string, unknown> };
+ expect(seen.request?.class).toBeUndefined();
+ expect(seen.request?.boostMs).toBeUndefined();
+ });
+
+ it("a head start never passes a day, and a class it doesn't know is free", () => {
+ const f = pool.poolFields(loadManifest().workflows[0].id, { account: accountId, boostMs: 7 * 24 * 60 * MIN }, 1_000_000_000_000);
+ expect(f.rankAt).toBe(1_000_000_000_000 - 24 * 60 * MIN);
+ expect(f.class).toBe("free");
+ expect(pool.poolFields(loadManifest().workflows[0].id, {}, 0).class).toBe("owner");
+ });
+});
+
+describe("fair share", () => {
+ it("off: strict order; on: each account's first run goes before anyone's second, counting runs it has going", () => {
+ const w = standInWorker();
+ const a1 = lineTask({ account: accountId, agoMs: 30 * MIN });
+ const a2 = lineTask({ account: accountId, agoMs: 29 * MIN });
+ const a3 = lineTask({ account: accountId, agoMs: 28 * MIN });
+ const b1 = lineTask({ account: other, agoMs: 10 * MIN });
+ const owner = lineTask({ agoMs: 60 * MIN });
+ const strict = pool.lineOrder(db().prepare("SELECT * FROM relay_tasks WHERE state = 'waiting' AND pools IS NOT NULL").all() as never, false).map((t) => t.id);
+ expect(strict).toEqual([a1, a2, a3, b1, owner]);
+ qs.saveQueueSettings({ ...qs.queueSettings(), fairShare: true });
+ expect(pool.placeInLine(rowOf(b1)).place).toBe(2);
+ expect(served(w)).toEqual([a1, b1, a2, a3, owner]);
+ });
+});
+
+describe("the pick allowance", () => {
+ it("0 (the default): strict order whatever the worker has loaded; set, a loaded lane goes first while the best one is young", () => {
+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
+ const w = standInWorker();
+ db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(lanes[1], 60 * MIN, w.id);
+ const old = lineTask({ account: accountId, agoMs: 5 * MIN, lane: lanes[0] });
+ const warm = lineTask({ account: other, agoMs: 1 * MIN, lane: lanes[1] });
+ beatAs(w);
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(claimAs(w)?.id).toBe(old);
+ done(old);
+ const old2 = lineTask({ account: accountId, agoMs: 5 * MIN, lane: lanes[0] });
+ qs.saveQueueSettings({ ...qs.queueSettings(), pickAllowanceMs: 10 * MIN });
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(warm);
+ done(warm);
+ // Never across classes: the owner's job in the loaded lane waits behind a person's run in another.
+ lineTask({ agoMs: 1 * MIN, lane: lanes[1] });
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(old2);
+ });
+});
+
+describe("the run ceiling", () => {
+ it("a worker's run limit never passes its lane's ceiling, and with no measured run it is the ceiling", () => {
+ const [a, b] = allLanes(loadIndex(), sha).map((l) => l.lane);
+ expect(pool.runLimitMs(null, a)).toBe(45 * MIN);
+ expect(pool.runLimitMs(60_000, a)).toBe(10 * MIN);
+ expect(pool.runLimitMs(20 * MIN, a, 2 * MIN)).toBe(45 * MIN);
+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 1800, lanes: { [b]: 3600 } } });
+ expect(pool.runLimitMs(null, a)).toBe(30 * MIN);
+ expect(pool.runLimitMs(null, b)).toBe(60 * MIN);
+ expect(pool.runLimitMs(15 * MIN, b, 5 * MIN)).toBe(50 * MIN);
+ });
+
+ it("a run longer than 45 minutes in a lane with a 60 minute ceiling goes on, and past 60 it stops", async () => {
+ const w = standInWorker();
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a long one" }) }),
+ );
+ const body = (await r.json()) as { items?: { id: string }[] };
+ expect(r.status, JSON.stringify(body)).toBe(201);
+ const id = body.items![0].id;
+ let t = taskOf(id);
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf(id);
+ }
+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [t!.lane!]: 3600 } } });
+ beatAs(w);
+ const got = claimAs(w)!;
+ expect(got.id).toBe(t!.id);
+ expect(got.runLimitMs).toBe(60 * MIN);
+ tasks.setTask(t!.id, { state: "running", started_at: Date.now() });
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("running");
+ const startedAgo = (ms: number) => db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);
+ startedAgo(50 * MIN);
+ beatAs(w);
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("running");
+ startedAgo(61 * MIN);
+ beatAs(w);
+ await globalThis.__fuobeRunner?.tick();
+ expect(getGeneration(id)?.status).toBe("failed");
+ });
+});
+
+describe("GET and PATCH /api/admin/queue/settings", () => {
+ const req = (o: { method?: string; token?: string; cookie?: string; body?: unknown } = {}) =>
+ new NextRequest(`http://${HOST}/api/admin/queue/settings`, {
+ method: o.method ?? "GET",
+ headers: { host: HOST, ...(o.token && { authorization: `Bearer ${o.token}` }), ...(o.cookie && { cookie: o.cookie }), ...(o.body !== undefined && { "content-type": "application/json" }) },
+ ...(o.body !== undefined && { body: JSON.stringify(o.body) }),
+ });
+ const ownerCookie = () => `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ const audits = () => db().prepare("SELECT * FROM admin_audit WHERE action = 'queue.settings' ORDER BY id").all() as { actor: string; detail_json: string | null; status: number; token_id: string | null }[];
+
+ it("the defaults are today's: a 45 minute ceiling, no owner wait limit, strict order", async () => {
+ const res = await settingsRoute.GET(req({ cookie: ownerCookie() }));
+ expect(res.status).toBe(200);
+ expect(res.headers.get("cache-control")).toBe("no-store");
+ expect(await res.json()).toEqual({ settings: { runCeilingS: { default: 2700, lanes: {} }, ownerWaitLimitS: null, fairShare: false, pickAllowanceMs: 0 } });
+ });
+
+ it("the owner changes them; each change is logged with the values before and after", async () => {
+ const lane = allLanes(loadIndex(), sha)[0].lane;
+ const res = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body: { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true } }));
+ expect(res.status).toBe(200);
+ const want = { runCeilingS: { default: 3000, lanes: { [lane]: 3600 } }, ownerWaitLimitS: 86_400, fairShare: true, pickAllowanceMs: 0 };
+ expect(await res.json()).toEqual({ settings: want });
+ expect(qs.queueSettings()).toEqual(want);
+ const row = audits().at(-1)!;
+ expect(row.actor).toBe("owner");
+ expect(row.status).toBe(200);
+ expect(JSON.parse(row.detail_json!)).toEqual({ before: qs.QUEUE_DEFAULTS, after: want });
+ // A field left out keeps its value; null takes the owner's wait limit away.
+ const back = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body: { ownerWaitLimitS: null } }));
+ expect(((await back.json()) as { settings: unknown }).settings).toEqual({ ...want, ownerWaitLimitS: null });
+ });
+
+ it("refuses values out of bounds, unknown settings and unknown lanes, and changes nothing", async () => {
+ const before = qs.queueSettings();
+ for (const body of [
+ { runCeilingS: { default: 10 } },
+ { runCeilingS: { default: 3000, lanes: { "not-a-lane": 3000 } } },
+ { runCeilingS: { default: 3000, lanes: { small: 999_999 } } },
+ { ownerWaitLimitS: -1 },
+ { fairShare: "yes" },
+ { pickAllowanceMs: 1.5 },
+ { somethingElse: 1 },
+ [1, 2],
+ null,
+ ]) {
+ const res = await settingsRoute.PATCH(req({ method: "PATCH", cookie: ownerCookie(), body }));
+ expect(res.status, JSON.stringify(body)).toBe(400);
+ expect(typeof ((await res.json()) as { error: string }).error).toBe("string");
+ }
+ expect(qs.queueSettings()).toEqual(before);
+ expect(audits().at(-1)!.status).toBe(400);
+ });
+
+ it("a stored value that isn't valid reads as the defaults", () => {
+ db().prepare("INSERT INTO settings (key, value) VALUES ('queue.settings', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run("{not json");
+ globalThis.__fuobeQueueSettings = undefined;
+ expect(qs.queueSettings()).toEqual(qs.QUEUE_DEFAULTS);
+ });
+
+ it("an admin token reads them with queue:read and changes them with queue:write", async () => {
+ const make = (scopes: import("@/server/admin-tokens").Scope[]) => admin.createAdminToken({ name: `t-${Math.random()}`, scopes });
+ const reader = make(["queue:read"]);
+ const writer = make(["queue:write"]);
+ expect((await settingsRoute.GET(req({ token: reader.token }))).status).toBe(200);
+ expect((await settingsRoute.GET(req({ token: writer.token }))).status).toBe(403);
+ expect((await settingsRoute.PATCH(req({ method: "PATCH", token: reader.token, body: { fairShare: true } }))).status).toBe(403);
+ const ok = await settingsRoute.PATCH(req({ method: "PATCH", token: writer.token, body: { pickAllowanceMs: 60_000 } }));
+ expect(ok.status).toBe(200);
+ expect(audits().at(-1)!.token_id).toBe(writer.info.id);
+ // Nobody else.
+ expect((await settingsRoute.GET(req())).status).toBe(403);
+ expect((await settingsRoute.PATCH(req({ method: "PATCH", cookie, body: { fairShare: true } }))).status).toBe(403);
+ });
+});
diff --cc tests/worker-queue.test.ts
index a9fca99b,00000000..b4d12d6b
mode 100644,000000..100644
--- a/tests/worker-queue.test.ts
+++ b/tests/worker-queue.test.ts
@@@ -1,256 -1,0 +1,256 @@@
+import crypto from "node:crypto";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The workers' line keeps its own rules, whoever a job belongs to: a worker holds one job at a time; a job still sending
+ * its files long after the claim goes back in line; a job back in line keeps its place, and its wait limit is over once
+ * a worker took it; the beat says how many people's jobs a worker may take now. The workers' log keeps which worker ran
+ * which job, and a run's report to the billing service carries the time the workers measured.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-worker-queue-");
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing answers here: no test may reach a real ComfyUI on this machine.
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const { queueReports } = await import("@/server/billing-outbox");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+
+const HOST = "localhost:3000";
+const MIN = 60_000;
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+let accountId = "";
+let cookie = "";
+
+beforeAll(() => {
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;
+});
+beforeEach(() => {
+ setSetting("comfyWhere", "workers");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+/** A worker the owner added and resumed, allowed every lane, able to run every workflow. */
+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 });
+ 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);
+ return w;
+}
+
+/** An account's job made straight in the line (no run route). */
+let gens = 0;
+function accountTask(o: { rankAt?: number; notAfter?: number } = {}) {
+ const gid = `queue-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(gid, JSON.stringify({ account: accountId, place: "pool" }), now, now);
+ const t = tasks.createTask({
+ principal: `acct:${accountId}`,
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], account: accountId, rankAt: o.rankAt ?? now, lane: allLanes(loadIndex(), sha)[0]?.lane ?? "small", needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 }, notAfter: o.notAfter },
+ });
+ return { id: t.id, generationId: gid };
+}
+
+type WorkerRow = import("@/server/computer/workers").WorkerRow;
+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+const beatAs = (w: { id: string }, now = Date.now(), local: { paused: boolean; why: string | null } = { paused: false, why: null }, running: { task: string }[] = []) =>
- pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { ...local, until: null }, gpu: {}, inventoryHash: null, running, stopped: [] }), now);
++ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { ...local, until: null }, gpu: {}, inventoryHash: null, running, stopped: [] }), now);
+const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);
+
+describe("one job at a time", () => {
+ it("a stolen worker token holds at most one task; one stuck sending its files goes back in line", () => {
+ const w = standInWorker();
+ const a = accountTask({ rankAt: Date.now() - 2 * MIN });
+ const b = accountTask({ rankAt: Date.now() - MIN });
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(a.id);
+ // Asking again while it holds one: nothing new, whether or not it says it is running it.
+ expect(claimAs(w, [a.id])).toBeNull();
+ expect(claimAs(w, [])?.id).toBe(a.id);
+ expect(rowOf(b.id).state).toBe("waiting");
+ // Still sending its files 15 minutes after the claim: back in line (a lost attempt), and b goes next.
+ const later = Date.now() + pool.SENDING_MS + MIN;
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(later, w.id);
+ pool.sweepPool(later);
+ expect(rowOf(a.id).state).toBe("waiting");
+ expect(rowOf(a.id).requeues).toBe(1);
+ });
+
+ it("a worker that asks again for its own task never winds the sending clock back", () => {
+ const w = standInWorker();
+ const a = accountTask();
+ const t0 = Date.now();
+ beatAs(w, t0);
+ expect(claimAs(w, [], t0)?.id).toBe(a.id);
+ const first = rowOf(a.id).claimed_at;
+ // Lost track of it a minute on: the same task, with its first claim's time.
+ beatAs(w, t0 + MIN);
+ expect(claimAs(w, [], t0 + MIN)?.id).toBe(a.id);
+ expect(rowOf(a.id).claimed_at).toBe(first);
+ // Still sending its files 15 minutes after that first claim, from a worker that beats on: back in line.
+ const late = t0 + pool.SENDING_MS + MIN;
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(late, w.id);
+ pool.sweepPool(late);
+ expect(rowOf(a.id).state).toBe("waiting");
+ expect(rowOf(a.id).requeues).toBe(1);
+ });
+
+ it("a job its ComfyUI lost while it ran sends again with a fresh sending clock", () => {
+ const w = standInWorker();
+ const a = accountTask();
+ const t0 = Date.now();
+ beatAs(w, t0);
+ expect(claimAs(w, [], t0)?.id).toBe(a.id);
+ tasks.setTask(a.id, { state: "running", sent_at: t0 + MIN, attempts: 1 });
+ // Twenty minutes in, its ComfyUI restarted and lost the job: the worker sends it again.
+ const gone = t0 + 20 * MIN;
+ tasks.report(rowOf(a.id), { event: "gone" }, () => ({ error: "unused" }), gone);
+ expect(rowOf(a.id).state).toBe("sending");
+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(gone + MIN, w.id);
+ pool.sweepPool(gone + MIN);
+ expect(rowOf(a.id).state).toBe("sending");
+ expect(rowOf(a.id).requeues).toBe(0);
+ });
+});
+
+describe("back in line", () => {
+ it("a requeue keeps the job's place (rank_at), and once a worker took it, its wait limit is over", () => {
+ const w = standInWorker();
+ const first = accountTask({ rankAt: Date.now() - 5 * MIN, notAfter: Date.now() + MIN });
+ const later = accountTask({ rankAt: Date.now() });
+ const rank = rowOf(first.id).rank_at;
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(first.id);
+ // The worker pauses at once (another program on the GPU): the job goes back in line at no cost.
+ beatAs(w, Date.now(), { paused: true, why: "gpu-busy:game.exe" }, [{ task: first.id }]);
+ const back = rowOf(first.id);
+ expect(back.state).toBe("waiting");
+ expect(back.rank_at).toBe(rank);
+ expect(back.requeues).toBe(0);
+ // First in line again, ahead of the later job, and past its wait limit it still waits.
+ expect(pool.queueOfGeneration(first.generationId)?.place).toBe(1);
+ expect(pool.queueOfGeneration(later.generationId)?.place).toBe(2);
+ pool.sweepPool(Date.now() + 10 * MIN);
+ expect(rowOf(first.id).state).toBe("waiting");
+ // A job no worker has taken yet still fails at its wait limit, not charged.
+ const never = accountTask({ notAfter: Date.now() + MIN });
+ pool.sweepPool(Date.now() + 2 * MIN);
+ expect(rowOf(never.id).state).toBe("failed");
+ });
+});
+
+describe("the beat", () => {
+ it("says how many people's tasks this worker may claim now (never the owner's own)", () => {
+ const w = standInWorker();
+ accountTask();
+ accountTask();
+ const owner = accountTask();
+ db().prepare("UPDATE relay_tasks SET principal = 'owner', account = NULL WHERE id = ?").run(owner.id);
+ expect(beatAs(w).claimableNow).toBe(2);
+ pool.patchWorker(w.id, { paused: true });
+ expect(beatAs(w).claimableNow).toBe(0);
+ });
+});
+
+describe("the workers' measured run reaches the billing service", () => {
+ it("settle carries the time the worker's ComfyUI spent on the run and its GPU's name", () => {
+ const now = Date.now();
+ const t = accountTask();
+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${t.id}` }), t.generationId);
+ tasks.logWorkerJob("finished", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-1", now, { execMs: 12_345, device: "Test GPU 24GB" });
+ queueReports(now);
+ const row = db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").get(t.generationId) as { payload_json: string };
+ const report = JSON.parse(row.payload_json) as { gpuMs: number; device: string };
+ expect(report.gpuMs).toBe(12_345);
+ expect(report.device).toBe("Test GPU 24GB");
+ });
+
+ it("a job that went back in line after its result was made counts once: the attempt whose result was kept", () => {
+ const now = Date.now();
+ const t = accountTask();
+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${t.id}` }), t.generationId);
+ const row = { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}` as const, lane: "small" };
+ tasks.logWorkerJob("finished", row, "w-1", now - 5 * MIN, { execMs: 50_000, device: "Test GPU A" });
+ tasks.logWorkerJob("requeued", row, "w-1", now - 4 * MIN);
+ tasks.logWorkerJob("finished", row, "w-2", now - MIN, { execMs: 40_000, device: "Test GPU B" });
+ // A second job of the same run adds its own time.
+ tasks.logWorkerJob("finished", { ...row, id: "second-job-0001x" }, "w-2", now, { execMs: 2_000, device: "Test GPU B" });
+ queueReports(now);
+ const report = JSON.parse((db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").get(t.generationId) as { payload_json: string }).payload_json) as { gpuMs: number; device: string };
+ expect(report.gpuMs).toBe(42_000);
+ expect(report.device).toBe("Test GPU B");
+ });
+});
+
+describe("the workers' log", () => {
+ it("only grows", () => {
+ const t = accountTask();
+ tasks.logWorkerJob("claimed", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: null }, "w-2");
+ expect(() => db().prepare("UPDATE worker_jobs SET event = 'done' WHERE task_id = ?").run(t.id)).toThrow(/only grows/);
+ expect(() => db().prepare("DELETE FROM worker_jobs WHERE task_id = ?").run(t.id)).toThrow(/kept a year/);
+ });
+
+ it("keeps a claim, a requeue and how the job ended, by worker", () => {
+ const w = standInWorker("logged");
+ const a = accountTask();
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(a.id);
+ beatAs(w, Date.now(), { paused: true, why: "here-now" }, [{ task: a.id }]);
+ pool.patchWorker(w.id, { paused: false });
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(a.id);
+ tasks.endTask(a.id, "canceled", { error: "Stopped" });
+ const log = db().prepare("SELECT event, worker_id, worker_name, principal FROM worker_jobs WHERE task_id = ? ORDER BY id").all(a.id) as { event: string; worker_id: string; worker_name: string; principal: string }[];
+ expect(log.map((x) => x.event)).toEqual(["claimed", "requeued", "claimed", "canceled"]);
+ expect(log.every((x) => x.worker_id === w.id && x.worker_name === "logged" && x.principal === `acct:${accountId}`)).toBe(true);
+ });
+
+ it("lists who took which job, newest first, for the owner or a token that may read the workers", async () => {
+ const jobsRoute = await import("@/app/api/admin/workers/jobs/route");
+ const { createAdminToken } = await import("@/server/admin-tokens");
+ const t = accountTask();
+ tasks.logWorkerJob("claimed", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-log-1");
+ tasks.logWorkerJob("finished", { id: t.id, generation_id: t.generationId, principal: `acct:${accountId}`, lane: "small" }, "w-log-1", Date.now(), { execMs: 4321, device: "Test GPU" });
+ const get = (qs: string, headers: Record<string, string>) => jobsRoute.GET(new Request(`http://${HOST}/api/admin/workers/jobs${qs}`, { headers: { host: HOST, ...headers } }));
+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ const res = await get(`?generation=${t.generationId}`, { cookie: owner });
+ expect(res.status).toBe(200);
+ const page = (await res.json()) as { items: { event: string; workerId: string; execMs: number | null; device: string | null }[]; next: string | null };
+ expect(page.items.map((x) => x.event)).toEqual(["finished", "claimed"]);
+ expect(page.items[0]).toMatchObject({ workerId: "w-log-1", execMs: 4321, device: "Test GPU" });
+ expect(JSON.stringify(page)).not.toContain("example.com");
+ // An account's session, or a token that may not read the workers: no.
+ expect((await get("", { cookie })).status).toBeGreaterThanOrEqual(401);
+ const reader = createAdminToken({ name: "workers reader", scopes: ["workers:read"] });
+ expect((await get("?limit=1", { authorization: `Bearer ${reader.token}` })).status).toBe(200);
+ const other = createAdminToken({ name: "queue reader", scopes: ["queue:read"] });
+ expect((await get("", { authorization: `Bearer ${other.token}` })).status).toBe(403);
+ expect((await get("?limit=0", { cookie: owner })).status).toBe(400);
+ });
+});
diff --cc tests/worker-runner.test.ts
index 00000000,6d05834e..6b687a5f
mode 000000,100644..100644
--- a/tests/worker-runner.test.ts
+++ b/tests/worker-runner.test.ts
@@@ -1,0 -1,490 +1,491 @@@
+ /**
+ * The shared runner (src/lib/computer-runner.ts) with a worker's hooks, against the studio's real routes and a stand-in
+ * ComfyUI on this computer: results kept on disk until the studio has them (a stop before the upload never runs a job
+ * twice), a job that stalls or runs past its run limit given back to the line, one retry after running out of memory,
+ * a job its ComfyUI stopped on twice failed in plain words, inputs read from the studio once, and a job the worker can't
+ * take given back. A browser tab's runner (no hooks) reports exactly as before.
+ */
+ import fs from "node:fs";
+ import path from "node:path";
+ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+ import type { HeldResults, WorkerHooks } from "@/lib/computer-runner";
+ import type { ClaimedTask, TaskInput } from "@/lib/relay";
+ import { Hold } from "../bin/lib/worker/hold.mjs";
+ import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";
+ import { apiAs, loadRoutes, sha256, SITE, type ComputerRoutes } from "./helpers/computer-tab";
+ import { tempDir } from "./helpers/temp-dir";
+
+ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+ vi.setConfig({ testTimeout: 60_000 });
+
+ const dir = tempDir("fuobe-worker-runner-");
+ process.env.FUOBE_DATA_DIR = dir;
+ process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+ delete process.env.FUOBE_PASSWORD;
+ globalThis.__fuobeTestDiskFree = 1e13;
+
+ const { db } = await import("@/server/db");
+ const { resetRates } = await import("@/server/rate");
+ const { setSetting } = await import("@/server/settings");
+ const tasks = await import("@/server/computer/tasks");
+ const pool = await import("@/server/computer/pool");
++const { runCeilingMs } = await import("@/server/queue-settings");
+ const workers = await import("@/server/computer/workers");
+ const { ComputerRunner } = await import("@/lib/computer-runner");
+ const { tabFailureWords } = await import("@/lib/relay");
+
+ let fake: LocalComfy;
+ let routes: ComputerRoutes;
+ const realFetch = globalThis.fetch;
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+ beforeAll(async () => {
+ fake = await startLocalComfy({ cors: "off", steps: 4, stepMs: 20, latencyMs: 10 });
+ routes = await loadRoutes();
+ setSetting("comfyWhere", "workers");
+ });
+ afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+ });
+ beforeEach(() => {
+ resetRates();
+ fake.restart({ failNext: undefined, loseNext: 0, steps: 4, stepMs: 20, outputs: ["image"] });
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ });
+
+ type W = { id: string; token: string };
+ const row = (w: W) => workers.getWorker(w.id)!;
+ const state = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+
+ function worker(): W {
+ const w = pool.addWorker(`w-${Math.random().toString(36).slice(2, 8)}`);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } });
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: ["small"], workflows: ["wf-test"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ beat(w);
+ return w;
+ }
+
+ function beat(w: W) {
+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));
+ }
+
+ let gens = 0;
+ /** A job for the workers: a picture it loads, a sampler, and a picture it saves. */
+ function task(): string {
+ const gid = `runner-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")
+ .run(gid, now, now);
+ const input = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");
+ const t = tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph: {
+ "1": { class_type: "LoadImage", inputs: { image: input } },
+ "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } },
+ "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } },
+ },
+ pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
+ });
+ return t.id;
+ }
+
+ /** The studio's routes as a worker calls them, every report written down, with a hook to answer a call itself. */
+ function studio(w: W) {
+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });
+ const reports: Record<string, unknown>[] = [];
+ const reads: string[] = [];
+ let intercept: ((p: string, init: RequestInit) => Promise<Response | undefined> | Response | undefined) | null = null;
+ const call = async (p: string, init: RequestInit = {}) => {
+ const mine = await intercept?.(p, init);
+ if (mine) return mine;
+ if (p.endsWith("/report")) reports.push(JSON.parse(String(init.body)));
+ if (p.includes("/inputs/")) reads.push(p);
+ return api(p, init);
+ };
+ return { call, reports, reads, set: (fn: typeof intercept) => (intercept = fn) };
+ }
+
+ const hooks = (o: Partial<WorkerHooks> = {}): WorkerHooks => ({
+ hold: new Hold(tempDir("fuobe-worker-hold-")) as unknown as WorkerHooks["hold"],
+ input: (_t: ClaimedTask, _i: TaskInput, read: () => Promise<ArrayBuffer | string>) => read() as never,
+ stallMs: 60_000,
+ free: async () => {},
+ crashes: () => 0,
+ stuck: async () => {},
+ claimed: () => {},
+ ...o,
+ });
+
+ function runner(s: ReturnType<typeof studio>, worker?: WorkerHooks, now?: () => number) {
+ return new ComputerRunner(
+ { api: s.call, local: (url, init) => realFetch(url, init), socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => sleep(Math.min(ms, 30)), ...(worker && { worker }), ...(now && { now }) },
+ { device: "worker", port: fake.port, clientId: "client-worker-01" },
+ );
+ }
+
+ /** A clock on which each real millisecond is `x` of the runner's (600: a real second is ten minutes). */
+ function fastClock(x: number) {
+ const start = Date.now();
+ return () => start + (Date.now() - start) * x;
+ }
+
+ /** Claim the next job as a worker's runner does, and run it (or `edit` it first). */
+ async function claimAndRun(r: InstanceType<typeof ComputerRunner>, s: ReturnType<typeof studio>, edit?: (t: ClaimedTask) => ClaimedTask) {
+ if (!edit) return r.claimAndRun();
+ const res = await s.call("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "worker", running: [] }) });
+ const { task: t } = (await res.json()) as { task: ClaimedTask };
+ await r.run(edit(t));
+ }
+
+ const saved = (id: string) => fs.readFileSync(tasks.outputFile(id, 0));
+
+ describe("a worker's runner", () => {
+ it("runs a job to the end and reports its ComfyUI's execution time and its GPU's name", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id).state).toBe("done");
+ expect(saved(id).equals(FAKE_PNG)).toBe(true);
+ const finished = s.reports.find((x) => x.event === "finished")!;
+ expect(finished.execMs).toBeTypeOf("number");
+ expect(finished.device).toMatch(/\S/);
+ expect(String(finished.device)).not.toMatch(/^cuda:|cudaMallocAsync/);
+ expect(tasks.execOf(state(id))).toEqual({ ms: finished.execMs, device: finished.device });
+ });
+
+ it("a browser tab's runner (no worker hooks) reports as it always did", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ await runner(s).claimAndRun();
+ expect(state(id).state).toBe("done");
+ const finished = s.reports.find((x) => x.event === "finished")!;
+ expect(Object.keys(finished).sort()).toEqual(["entry", "event"]);
+ });
+
+ it("out of memory: frees its ComfyUI's memory and sends the job once more, and the studio never hears of the first try", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ let freed = 0;
+ const before = fake.posts();
+ fake.opts.failNext = "oom";
+ await runner(s, hooks({ free: async () => void freed++ })).claimAndRun();
+ expect(state(id).state).toBe("done");
+ expect(fake.posts() - before).toBe(2);
+ expect(freed).toBe(1);
+ expect(s.reports.filter((x) => x.event === "finished")).toHaveLength(1);
+ expect(s.reports.some((x) => x.event === "failed")).toBe(false);
+ // A second time it ran out: the run fails, as ComfyUI said.
+ const id2 = task();
+ fake.opts.failNext = "oom";
+ const r2 = runner(s, hooks({ free: async () => void (fake.opts.failNext = "oom") }));
+ await r2.claimAndRun();
+ expect(state(id2).state).toBe("failed");
+ });
+
+ it("a job that stalls goes back to the line within the stall limit, with its prompt taken off ComfyUI", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.failNext = "never";
+ const t0 = Date.now();
+ // The PC's own stall limit (600 ms here) wins over the claim's.
+ await runner(s, hooks({ stallLocalMs: 600 })).claimAndRun();
+ const took = Date.now() - t0;
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1, worker_id: null });
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "stalled" });
+ expect(took).toBeLessThan(600 + 5_000);
+ const q = (await (await realFetch(`${fake.url}/queue`)).json()) as { queue_running: unknown[]; queue_pending: unknown[] };
+ expect([...q.queue_running, ...q.queue_pending]).toEqual([]);
+ // Back in line, it runs to the end the next time.
+ beat(w);
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id).state).toBe("done");
+ });
+
+ it("the stall limit comes with the claim (the studio's), over the worker's own default", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.failNext = "never";
+ let given: number | undefined;
+ // The worker's default is an hour; the claim's limit is the one obeyed (2 minutes here: a real 200 ms on this clock).
+ await claimAndRun(runner(s, hooks({ stallMs: 60 * 60_000 }), fastClock(600)), s, (t) => ((given = t.stallMs), { ...t, stallMs: 2 * 60_000 }));
+ expect(given).toBe(pool.STALL_MS);
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "stalled" });
+ });
+
+ it("a job past its run limit goes back to the line", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ // About 20 minutes of running on the runner's clock, with an 11-minute limit.
+ fake.opts.steps = 40;
+ fake.opts.stepMs = 50;
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 11 * 60_000 }));
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "run-limit" });
+ });
+
+ it("a worker with no times for the lane runs a 20-minute first job to the end (the claim's limit is the run ceiling)", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ // About 20 minutes on the runner's clock (a cold model load and a long render), with the limit the studio gives.
+ fake.opts.steps = 40;
+ fake.opts.stepMs = 50;
+ let limit: number | undefined;
+ const clock = fastClock(600);
+ const t0 = clock();
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), clock), s, (t) => ((limit = t.runLimitMs), t));
+ expect(clock() - t0).toBeGreaterThan(19 * 60_000);
- expect(limit).toBe(pool.RUN_CEILING_MS);
++ expect(limit).toBe(runCeilingMs("small"));
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("an older studio's 5-minute limit for a lane with no times isn't obeyed: the job runs to the end", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.steps = 40;
+ fake.opts.stepMs = 15;
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 5 * 60_000 }));
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("the run limit counts from when its ComfyUI starts the job, not while the job waits in ComfyUI's queue", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ // Another prompt holds its ComfyUI for about 10 minutes first; the job itself then runs about 3, under an 11-minute limit.
+ fake.opts.steps = 20;
+ fake.opts.stepMs = 15;
+ fake.foreign(1_000);
+ await claimAndRun(runner(s, hooks({ stallLocalMs: 60 * 60_000 }), fastClock(600)), s, (t) => ({ ...t, runLimitMs: 11 * 60_000 }));
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "give-back")).toBe(false);
+ });
+
+ it("after running out of memory, only the retry's own time is reported", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.failNext = "oom";
+ // The first try (which runs out of memory) takes as long as the retry would; only the retry's time counts.
+ fake.opts.steps = 10;
+ fake.opts.stepMs = 30;
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id).state).toBe("done");
+ const finished = s.reports.find((x) => x.event === "finished")!;
+ const entry = finished.entry as { status?: { messages?: [string, { timestamp?: number }][] } };
+ const stamps = (entry.status?.messages ?? []).map(([, d]) => d.timestamp).filter((x): x is number => typeof x === "number");
+ expect(finished.execMs).toBe(Math.max(...stamps) - Math.min(...stamps));
+ });
+
+ it("a job its ComfyUI stopped on twice fails in plain words; the worker goes on", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.steps = 20;
+ fake.opts.stepMs = 40;
+ const r = runner(s, hooks({ crashes: () => 2 }));
+ const run = r.claimAndRun();
+ // ComfyUI restarts mid-job (it loses its queue and history).
+ for (let i = 0; i < 100 && !fake.log.some((l) => l.path === "/prompt"); i++) await sleep(20);
+ await sleep(200);
+ fake.restart();
+ await run;
+ expect(state(id)).toMatchObject({ state: "failed", error: "tab:input-crashed" });
+ expect(tabFailureWords("input-crashed")).not.toMatch(/ComfyUI|GPU|worker/i);
+ // The next job runs.
+ const id2 = task();
+ fake.opts.steps = 4;
+ fake.opts.stepMs = 20;
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id2).state).toBe("done");
+ });
+
+ it("reads each input from the studio once a job, even when the job is sent again", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ const cache = new Map<string, ArrayBuffer>();
+ let reads = 0;
+ fake.opts.loseNext = 1;
+ const input: WorkerHooks["input"] = async (_t, i, read) => {
+ const kept = cache.get(i.sha256);
+ if (kept) return kept;
+ reads++;
+ const got = await read();
+ if (typeof got !== "string") cache.set(i.sha256, got);
+ return got;
+ };
+ await runner(s, hooks({ input })).claimAndRun();
+ expect(state(id).state).toBe("done");
+ expect(s.reports.some((x) => x.event === "gone")).toBe(true);
+ expect(reads).toBe(1);
+ expect(s.reads).toHaveLength(1);
+ });
+
+ it("a studio that won't send an input again (429) fails the job instead of looping", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ s.set((p) => (p.includes("/inputs/") ? Response.json({ error: "That file was sent enough times." }, { status: 429 }) : undefined));
+ await runner(s, hooks()).claimAndRun();
+ expect(state(id)).toMatchObject({ state: "failed", error: "tab:input-changed" });
+ });
+
+ it("an input it can't take (a clip, with no way to make it again) gives the job back", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ await runner(s, hooks({ input: async () => "give-back" })).claimAndRun();
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "media" });
+ });
+ });
+
+ describe("results kept until the studio has them", () => {
+ it("a stop before the upload: the next start uploads the kept results, and ComfyUI got exactly one prompt", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const before = fake.posts();
+ // The worker stops as it starts the upload.
+ const first = runner(s, hooks({ hold: new Hold(holdDir) as never }));
+ s.set((p, init) => {
+ if (!p.includes("/outputs/") || init.method !== "PUT") return undefined;
+ first.stop();
+ throw new TypeError("fetch failed");
+ });
+ await first.claimAndRun();
+ expect(state(id).state).toBe("collecting");
+ expect(new Hold(holdDir).ids()).toEqual([id]);
+ // Its ComfyUI starts again (no history, no files), and so does the worker.
+ fake.restart();
+ s.set(null);
+ let claimed: string | null | undefined;
+ await runner(s, hooks({ hold: new Hold(holdDir) as never, claimed: (t) => void (claimed = t?.id ?? null) })).claimAndRun();
+ expect(claimed).toBe(id);
+ expect(state(id).state).toBe("done");
+ expect(saved(id).equals(FAKE_PNG)).toBe(true);
+ expect(fake.posts() - before).toBe(1);
+ });
+
+ it("a stop before the studio heard it finished: the kept results are reported and uploaded, never run again", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const before = fake.posts();
+ s.set((p, init) => {
+ if (p.endsWith("/report") && JSON.parse(String(init.body)).event === "finished") throw new TypeError("fetch failed");
+ return undefined;
+ });
+ await expect(runner(s, hooks({ hold: new Hold(holdDir) as never })).claimAndRun()).rejects.toThrow();
+ expect(state(id).state).toBe("running");
+ fake.restart();
+ s.set(null);
+ await runner(s, hooks({ hold: new Hold(holdDir) as never })).claimAndRun();
+ expect(state(id).state).toBe("done");
+ expect(saved(id).equals(FAKE_PNG)).toBe(true);
+ expect(fake.posts() - before).toBe(1);
+ const held = s.reports.filter((x) => x.event === "finished");
+ expect(held).toHaveLength(1);
+ expect(held[0].execMs).toBeTypeOf("number");
+ });
+
+ it("kept results go up without its ComfyUI; any other job claimed meanwhile goes straight back to the line", async () => {
+ const w = worker();
+ const s = studio(w);
+ const holdDir = tempDir("fuobe-worker-hold-");
+ // Nothing kept: a claim for kept results only lets a fresh job go at once.
+ const id = task();
+ let seen: (string | null)[] = [];
+ const r = runner(s, hooks({ hold: new Hold(holdDir) as never, claimed: (t) => void seen.push(t?.id ?? null) }));
+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);
+ expect(seen).toEqual([id]);
+ expect(state(id)).toMatchObject({ state: "waiting", worker_id: null, device: null, requeues: 0 });
+ // No job at all: the claim says so (null).
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(id);
+ seen = [];
+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);
+ expect(seen).toEqual([null]);
+ });
+
+ it("keeps every file its entries name, under no path but its own, and nothing that looks whole when a copy fails", async () => {
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const hold = new Hold(holdDir);
+ const t = { id: "BBBBBBBBBBBBBBBB", promptId: "00000000-0000-4000-8000-000000000001" } as ClaimedTask;
+ const entry = {
+ prompt: [1, t.promptId, { secret: "someone's prompt" }],
+ status: { status_str: "success", completed: true },
+ outputs: {
+ "9": {
+ images: [
+ { filename: "a_00001_.png", subfolder: "fuobe", type: "output" },
+ { filename: "../escape.png", subfolder: "", type: "output" },
+ { filename: "b.png", subfolder: "../..", type: "output" },
+ { filename: "c.png", subfolder: "", type: "input" },
+ ],
+ },
+ },
+ };
+ const asked: string[] = [];
+ await hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async (f: { filename: string; subfolder: string; type: string }) => {
+ asked.push(`${f.type}/${f.subfolder}/${f.filename}`);
+ return new Response(FAKE_PNG);
+ });
+ expect(asked).toEqual(["output/fuobe/a_00001_.png"]);
+ const got = await hold.get(t);
+ expect(got?.entries[0].prompt).toEqual([1, t.promptId]);
+ const blob = await hold.file(t, { filename: "a_00001_.png", subfolder: "fuobe", type: "output" });
+ expect(Buffer.from(await blob!.arrayBuffer()).equals(FAKE_PNG)).toBe(true);
+ // Another prompt for the same task (sent again from the start): not these results.
+ expect(await hold.get({ ...t, promptId: "00000000-0000-4000-8000-000000000002" })).toBeNull();
+ // A copy that fails halfway keeps nothing.
+ await expect(hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async () => null)).rejects.toThrow();
+ expect(hold.has(t.id)).toBe(false);
+ expect(fs.readdirSync(holdDir)).toEqual([]);
+ expect(() => hold.folder("../x")).toThrow();
+ expect(path.basename(hold.folder(t.id))).toBe(t.id);
+ });
+
+ it("lets go of kept results the studio never took after a day, and of a half-made copy that old", async () => {
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const hold = new Hold(holdDir);
+ const t = { id: "CCCCCCCCCCCCCCCC", promptId: "00000000-0000-4000-8000-000000000003" } as ClaimedTask;
+ await hold.keep(t, { kind: "finished", entries: [{ status: { status_str: "success", completed: true }, outputs: {} }] } as HeldResults, async () => new Response(FAKE_PNG));
+ fs.mkdirSync(path.join(holdDir, "DDDDDDDDDDDDDDDD"));
+ const day = 24 * 3_600_000;
+ expect(hold.expire(Date.now(), day)).toEqual([]);
+ expect(hold.ids()).toEqual([t.id]);
+ expect(hold.expire(Date.now() + day + 60_000, day).sort()).toEqual(["CCCCCCCCCCCCCCCC", "DDDDDDDDDDDDDDDD"]);
+ expect(fs.readdirSync(holdDir)).toEqual([]);
+ });
+
+ it("a claim with nothing for it says so with whether it was for kept results only, and the kept results stay", async () => {
+ const w = worker();
+ const s = studio(w);
+ const holdDir = tempDir("fuobe-worker-hold-");
+ const hold = new Hold(holdDir);
+ const kept = { id: "EEEEEEEEEEEEEEEE", promptId: "00000000-0000-4000-8000-000000000004" } as ClaimedTask;
+ await hold.keep(kept, { kind: "finished", entries: [{ status: { status_str: "success", completed: true }, outputs: {} }] } as HeldResults, async () => new Response(FAKE_PNG));
+ const seen: [string | null, boolean][] = [];
+ const r = runner(s, hooks({ hold: hold as never, claimed: (t, o) => void seen.push([t?.id ?? null, o.onlyHeld]) }));
+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);
+ expect(seen).toEqual([[null, true]]);
+ expect(hold.ids()).toEqual([kept.id]);
+ });
+ });
diff --cc tests/workers-pool.test.ts
index a85f36f1,f66edf7f..d7da019d
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@@ -20,11 -20,11 +20,12 @@@ const { principalOf } = await import("@
const beatRoute = await import("@/app/api/gpu/computer/beat/route");
const claimRoute = await import("@/app/api/gpu/computer/claim/route");
const reportRoute = await import("@/app/api/gpu/computer/tasks/[id]/report/route");
- const { forWorkers } = await import("@/server/providers/comfyui");
+ const { comfyProvider, forWorkers } = await import("@/server/providers/comfyui");
const { hoursAt, parseHours } = await import("@/lib/worker-hours");
- const { lanesFor, needsOf, laneOf } = await import("@/lib/lanes");
+ const lanesModule = await import("@/lib/lanes");
+ const { lanesFor, needsOf, laneOf } = lanesModule;
const { loadIndex } = await import("@/server/gpu/index-file");
- const { QUEUE_DEFAULTS, queueSettings, saveQueueSettings } = await import("@/server/queue-settings");
++const { QUEUE_DEFAULTS, queueSettings, runCeilingMs, saveQueueSettings } = await import("@/server/queue-settings");
const LANE_A = "aaaaaaaaaaaa";
const LANE_B = "bbbbbbbbbbbb";
@@@ -317,7 -393,7 +401,8 @@@ describe("routes", () =>
const { task: t } = await c.json();
expect(t.id).toBe(id);
expect(t.lane).toBe(LANE_A);
- // No measured run in its lane yet: the lane's run ceiling (45 minutes unless the owner sets another).
- // No times for the lane on this worker yet: the run ceiling, so a first long job (a cold model load) can finish.
++ // No times for the lane on this worker yet: the lane's run ceiling (45 minutes unless the owner sets another), so a
++ // first long job (a cold model load) can finish.
expect(t.runLimitMs).toBe(45 * MIN);
const sent = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify({ event: "sent", promptId: t.promptId }) }), {
params: Promise.resolve({ id }),
@@@ -369,3 -445,227 +454,227 @@@ describe("hours and lanes", () =>
expect(laneOf(index, id, sha)).toMatch(/^([0-9a-f]{12}|small)$/);
});
});
+
+ describe("a worker's own reports: giving a job back, its execution time, the inputs it takes", () => {
+ const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+ async function routed(w: W, id: string) {
+ const headers = { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" };
+ const c = await claimRoute.POST(new Request("http://localhost:3000/api/gpu/computer/claim", { method: "POST", headers, body: JSON.stringify({ running: [] }) }));
+ const { task: t } = await c.json();
+ expect(t.id).toBe(id);
+ const say = async (body: Record<string, unknown>) => {
+ const r = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify(body) }), { params: Promise.resolve({ id }) });
+ return { status: r.status, body: await r.json() };
+ };
+ return { t, say };
+ }
+
+ it("a job given back goes back in line with its place, counts as an attempt, and the third time fails in plain words", async () => {
+ clock = Date.now();
+ const id = task();
+ const rank = state(id).rank_at;
+ const w = worker("gives-back");
+ for (let i = 1; i <= 3; i++) {
+ const { t, say } = await routed(w, id);
+ expect(t.attempt).toBe(i);
+ expect((await say({ event: "sent", promptId: t.promptId })).status).toBe(200);
+ const back = await say({ event: "give-back", why: i === 1 ? "stalled" : i === 2 ? "run-limit" : "media" });
+ expect(back.status).toBe(200);
+ if (i < 3) {
+ expect(back.body.state).toBe("waiting");
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: i, rank_at: rank, worker_id: null });
+ expect(JSON.parse(state(id).tried_json ?? "[]")).toEqual([w.id]);
+ } else {
+ expect(back.body.state).toBe("failed");
+ expect(state(id).error).toBe(pool.GAVE_BACK_WORDS);
+ }
+ }
+ });
+
+ it("a job given back shows its kept place in line, then the usual words once a worker has it again: never a restart", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("words");
+ const poll = async () => (await comfyProvider.poll({ externalId: "11111111-1111-4111-8111-111111111111", meta: { relay: id, workflowId: "none", generationId: state(id).generation_id } } as never)) as { state: string; message?: string };
+ const first = await routed(w, id);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ await first.say({ event: "give-back", why: "stalled" });
+ expect(state(id)).toMatchObject({ state: "waiting", note: "resent" });
+ const waiting = await poll();
+ expect(waiting).toMatchObject({ state: "queued", message: pool.poolWaitWords(state(id)) });
+ expect(waiting.message).not.toMatch(/another GPU|restart/i);
+ await routed(w, id);
+ const again = await poll();
+ expect(state(id).state).toBe("sending");
+ expect(again.state).toBe("queued");
+ expect(again.message).not.toMatch(/restart|sent it again/i);
+ });
+
+ it("a give-back with an unknown reason is refused, and a person's own computer can't give its job back", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("bad-reason");
+ const { t, say } = await routed(w, id);
+ await say({ event: "sent", promptId: t.promptId });
+ expect((await say({ event: "give-back", why: "bored" })).status).toBe(400);
+ expect(state(id).state).toBe("queued");
+ const own = tasks.createTask({ principal: "owner", generationId: "own-gen", graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } } });
+ db().prepare("UPDATE relay_tasks SET state = 'running' WHERE id = ?").run(own.id);
+ expect(() => tasks.report(state(own.id), { event: "give-back", why: "stalled" }, () => ({ error: "x" }))).toThrow(/doesn't fit/);
+ });
+
+ it("keeps the execution time and the GPU name a worker reports with a finished job", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("exec");
+ const { t } = await routed(w, id);
+ tasks.report(state(id), { event: "sent", promptId: t.promptId }, () => ({ error: "x" }));
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ tasks.report(state(id), { event: "finished", entry, execMs: 12_345.6, device: " Test GPU " }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ expect(state(id).state).toBe("done");
+ expect(tasks.execOf(state(id))).toEqual({ ms: 12_346, device: "Test GPU" });
+ // Nothing reported: nothing kept; a nonsense time is not kept either.
+ const id2 = task();
+ const { t: t2 } = await routed(w, id2);
+ tasks.report(state(id2), { event: "sent", promptId: t2.promptId }, () => ({ error: "x" }));
+ tasks.report(state(id2), { event: "finished", entry, execMs: -5 }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ expect(tasks.execOf(state(id2))).toBeNull();
+ });
+
+ it("holds a reported execution time to the time since the job was sent, and to its run ceiling", async () => {
+ clock = Date.now();
+ const w = worker("exec-caps");
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ const finish = async (sentAgoMs: number, execMs: number) => {
+ const id = task();
+ const { t } = await routed(w, id);
+ tasks.report(state(id), { event: "sent", promptId: t.promptId }, () => ({ error: "x" }));
+ tasks.setTask(id, { sent_at: Date.now() - sentAgoMs });
+ tasks.report(state(id), { event: "finished", entry, execMs }, () => ({ wanted: [], outputs: [], budget: 0 }));
+ return tasks.execOf(state(id))!.ms;
+ };
+ // Sent 2 minutes ago, said to have run 10 hours: about 3 minutes (2, and the minute allowed before "sent").
+ const capped = await finish(2 * MIN, 10 * 60 * MIN);
+ expect(capped).toBeGreaterThanOrEqual(3 * MIN - 1_000);
+ expect(capped).toBeLessThanOrEqual(3 * MIN + 1_000);
+ // Sent 3 hours ago, said to have run 2 hours: the run ceiling.
- expect(await finish(180 * MIN, 120 * MIN)).toBe(pool.RUN_CEILING_MS);
++ expect(await finish(180 * MIN, 120 * MIN)).toBe(runCeilingMs(LANE_A));
+ // A sound time stays as it was.
+ expect(await finish(30 * MIN, 25 * MIN)).toBe(25 * MIN);
+ });
+
+ it("past its run limit: back in line once, with the whole run ceiling for its next try; past it again, it fails at once", async () => {
+ clock = Date.now();
+ const id = task();
+ const w = worker("run-limit");
+ db().prepare("UPDATE relay_workers SET bench_json = ? WHERE id = ?").run(JSON.stringify({ [LANE_A]: { medianMs: 2 * MIN, p90Ms: 3 * MIN } }), w.id);
+ const first = await routed(w, id);
+ expect(first.t.runLimitMs).toBe(10 * MIN);
+ expect(first.t.stallMs).toBe(pool.STALL_MS);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ expect((await first.say({ event: "give-back", why: "run-limit" })).body.state).toBe("waiting");
+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });
+ // The lane's times may come from shorter jobs: this one gets the whole ceiling now.
+ const second = await routed(w, id);
- expect(second.t.runLimitMs).toBe(pool.RUN_CEILING_MS);
++ expect(second.t.runLimitMs).toBe(runCeilingMs(LANE_A));
+ await second.say({ event: "sent", promptId: second.t.promptId });
+ const back = await second.say({ event: "give-back", why: "run-limit" });
+ expect(back.body.state).toBe("failed");
+ expect(state(id)).toMatchObject({ state: "failed", error: pool.GAVE_BACK_WORDS, requeues: 2 });
+ // Other reasons still have three tries: a stall after one run-limit goes back in line.
+ const id2 = task();
+ const third = await routed(w, id2);
+ await third.say({ event: "sent", promptId: third.t.promptId });
+ await third.say({ event: "give-back", why: "run-limit" });
+ const fourth = await routed(w, id2);
+ await fourth.say({ event: "sent", promptId: fourth.t.promptId });
+ expect((await fourth.say({ event: "give-back", why: "stalled" })).body.state).toBe("waiting");
+ });
+
+ it("results kept from an earlier try go up as no new attempt, keep their own time, and add no time to the lane", async () => {
+ clock = Date.now();
+ const entry = { status: { status_str: "success", completed: true }, outputs: {} };
+ // Made 10 minutes ago; it ran, its worker stopped before the studio heard, and it went back in line.
+ const id = task({ rankAgoMs: 10 * MIN });
+ const w = worker("kept");
+ const first = await routed(w, id);
+ await first.say({ event: "sent", promptId: first.t.promptId });
+ expect(state(id).attempts).toBe(1);
+ pool.backInLine(state(id), { blame: true });
+ const again = await routed(w, id);
+ expect((await again.say({ event: "sent", promptId: again.t.promptId, kept: true })).status).toBe(200);
+ expect(state(id).attempts).toBe(1);
+ const done = await again.say({ event: "finished", entry, execMs: 4 * MIN, device: "Test GPU <b>", kept: true });
+ expect(done.status).toBe(200);
+ expect(state(id).state).not.toBe("queued");
+ // Its time ran before this "sent": kept as reported (it is under the time since the task was made). The GPU's name
+ // keeps only plain characters.
+ expect(tasks.execOf(state(id))).toEqual({ ms: 4 * MIN, device: "Test GPU b" });
+ expect(JSON.parse(row(w).bench_json ?? "{}")[LANE_A]).toBeUndefined();
+ // A job that runs here counts toward the lane's times, and its "sent" is an attempt.
+ const id2 = task();
+ const run = await routed(w, id2);
+ await run.say({ event: "sent", promptId: run.t.promptId });
+ expect(state(id2).attempts).toBe(1);
+ tasks.setTask(id2, { sent_at: Date.now() - 5_000 });
+ await run.say({ event: "finished", entry, execMs: 1_000 });
+ expect(JSON.parse(row(w).bench_json ?? "{}")[LANE_A]?.runs).toHaveLength(1);
+ });
+
+ it("a worker that can't make clips and sound again gets no workflow that reads them", () => {
+ const index = loadIndex();
+ const { mediaOf } = lanesModule;
+ const reads = Object.keys(index.workflows).filter((k) => !index.workflows[k].isolated && mediaOf(index.workflows[k]).length);
+ const pictures = Object.keys(index.workflows).filter((k) => !index.workflows[k].isolated && !mediaOf(index.workflows[k]).length);
+ expect(reads.length).toBeGreaterThan(10);
+ // A worker that has every file and pack.
+ const files = Object.values(index.files).map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ const nodePacks = Object.keys(index.packs).map((name) => ({ name, commit: null }));
+ const all = lanesFor(index, { files, nodePacks, media: ["image", "video", "audio"] }, sha).workflows;
+ expect(all).toEqual(expect.arrayContaining([...reads, ...pictures]));
+ const onlyPictures = lanesFor(index, { files, nodePacks, media: ["image"] }, sha);
+ expect(onlyPictures.workflows).toEqual(expect.arrayContaining(pictures));
+ for (const id of reads) expect(onlyPictures.workflows).not.toContain(id);
+ expect(onlyPictures.missing.some((m) => m.files.includes("input:video"))).toBe(true);
+ // A worker from before workers said which inputs they take (no `media`) never re-encodes clips: pictures only.
+ expect(lanesFor(index, { files, nodePacks }, sha).workflows).toEqual(onlyPictures.workflows);
+ });
+
+ it("a job's run limit: the run ceiling with no times yet, else 3 × the lane's p90 plus its load, 10 minutes to the ceiling", () => {
- expect(pool.runLimitMs(undefined)).toBe(pool.RUN_CEILING_MS);
++ expect(pool.runLimitMs(undefined)).toBe(runCeilingMs(LANE_A));
+ expect(pool.runLimitMs(null, "small", 200_000)).toBe(45 * MIN);
+ expect(pool.runLimitMs(0)).toBe(45 * MIN);
+ expect(pool.runLimitMs(30_000)).toBe(10 * MIN);
+ expect(pool.runLimitMs(4 * MIN, "small", 3 * MIN)).toBe(15 * MIN);
+ expect(pool.runLimitMs(20 * MIN, "small", 5 * MIN)).toBe(45 * MIN);
+ // The claim gives the worker's own times for the lane.
+ clock = Date.now();
+ const id = task();
+ const w = worker("timed");
+ db().prepare("UPDATE relay_workers SET bench_json = ? WHERE id = ?").run(JSON.stringify({ [LANE_A]: { medianMs: 3 * MIN, p90Ms: 4 * MIN, loadMs: 3 * MIN } }), w.id);
+ const t = pool.workerClaim(row(w), [], clock)!;
+ expect(t.id).toBe(id);
+ expect(t.runLimitMs).toBe(15 * MIN);
+ });
+
+ it("an older worker's inventory (no `media`) keeps its hash, so the studio doesn't ask for it at every beat", () => {
+ const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };
+ const w = worker("older");
+ pool.saveInventory(row(w), inv);
+ expect(row(w).inventory_hash).toBe(pool.inventoryHash(inv));
+ expect(JSON.parse(row(w).inventory_json ?? "{}").media).toBeUndefined();
+ });
+
+ it("the inventory's hash covers the kinds of input, and the worker hashes it the same way", async () => {
+ const { inventoryHash: workerHash } = await import("../bin/lib/worker/inventory.mjs");
+ const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };
+ expect(pool.inventoryHash({ ...inv, media: ["image"] })).not.toBe(pool.inventoryHash(inv));
+ expect(pool.inventoryHash({ ...inv, media: ["video", "image"] })).toBe(pool.inventoryHash({ ...inv, media: ["image", "video"] }));
+ expect(workerHash({ ...inv, media: ["image", "audio"] })).toBe(pool.inventoryHash({ ...inv, media: ["image", "audio"] }));
+ const w = worker("media");
+ const saved = pool.saveInventory(row(w), { ...inv, media: ["image", "teleport"] });
+ expect(saved.lanes).toBeDefined();
+ expect(JSON.parse(row(w).inventory_json ?? "{}").media).toEqual(["image"]);
+ });
+ });
diff --cc workflows/comfyui/requirements.json
index 0d1ec6a6,05bf70be..a099d030
--- a/workflows/comfyui/requirements.json
+++ b/workflows/comfyui/requirements.json
@@@ -1,6 -1,6 +1,6 @@@
{
"v": 1,
- "hash": "2afa9c2e36d41f07827cae818d0515ab35fe16fc7c2e82bdc81f6975539753e6",
- "hash": "b095fdeec33909f3f45e9b1deb95051ef7b623bd27750b551ee3391545f20754",
++ "hash": "3abbe8e8de3085b812a6b93cd74572176d72b82b31334ab5fb927b7ebfd30288",
"comfyui": {"min":"0.42.0","testedCommit":"5841c187"},
"folders": ["audio_encoders","background_removal","checkpoints","clip_vision","dbs","diffusion_models","facerestore_models","foley","frame_interpolation","geometry_estimation","insightface","latent_upscale_models","loras","mmaudio","model_patches","optical_flow","reuse","sams","text_encoders","thinksound","upscale_models","vae"],
"sentinels": ["AILab_Qwen3ASRSubtitle","AILab_Qwen3TTSVoiceClone_Advanced","AILab_Qwen3TTSVoiceDesign_Advanced","AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_MaskByTouch","AUSBOSS_NODES_StitchInpaint","Add Subtitles To Frames","Apply Whisper","CFGOverride","ClothesSegment","ComfyMathExpression","CropFuobeLive","DBSLoader","DBSSeparate","DownloadAndLoadWav2VecModel","DualModelGuider","FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC","GetImageRangeFromBatch","GetImageSizeAndCount","GrowMaskWithBlur","H3AdaLNLoRAFix","H3AdvancedSwapPlan","H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan","H3ClipShots","H3FaceChunks","H3FaceJoin","H3FaceMaskSAM","H3FaceStitch","H3FaceTrackCrop","H3FillShots","H3GreyMannequins","H3ObjectSwapPlan","H3PeopleMask","H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan","H3RoleMask","H3SLAAttention","H3SoundtrackOrSilence","H3SourceSlice","H3SubjectPrompt","H3TrackCrops","H3TrackRoles","HunyuanDependenciesLoader","HunyuanFoleySampler","HunyuanModelLoader","INTConstant","Ideogram4Scheduler","ImageBatchExtendWithOverlap","ImageDetailContrast","ImageGridtoBatch","ImageResizeKJv2","IndexTTS2Simple","Krea2EditGroundedEncode","Krea2EditModelPatch","Krea2OstrisEditModelPatch","LTXAVTextEncoderLoader","LTXAddVideoICLoRAGuide","LTXICLoRALoaderModelOnly","LTXVAddGuide","LTXVAudioVAEDecode","LTXVAudioVAELoader","LTXVConcatAVLatent","LTXVConditioning","LTXVCropGuides","LTXVDualCFGGuider","LTXVEmptyLatentAudio","LTXVImgToVideoInplace","LTXVLatentUpsampler","LTXVPreprocess","LTXVScheduler","LTXVSeparateAVLatent","LTXVTiledFusionSampler","LatentSyncNode","LoadBackgroundRemovalModel","LoadImageFuobeLive","LoadVideoDepthAnythingModel","MMAudioFeatureUtilsLoader","MMAudioModelLoader","MMAudioSampler","MelBandRoFormerModelLoader","MelBandRoFormerSampler","Metric3D-NormalMapPreprocessor","MiniMaxH3ChainAssemble","MiniMaxH3ChainContext","MiniMaxH3ChainCurrent","MiniMaxH3ChainLoopEnd","MiniMaxH3ChainLoopStart","MiniMaxH3ChainPlanModern","MiniMaxH3ChainReview","MiniMaxH3ChainSegmentSave","MiniMaxH3ContexMaskedTarget","MiniMaxH3FantasticVideoEditLatent","MiniMaxH3GenerationProfile","MiniMaxH3LoopTrim","MiniMaxH3SourceTimeline","MiniMaxH3TurboLoRA","MiniMaxH3TurboSampler","MultiTalkModelLoader","MultiTalkWav2VecEmbeds","OpenH3RegenFastVAEDecode","OpenH3RegenFinish","OpenH3RegenLora","OpenH3RegenPrepareDraft","OpenH3RegenRefineLatent","OpenH3RegenSigmas","OpenH3RegenUpscale","OpenH3SaveRefinedLatent","Orion4D_FXMax_DCTLToneMapper","PasteBackFuobeLive","QWMComposite","QWMDetect","QWMFinal","QWMPrepare","QWMRefineMask","QWMResidualDetect","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","QwenImage21Cache","REUSEEnhance","REUSELoader","RIFE VFI","RMBG","ReActorFaceSwap","RemoveBackground","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SAMLoader","SaveImageFuobeLive","SeedVR2Conditioning","SeedVR2PostProcessing","SeedVR2Preprocess","SolarRendererConditioning","SolarRendererLoraLoader","SolarRendererModel","SolarRendererSigmas","TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO","TextEncodeFibo2","TextEncodeKrea2OstrisEdit","TextEncodeQwenImage21","ThinkSoundFeatureUtilsLoader","ThinkSoundModelLoader","ThinkSoundSampler","Trellis2Conditioning","Trellis2ShapeStage","Trellis2TextureStage","Trellis2UpsampleStage","VHS_BatchManager","VHS_LoadAudioUpload","VHS_LoadVideo","VHS_SelectEveryNthImage","VHS_VideoCombine","VHS_VideoInfo","VHS_VideoInfoLoaded","VRAM_Debug","VideoDepthAnythingOutput","VideoDepthAnythingProcess","VideoLengthAdjuster","ViggleTurboLora","ViggleTurboSigmas","VoxCPM2_Clone","VoxCPM2_TTS","WanVideoBlockSwap","WanVideoClipVisionEncode","WanVideoDecode","WanVideoEncode","WanVideoImageToVideoMultiTalk","WanVideoLoraSelect","WanVideoModelLoader","WanVideoPassImagesFromSamples","WanVideoSampler","WanVideoTextEncodeCached","WanVideoVAELoader","ZenImage21AdapterLoader","ZenImage21TextEncode"],