The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Runs on this install's GPUs wait to enter the line instead of being refused; only a press past the cap is turned down
Adarsh1be99d120f48
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex 32d70936..242b14ad 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -134,7 +134,7 @@ A file that looks like the note but was changed (it has a password or a sign-in| `FUOBE_LLM_CONTEXT` | Tokens of context for the local model (default `16384`): Ollama's `num_ctx`, and the context LM Studio loads a model with. `0` leaves it to the server || `OPENAI_API_KEY`, `GEMINI_API_KEY` | Read into Settings; no feature uses them yet || `WORLDCAST_URL`, `WORLDCAST_TOKEN` | The WorldCast worker's address (also a Settings field) and its shared secret, sent as a Bearer header on every call; set the same `WORLDCAST_TOKEN` where the worker runs. The token has no Settings field yet. Without one, keep the worker on `127.0.0.1` ([worldcast.md](workers/worldcast.md)) |-| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs |+| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs. While it is on, an account's runs at once (4) and per hour (60) count its runs on its own GPU or key and its light work (a join, a trim) only: its other runs on this install's GPUs meet the billing service's limits instead (with `FUOBE_HOSTED_FREE=1`, 4 at once, 4 waiting and 60 an hour, refused past them as before). The table of runs waiting to enter the line (`pool_holds`, used only when a billing service's policy says runs wait instead of being refused) is made on every install and stays empty, and unread, while hosted runs are off || `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed || `FUOBE_PLACE_NAME` | The name visitors read for this install's GPUs while hosted runs are on ("Runs on Ana's render box", "Made on: Ana's render box"), at most 40 characters. Also Settings → Workers → Name for your GPUs, which wins over it; a billing service's own name for them wins over both. Unset: "Our GPUs". Nothing reads it while hosted runs are off. The table that keeps where each account picked its runs to go (`account_run_on`) is made on every install and stays empty, and unread, while hosted runs are off || `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`). A billing service's policy (`limits.giveUpS`, 0: no limit) or reserve answer wins over it. With hosted runs on and no billing service, a run that waits this long ends with one plain sentence, "Sorry, this one couldn't be made." |diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 39f7e635..25604b10 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -56,7 +56,7 @@ type Action = { label: string; url: string }; // Fuobe opens url astype Offer = { key: string; text: string; label: string }; // a click sends POST /v1/interest { account, key }type RefuseCode = "top-up" | "limit" | "busy" | "not-offered" | "blocked" | "closed" | "paused";-type Quote = { allowed: boolean; amount: number; priceVersion: string; text: string; sub?: string; code?: RefuseCode; etaS?: number | null; action?: Action; offer?: Offer };+type Quote = { allowed: boolean; amount: number; priceVersion: string; text: string; sub?: string; code?: RefuseCode; etaS?: number | null; startAt?: number; action?: Action; offer?: Offer };type Policy = {hosted: boolean; // may this account use this install's GPUs at allpool: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; // models and apps there@@ -66,6 +66,7 @@ type Policy = {keepDays: number; spaceBytes: number; addressRunsPerHour?: number;giveUpS?: number; // longest wait before a GPU first takes a run (0: none)offerAfterS?: number; // a wait after which an account's own GPU or key is offered (absent: 1200)+ held?: number; // runs that may wait behind an account's runs at once (0: no cap; absent: limits refuse)};prefer?: "pool" | "own"; // the default place (absent: "own")kinds?: { image?: boolean; video?: boolean; audio?: boolean; text?: boolean; model3d?: boolean }; // absent: all@@ -86,6 +87,20 @@ estimates it) after which the line before Run offers an account its own GPU, orversion at its price, for that one run. Absent: 1200. A wait with no end known (every GPU that could run it is away)counts as past it.+`limits.held` says runs wait instead of being refused. Present (0 or more), a press past `limits.activeRuns`,+`limits.waiting` or an hourly limit is taken: the run is made, its tile says "In line", and it enters the line when+its reason clears (at the back of the line, so an account's fast presses never pass anyone). `limits.held` is how many+runs may wait like that behind the account's runs at once (`0`: no cap); a press past it is the only one refused,+"You have 10 runs on the way. Add more when one is done." Absent (an older service), every limit refuses as before.++`startAt` (epoch ms, only with `allowed: true` or `ok: true`) says the run may be made now and waits until then before+it enters the line: the day's GPU time is used up (a `startAt` at a UTC midnight: the line before Run says "Lots of+runs today · starts in about 7 h", and at that time the runs enter at their press-time places, in press order), or an+hourly limit (at the back of the line). With credits on, a reserve refused with `top-up` whose quote is allowed with a+`startAt` (free generations that renew then) waits too, and reserves at that time. `timing.heldMs` is about how long+the run is expected to wait before it enters the line at all (behind the account's runs, or until a time it was+given); a service adds it to the hold's life.+While the service doesn't answer, a run that would go to this install's GPUs because the service's last answer put themfirst (`prefer: "pool"`) waits for the service; it is never moved to the account's own GPU for that.@@ -198,7 +213,7 @@ answers again.| Call | Request | Answer ||---|---|---|| `POST /v1/quote` | `{ account: AccountFacts \| null, run: RunFacts, queue: QueueFacts \| null }` | `Quote` |-| `POST /v1/reserve` | `{ requestId, account: AccountFacts, run: RunFacts, queue: QueueFacts \| null, shown: { amount, priceVersion }, timing?: { runMs, pausedMs } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, class?, text }` or `{ ok: false, code: RefuseCode \| "price-changed", text, quote?, action?, offer? }` |+| `POST /v1/reserve` | `{ requestId, account: AccountFacts, run: RunFacts, queue: QueueFacts \| null, shown: { amount, priceVersion }, timing?: { runMs, pausedMs, heldMs? } }` | `{ ok: true, holdId, amount, boostMs, maxWaitMs, pools?, class?, text, startAt? }` or `{ ok: false, code: RefuseCode \| "price-changed", text, quote?, action?, offer? }` || `POST /v1/release` | `{ holdId, reason: "not-created" }` or `{ requestId, reason: "not-created" }` | `{ ok: true }` || `POST /v1/settle` | `{ holdId, generationId, rows, status: "succeeded", final: { outputs, megapixels, seconds }, providerUsd, gpuMs, device, reachedProvider }` | `{ ok: true, charged }` || `POST /v1/refund` | `{ holdId, generationId, rows, status: "failed" \| "canceled" \| "hidden" \| "unchecked", reason, reachedProvider, gpuMs, device }` | `{ ok: true, text }` |@@ -303,6 +318,7 @@ seconds. A stop that comes after the result was saved leaves the run saved, so i|---|---|| No `FUOBE_BILLING_URL` | No call. Runs on this install's GPUs are closed, or free and allowed with `FUOBE_HOSTED_FREE=1`. || Set, and it answers | As above. |-| Set, and no answer in time | A press of Run waits while the reserve is tried again for up to 40 seconds (a restart of the service), and the feed shows the run as "In line" meanwhile. Then the run is made with its place in line. Past that, the run is refused (503, "Try again in a moment.") and nothing is made. The last policy stands for 10 minutes (above). Before Run, the price slot says "Ready in a moment" and Run is off; the price check asks again by itself, and Run comes back on with its answer. Runs on the account's own GPU or key go on. Reports wait in the outbox and are sent when it is back. Runs that already have a hold keep running. |+| Set, no answer in time, and the policy has `limits.held` | The reserve is tried for up to 5 seconds. Then the run is made all the same and its tile shows "In line" at its place, with no card and no toast; it reserves under its press's own request id (so the service makes one hold for it) once the service answers (tried again after 1 s, doubling to 30 s, and at once after the service answers any call), and enters at its press-time place. A refusal then ends the run in one plain sentence. Before Run, the price slot shows the last price the service gave for that run (kept 10 minutes), else nothing, and Run stays on. While the service answers `paused`, its words are the line before Run and a press waits the same way. A moderation service that doesn't answer at a studio's press is handled the same way: the run is checked before it enters the line. Runs waiting longer than 5 minutes are said in the server log. |+| Set, and no answer in time (no `limits.held`) | A press of Run waits while the reserve is tried again for up to 40 seconds (a restart of the service), and the feed shows the run as "In line" meanwhile. Then the run is made with its place in line. Past that, the run is refused (503, "Try again in a moment.") and nothing is made. The last policy stands for 10 minutes (above). Before Run, the price slot says "Ready in a moment" and Run is off; the price check asks again by itself, and Run comes back on with its answer. Runs on the account's own GPU or key go on. Reports wait in the outbox and are sent when it is back. Runs that already have a hold keep running. |The service's address and its errors are written to the server's log only. A browser never sees them.diff --git a/docs/public-signup.md b/docs/public-signup.mdindex e56ce42a..17a72b50 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -714,7 +714,33 @@ With it on:(0: as long as it takes), else what its reserve answer says, else `FUOBE_POOL_WAIT_MIN` minutes (30 by default).Past that it fails with one plain sentence, not charged. A later step of a run (a chain's next step) keeps the run'splace in line and has no wait limit.-- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.+- When the billing service's policy says runs wait instead of being refused (`limits.held`: how many may wait behind+ an account's runs at once), a press past a limit is taken all the same: the run and its tile exist at once ("In+ line"), and the run enters the line when its reason clears (`src/server/pool-holds.ts`, released by+ `src/server/pool-release.ts` in the generations runner's turn, in every app process):+ - past the account's runs at once (`limits.activeRuns`): "Starts after your other runs" before Run, "In line · after+ your other runs" on the tile; it enters at the back of the line when one of them ends, so ten fast presses never+ pass another account, and its presses enter in the order they were made;+ - the day's GPU time used up (the service's `startAt` at the next UTC day): "Lots of runs today · starts in about+ 7 h" before Run, "In line · starts in about 7 h" on the tile; at the renewal the runs enter at their press-time+ places, in press order;+ - the billing service doesn't answer within 5 s of the press (or the moderation service doesn't, at a studio's+ press), or a run was cut off between its row and its GPU task (a deploy, a crash): its tile shows its place as if+ in line, it reserves (and is checked) under its press's own request id once the service answers, and enters at its+ press-time place. While the service says runs+ here are paused, the line before Run shows its words, and a press waits ("In line · starts when a GPU is free");+ - an hourly limit or free generations that renew (credits on): it starts at that time, at the back of the line.++ Holds are kept in SQLite (`pool_holds`) with a lease per run, so they survive a deploy, a restart and two app+ processes at once. Cancel works on a held run like on any other. A deleted account's holds go with it. Only a press+ past the cap on runs waiting is turned down: "You have 10 runs on the way. Add more when one is done." The owner+ reads the held runs by why they wait (counts only) in Settings → Workers ("Waiting to enter the line: 3 (oldest 12+ min)") and in `GET /api/admin/queue` and `/api/admin/workers` (`held`). Runs waiting for the billing service longer+ than 5 minutes are said in the server log. With a policy that has no `limits.held` (an older service), every limit+ refuses as before.+- The account's usual limits apply: outputs per run and its space. Its runs at once (4) and per hour (60) count its+ runs on its own GPU or key and its light work (a join, a trim) only: its other runs on this install's GPUs meet the+ billing service's limits instead. (With hosted runs off they count every run, as before.)Two optional services can go with it:diff --git a/src/app/api/admin/workers/route.ts b/src/app/api/admin/workers/route.tsindex 62b4b61a..9cf3f80b 100644--- a/src/app/api/admin/workers/route.ts+++ b/src/app/api/admin/workers/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { adminAccess, audit } from "@/server/admin-tokens";import { addWorker, lanesCatalog, listWorkers } from "@/server/computer/pool";+import { heldView } from "@/server/pool-holds";const NO_STORE = { "Cache-Control": "no-store" };const DENIED = "Only the studio's owner manages workers";@@ -9,13 +10,14 @@ const DENIED = "Only the studio's owner manages workers";* Settings → Workers (owner only, or an admin token with workers:read / workers:tokens; docs/gpu-workers.md): the* shared GPUs with their state in words, and the lanes this studio's catalog has (to allow per worker). POST* `{ name, pool? }` adds one: paused, with no hours and no lanes; its token is in this answer only. A worker's token- * receives accounts' queued jobs and their files, so making one needs workers:tokens, not just workers:write.+ * receives accounts' queued jobs and their files, so making one needs workers:tokens, not just workers:write. `held`:+ * the runs made but waiting to enter the line (hosted runs, pool-holds.ts), by why, and the oldest: counts only.*/export async function GET(request: Request) {await connection();const access = adminAccess(request, "workers:read", DENIED);if (access instanceof Response) return access;- return Response.json({ workers: listWorkers(), lanes: lanesCatalog() }, { headers: NO_STORE });+ return Response.json({ workers: listWorkers(), lanes: lanesCatalog(), held: heldView() }, { headers: NO_STORE });}export async function POST(request: Request) {diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 72ff17c8..db5f6266 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -15,17 +15,18 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskimport { accountInputProblem } from "@/server/account-inputs";import { findView, requestViewKey } from "@/server/any-angle";import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, captureRun, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, stepsOf, type AccountRunRefusal } from "@/server/generations";-import { accountActiveRuns, AdmitRefused, admitRun, clientAddress, poolLimitRefusal } from "@/server/pool-limits";+import { AdmitRefused, admitRun, clientAddress, ownActiveRuns, poolLimitPlan, type LimitPlan } from "@/server/pool-limits";+import { heldGuessMs, holdRun, holdShape, type HoldReason } from "@/server/pool-holds";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { hit, unhit } from "@/server/rate";import { GenerationRequestSchema } from "@/server/request-schema";import { gateGeneration, GPU_SETUP_HEADER } from "@/server/gpu/gate";import { gpuTargetFor } from "@/server/gpu/target";import { connectNeeds } from "@/server/connect-refusal";-import { BILLING_HEADER, BILLING_WAIT } from "@/server/billing";+import { BILLING_HEADER, BILLING_WAIT, holdsOn } from "@/server/billing";import { queueRelease } from "@/server/billing-outbox";import { runOnPool } from "@/server/hosted";-import { decidePlace, moderateRun, policyWait, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";+import { decidePlace, moderateRun, policyWait, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal, type ReserveFacts, type ReserveWait } from "@/server/hosted-run";import { withRunStamp, type RunStamp } from "@/server/run-stamp";import { hostedRunsOn } from "@/server/hosted-switch";import { endTry, notePressRun, pressPrior, pressRun, pressTries, pressTry, readPressId } from "@/server/run-requests";@@ -115,16 +116,34 @@ export async function POST(request: Request) {// A visitor's price check: priced as it would run, as that visitor (an account: its own GPU and keys; a guest: the open// engine, no demo).const priced = <T,>(fn: () => T): T => (viewer.kind === "owner" ? fn() : account ? asAccount(account.id, fn) : asVisitor(null, fn));+ // When the press came: a run that waits to enter the line for the system's reasons keeps this place (pool-holds.ts).+ const pressedAt = Date.now();+ // The studio's own limits of runs at once and an hour: with hosted runs off, on every run of an account, checked first,+ // as always. With them on, on its runs on its own GPU or key and its light work only (its other runs on this+ // install's GPUs meet the policy's limits instead), checked once its place is known. A refused run gives its count of the hour back (unhitRun).+ const ownLimitsFirst = !hostedRunsOn();+ let rated = false;+ const unhitRun = () => {+ if (account && rated) unhit(`run:${account.id}`);+ rated = false;+ };+ const ownLimits = (id: string): Response | null => {+ if (ownActiveRuns(id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });+ const rate = hit(`run:${id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);+ if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });+ rated = true;+ return null;+ };/** An account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */const refused = (r: AccountRunRefusal) => {- if (account) unhit(`run:${account.id}`);+ unhitRun();const a = accountRunAnswer(r);return refuse(a.status, a.body.error, a.body, a.headers);};// Beside the request (never in it): the place the client prefers, and the price it showed (hosted runs, billing hook).const { wish, shown } = readWishes(body, request.headers);const refusedBy = (r: Refusal) => {- if (account) unhit(`run:${account.id}`);+ unhitRun();return refuse(r.status, r.body.error, r.body, r.headers);};// With hosted runs on, an account's press of Run whose run goes to this install's GPUs is made once however often the@@ -140,9 +159,10 @@ export async function POST(request: Request) {// Room on the server, room in the account's files, and a fair share of runs.if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);if (accountUsage(account.id).total >= accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));- if (accountActiveRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });- const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);- if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });+ if (ownLimitsFirst) {+ const no = ownLimits(account.id);+ if (no) return no;+ }if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {req = { ...req, params: { ...req.params, numOutputs: ACCOUNT_LIMITS.outputsPerRun } };notes.push(ACCOUNT_MESSAGES.outputsCapped);@@ -150,7 +170,7 @@ export async function POST(request: Request) {// Only files it uploaded here, or its own results (no links, no data: URIs, nobody else's).const problem = accountInputProblem(req, account.id);if (problem) {- unhit(`run:${account.id}`);+ unhitRun();return refuse(problem.status, problem.error, { code: problem.code });}}@@ -162,7 +182,7 @@ export async function POST(request: Request) {const built = findView(key, account?.id);const g = built ? getGeneration(built) : null;if (g) {- if (account) unhit(`run:${account.id}`);+ unhitRun();return Response.json({ items: [g] }, { status: 201 });}// The build takes nothing but the photo (fixed seeds, src/lib/catalog/any-angle.ts): other params are dropped, so@@ -192,17 +212,27 @@ export async function POST(request: Request) {if (decision.kind === "refuse") return refusedBy(decision.refusal);}const onPool = decision.kind === "pool" ? decision : null;+ // A run on the account's own GPU or key, or light work (free, on this install's CPU), with hosted runs on: the+ // studio's own limits, now that its place is known.+ if (account && !preview && (!onPool || onPool.light) && !ownLimitsFirst) {+ const no = ownLimits(account.id);+ if (no) return no;+ }// The try of the press this send is, for a run on this install's GPUs only (run-requests.ts).const poolTry = account && onPool && pressId ? pressTries(account.id, pressId) : null;// The client's address, kept only as a salted hash for the policy's hourly count per address (null: no trusted proxy).const addr = account && onPool ? clientAddress(request) : null;+ // What the policy's limits say of it: into line now, waiting to enter it (held), or refused.+ let plan: LimitPlan = { go: true };if (account && onPool) {// The policy's limits for runs on this install's GPUs, counted on runs there only (never on runs on the account's own// GPU or key, nor on a run of light work only, which is free): said now, before anything is checked or set aside, and- // counted again as the run is made (admitRun).- const over = onPool.light ? null : poolLimitRefusal(account.id, onPool.policy, addr);- if (over) {- unhit(`run:${account.id}`);+ // counted again as the run is made (admitRun). Past a limit it can wait out, the run is taken and waits to enter the+ // line (when the policy says so); only a press past the cap on runs waiting is refused.+ plan = onPool.light ? { go: true } : poolLimitPlan(account.id, onPool.policy, addr);+ if ("refuse" in plan) {+ unhitRun();+ const over = plan.refuse;return refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) });}// The request as it runs there (no more outputs than the policy's cap per run): planned and priced as it is.@@ -233,12 +263,12 @@ export async function POST(request: Request) {// A workflow for the isolated worker (LatentSync 1.6, ThinkSound) on someone's computer: its tab reaches no second// ComfyUI yet. Said now, before anything is staged or queued.if (planned.route.provider === "comfyui" && workerFor(planned.route.endpoint) === "isolated" && onOwn(() => computerScope())) {- if (account) unhit(`run:${account.id}`);+ unhitRun();return refuse(422, ISOLATED_ON_COMPUTER, { code: "isolated-on-computer" });}// The same on an account's own GPU at a web address: one ComfyUI, where the second one these graphs need isn't.if (account && planned.route.provider === "comfyui" && workerFor(planned.route.endpoint) === "isolated") {- unhit(`run:${account.id}`);+ unhitRun();return refuse(422, ISOLATED_ON_GPU, { code: "isolated-on-gpu" });}// An account's 3D model (Image to 3D, Photo to 3D, Make it 3D) runs on its own GPU or key, and is finished on@@ -247,7 +277,7 @@ export async function POST(request: Request) {const skip = (body as { gpuCheck?: unknown } | null)?.gpuCheck === "skip";const gate = await gateGeneration(gpuTargetFor(request, "read"), { request: req, route: planned.route, op: planned.op, modelId: planned.model.id, gpu: planned.gpu, h3: planned.h3, skip, actor: account?.id ?? "owner" });if (!gate.ok) {- if (account) unhit(`run:${account.id}`);+ unhitRun();return Response.json({ error: gate.message, code: "gpu-setup", ref: gate.ref, plan: gate.plan }, { status: 409, headers: { [GPU_SETUP_HEADER]: "1" } });}gpuWarning = gate.warning;@@ -258,34 +288,52 @@ export async function POST(request: Request) {// ComfyUI: say which to download before anything is queued.const fix = await onOwn(() => accountLoraFix(req));if (fix) {- unhit(`run:${account.id}`);+ unhitRun();return refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix });}}// The moderation service's check (none set: nothing checked), before anything is set aside: a refusal costs nothing.// Then, on this install's GPUs, the billing service sets the run's price aside (none set: the run is free).let stamp: RunStamp | null = null;+ // A run on this install's GPUs that waits for a service (it didn't answer, or said runs are paused, or gave a later+ // start): why, and what its reserve then sends; `unchecked`: the moderation service didn't answer (it is checked first).+ let wait: ReserveWait | undefined;+ let facts: ReserveFacts | undefined;+ let unchecked = false;if (account) {const mod = await moderateRun(account, req, onPool?.planned ?? null, onPool ? "pool" : "own");- if (!mod.ok) return refusedBy(mod.refusal);+ if (!mod.ok) {+ // While runs on this install's GPUs wait for the services (the policy says so), one the moderation service didn't+ // answer for is taken, and checked before it enters the line.+ if (onPool && !onPool.light && holdsOn(onPool.policy) && mod.refusal.body.code === "paused") unchecked = true;+ else return refusedBy(mod.refusal);+ }+ const checkOutputs = mod.ok && mod.checkOutputs;if (onPool?.light) {// Light work only (joins, trims): free, so nothing is set aside, and it counts against none of the policy's limits.- stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }), ...policyWait(onPool.policy) };+ stamp = { place: "pool", light: true, ...(checkOutputs && { checkOutputs: true }), ...policyWait(onPool.policy) };} else if (onPool) {- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, poolTry === null ? null : pressTry(account.id, pressId!, poolTry), onPool.policy);+ const limit = "hold" in plan ? { reason: plan.hold, ...(plan.startAt !== undefined && { startAt: plan.startAt }) } : undefined;+ const press = poolTry === null ? null : pressTry(account.id, pressId!, poolTry);+ const held = await reservePool(account, req, onPool.planned, shown, checkOutputs, onPool.steps, press, onPool.policy, { heldMs: heldGuessMs(limit) });if (!held.ok) return refusedBy(held.refusal);stamp = held.stamp;- } else if (mod.checkOutputs) stamp = { checkOutputs: true };+ wait = held.wait;+ facts = held.facts;+ } else if (checkOutputs) stamp = { checkOutputs: true };}const make = () => createGenerations(req);const inScope = <T,>(fn: () => T): T => (account && onPool ? runOnPool(account.id, () => withRunStamp(stamp ?? { place: "pool" }, fn)) : stamp ? onOwn(() => withRunStamp(stamp, fn)) : onOwn(fn));let items: ReturnType<typeof createGenerations>;+ // Why the run waits to enter the line, when it does (its tile says "In line" at once all the same).+ let heldFor: HoldReason | undefined;try {if (account) {// Counted again as the run is made, in one transaction (admitRun): requests that arrived together all passed the// first counts while the checks above waited, and a second server may be making runs too. The run's rows are made// and checked step by step (every step of a chain on this install's GPUs is one the policy allows); nothing is- // sent until they are kept.+ // sent until they are kept. A run the limits or a service hold is kept waiting to enter the line instead of being+ // sent (pool-holds.ts); the release loop sends it when its reason clears.const pool = onPool;const admitted = inScope(() => {const r = admitRun(@@ -299,19 +347,21 @@ export async function POST(request: Request) {// of its own, never a run against this one. Noted in the same transaction, before any send can look....(poolTry !== null && stamp?.hold && { refused: () => void endTry(account.id, pressId!, poolTry) }),},- () => {+ (admit) => {const run = captureRun(make);const problem = pool && stepsProblem(pool.policy, stepsOf(run.ids));if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });+ const shape = pool && !pool.light ? holdShape({ limit: admit.hold, wait, unchecked }) : null;+ if (shape) holdRun({ accountId: account.id, rows: run.rows, pressedAt, ...shape, ...(facts && { facts }) });if (poolTry !== null) notePressRun(account.id, pressId!, poolTry, run.value.map((g) => g.id), stamp?.hold ?? null);- return run;+ return { ...run, held: shape?.reason };},);- if (r.ok) r.value.start();+ if (r.ok && !r.value.held) r.value.start();return r;});if (!admitted.ok && "prior" in admitted) {- unhit(`run:${account.id}`);+ unhitRun();const prior = admitted.prior;// The service gives one try of a press one hold; a different one (a service that made a second) goes back, and// so does the hold of a try another send ended.@@ -319,12 +369,15 @@ export async function POST(request: Request) {return prior === "ended" ? refuse(503, BILLING_WAIT.run, { code: "paused" }, { [BILLING_HEADER]: "paused" }) : madeAlready(prior.ids);}if (!admitted.ok) {- unhit(`run:${account.id}`);+ unhitRun();if (stamp?.hold) queueRelease(stamp.hold);const a = limitAnswer(admitted.refusal);return refuse(a.status, a.body.error, a.body, a.headers);}items = admitted.value.value;+ heldFor = admitted.value.held;+ // Its tiles as they read now: "In line", with why it waits (its rows were read before their holds were kept).+ if (heldFor) items = items.map((g) => ({ ...(getGeneration(g.id) ?? g), ...(g.notes && { notes: g.notes }) }));} else items = make();} catch (e) {// Nothing was made: what was set aside goes back.@@ -335,12 +388,12 @@ export async function POST(request: Request) {if (viewer.kind === "owner" && token && getSetting("comfyWhere") === "computer" && items.some((g) => g.provider === "comfyui")) notes.push(RUNS_ON_COMPUTER_NOTE);// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).const all = [...new Set([...notes, ...items.flatMap((g) => g.notes ?? [])])];- return Response.json({ items, ...(all.length && { notes: all }), ...(gpuWarning && { gpuWarning }) }, { status: 201 });+ return Response.json({ items, ...(all.length && { notes: all }), ...(gpuWarning && { gpuWarning }), ...(heldFor && { held: { reason: heldFor } }) }, { status: 201 });} catch (e) {const refusal = e instanceof AccountRunError ? e.refusal : undefined;// A price check of a paid model the account has no key for says so, without opening "Add your key".if (refusal && !preview) return refused(refusal);- if (account && !preview) unhit(`run:${account.id}`);+ if (account && !preview) unhitRun();// Nothing connected runs this, and ComfyUI or a key could (placeholder results off): the owner's own browser// (never a script's token) opens the connect card for it, with the ways that would run it, and the run starts once// one is connected (src/server/connect-refusal.ts).diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 719f730e..f6f55d83 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -893,14 +893,17 @@ export function Composer({ docked }: { docked: boolean }) {const onRunOnSite = () => submitRef.current(undefined, undefined, "pool");// A long wait on this studio's GPUs (past the policy's offer time, or until a GPU is free): an account with its own GPU,// or a key that runs this item's cloud version (at its price, never without one), may run this run there now, once.- // Its pick stays as it was, and the run is taken in line all the same when it doesn't.+ // Its pick stays as it was, and the run is taken in line all the same when it doesn't. While the day's GPU time is used+ // up, or runs there are paused, an account with nothing of its own gets the quiet way to connect its own GPU.const waitOffer =viewerInfo?.kind === "account" && poolState && !poolState.refused && poolState.long? viewerInfo.gpu.connected? { label: "Run it now on your GPU", run: () => submitRef.current(undefined, undefined, "own") }: keyTwin && keyPrice? { label: `Run it now with your ${CLOUD_KEY[keyTwin.provider].label} key · ${keyPrice}`, run: () => submitRef.current(undefined, withKeyAction(keyTwin.provider, keyTwin.modelId, keyTwin.op, keyPrice)) }- : undefined+ : poolState.held === "today" || poolState.held === "service"+ ? { label: "Or connect your own GPU", run: () => void pressSetup({ need: "gpu" }) }+ : undefined: undefined;// A choice before Run for an item this studio's GPUs can't run, for an account whose key runs its cloud version (and no// GPU): run it once on the key, at its price, or connect a GPU. Nothing runs until one is pressed.diff --git a/src/components/studio/pool-note.tsx b/src/components/studio/pool-note.tsxindex 51a4afa4..8ae3d800 100644--- a/src/components/studio/pool-note.tsx+++ b/src/components/studio/pool-note.tsx@@ -8,19 +8,21 @@ type PoolState = NonNullable<ReturnType<typeof poolRunState>>;/*** The line under a composer's toolbar for a run on this studio's GPUs: when it would be ready, before Run is pressed- * ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds"), with `offer` after a long wait (the account's- * own GPU or key for this run, once: "Run it now on your GPU"); or, when the price check refused it, the words (the+ * ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds", "Starts after your other runs", "Lots of+ * runs today · starts in about 7 h"), with `offer` after a long wait (the account's own GPU or key for this run, once:+ * "Run it now on your GPU"); or, when the price check refused it, the words (the* toolbar's price slot has no room for them on a phone), with the link or offer the answer carries.*/export function PoolNote({ state, offer, className }: { state: PoolState; offer?: { label: string; run: () => void }; className?: string }) {const interest = useInterest();const href = safeLink(state.action?.url);if (!state.refused) {- if (!state.wait) return null;+ const words = state.note ?? (state.wait ? capitalFirst(state.wait) : null);+ if (!words) return null;const press = state.long ? offer : undefined;return (<p data-pool-note="wait" className={cn("flex flex-wrap items-center gap-x-2 px-2 text-[12px] text-muted-foreground tabular-nums", className)}>- <span>{capitalFirst(state.wait)}</span>+ <span>{words}</span>{press && (<buttontype="button"diff --git a/src/components/workers-admin.tsx b/src/components/workers-admin.tsxindex 2cc25502..d423724d 100644--- a/src/components/workers-admin.tsx+++ b/src/components/workers-admin.tsx@@ -49,6 +49,26 @@ interface Lane {workflows: number;}+/** Runs made but waiting to enter the line (hosted runs), by why they wait, and when the oldest was pressed. */+interface HeldCounts {+ mine: number;+ today: number;+ service: number;+ hour: number;+ list: number;+ credits: number;+ oldestAt: number | null;+}++/** "Waiting to enter the line: 3 (oldest 12 min)", or null when none waits. */+export function heldLine(h: HeldCounts | undefined, now: number): string | null {+ if (!h) return null;+ const n = h.mine + h.today + h.service + h.hour + h.list + h.credits;+ if (!n) return null;+ const min = h.oldestAt === null ? null : Math.max(0, Math.round((now - h.oldestAt) / 60_000));+ return `Waiting to enter the line: ${n}${min === null ? "" : ` (oldest ${min} min)`}`;+}+async function call<T>(method: string, url: string, body?: unknown): Promise<T> {const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });const j = (await res.json().catch(() => ({}))) as T & { error?: string };@@ -250,7 +270,7 @@ function WorkerCard({ w, lanes, onToken }: { w: WorkerView; lanes: Lane[]; onTokexport function useWorkers(enabled: boolean) {return useQuery({queryKey: ["admin", "workers"],- queryFn: () => call<{ workers: WorkerView[]; lanes: Lane[] }>("GET", "/api/admin/workers"),+ queryFn: () => call<{ workers: WorkerView[]; lanes: Lane[]; held?: HeldCounts }>("GET", "/api/admin/workers"),enabled,refetchInterval: 10_000,});@@ -261,6 +281,7 @@ export function WorkersAdmin() {const hydrated = useHydrated();const owner = useViewer().data?.owner;const q = useWorkers(!!owner);+ const now = useNow(30_000);const qc = useQueryClient();const [name, setName] = useState("");const [token, setToken] = useState<string | null>(null);@@ -283,6 +304,7 @@ export function WorkersAdmin() {if (!hydrated) return null;if (!owner) return <p className="text-[14px] text-muted-foreground">Only the studio's owner manages workers.</p>;const workers = q.data?.workers ?? [];+ const held = heldLine(q.data?.held, now);return (<div className="space-y-6"><div className="space-y-2">@@ -310,6 +332,11 @@ export function WorkersAdmin() {</Button></form>{q.isError && <p className="text-[13px] text-destructive">{(q.error as Error).message}</p>}+ {held && (+ <p data-held-line className="text-[13px] text-muted-foreground tabular-nums">+ {held}+ </p>+ )}{workers.length ? (<ul className="space-y-3">{workers.map((w) => (diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex eafc5832..e5cd1efb 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -26,6 +26,9 @@ export async function register() {// Where a deleted account's runs went (its pick of a place, hosted runs) goes with it.const { clearRunOn } = await import("./server/run-on");onAccountDeleted(clearRunOn);+ // Its runs waiting to enter the line on this install's GPUs (hosted runs) go with it too.+ const { clearHolds } = await import("./server/pool-holds");+ onAccountDeleted(clearHolds);// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.const { ensureFacelessRunner } = await import("./server/faceless");ensureFacelessRunner();diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 132ad502..6a1301eb 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1494,9 +1494,18 @@ export interface Generation {/*** A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). `unknown`:* no GPU that could run it can take it now, so it starts when one is free; `returnAt` (epoch ms): when the first of- * them is due back, when one says.- */- queue?: { place: number; etaSeconds: number | null; unknown?: true; returnAt?: number };+ * them is due back, when one says. `held`: made, and waiting to enter the line (behind the account's other runs, until+ * `startAt`, for a service; `paused`: runs there are paused), still "In line" on its tile (src/lib/pool-line.ts).+ */+ queue?: {+ place: number;+ etaSeconds: number | null;+ unknown?: true;+ returnAt?: number;+ held?: "mine" | "today" | "service" | "hour" | "list" | "credits";+ startAt?: number;+ paused?: true;+ };/*** A run working on this install's GPUs: the address of its latest preview picture (a JPEG, for the run's own account* only), while there is one.diff --git a/src/lib/guest-draft.ts b/src/lib/guest-draft.tsindex 28722d9c..7e7b4c23 100644--- a/src/lib/guest-draft.ts+++ b/src/lib/guest-draft.ts@@ -198,7 +198,9 @@ export function restoredPrompt(link: string, saved: string, pressed: boolean): s* it, and the person is asked to add it again;* - wait: the draft, its files or the price check haven't settled;* - ask: the draft was edited after Run was pressed (`same` false): it waits for a click on what is there now;- * - start: the price is the one the guest saw;+ * - start: the price is the one the guest saw, also for a run that will wait to enter the line (behind the account's+ * other runs, until the day's GPU time renews: the server takes it all the same); or the price can't be known now+ * (the billing service doesn't answer: the run waits for it, and is priced against the price the guest saw);* - note: a new price, shown, and Run waits for a click;* - none: something is missing (the blocker says what), it would run elsewhere, it is refused now, or no price was shown* to compare.@@ -217,5 +219,7 @@ export function pendingStep(o: {if (o.blocked || !o.pool) return "none";if (!o.same) return o.quote?.allowed ? "ask" : "none";if (priceUnchanged(o.shown, o.quote)) return "start";+ // Allowed with no price said: the service doesn't answer now (the run is taken and waits for it).+ if (o.shown && o.quote?.allowed && !o.quote.text) return "start";return o.shown && o.quote?.allowed && o.quote.text ? "note" : "none";}diff --git a/src/lib/hosted.ts b/src/lib/hosted.tsindex e365c4f3..d53daf9c 100644--- a/src/lib/hosted.ts+++ b/src/lib/hosted.ts@@ -4,7 +4,7 @@ import { useEffect, useState } from "react";import { useMutation, useQuery, type QueryClient } from "@tanstack/react-query";import { toast } from "sonner";import type { GenerationRequest } from "./catalog/types";-import { lineWords, waitWords } from "./pool-line";+import { lineWords, noteWords, waitWords, type HeldReason } from "./pool-line";import type { OwnSetup } from "./own-setup";/**@@ -98,7 +98,9 @@ export function useSettled<T>(value: T, ms = 300): T {* Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown).* The run is taken whatever the line. `unknown`: no GPU that could run it can take it now, so it starts when one is free* (`returnAt`: when the first is due back, when one says); `light`: light work, ready in seconds; `long`: a wait long- * enough that an account with its own GPU or key is offered it for this run, once.+ * enough that an account with its own GPU or key is offered it for this run, once. `held`: a run pressed now is taken and+ * waits to enter the line (behind the account's other runs, until `startAt`, or while runs there are paused, with the+ * service's words in `note`).*/export interface HostedLine {place: number;@@ -107,6 +109,10 @@ export interface HostedLine {returnAt?: number;light?: true;long?: true;+ held?: HeldReason;+ startAt?: number;+ paused?: true;+ note?: string;}/** The price check's answer for a run on this studio's GPUs: the quote, and where the run would stand in line. */@@ -169,16 +175,38 @@ export function refreshPriceChecks(qc: QueryClient): void {* - otherwise the price (`text`: the service's words, empty when there is none) and, under it, when the run would be* ready (`wait`, inside a sentence: "ready in about 2 min", "starts when a GPU is free", "ready in seconds"; none when* nothing is known), and whether the wait is long (`long`: an account's own GPU or key may be offered for this run).+ * `note`: the line under the toolbar as a sentence of its own ("Starts after your other runs", "Lots of runs today ·+ * starts in about 7 h"); `held`: a run pressed now waits to enter the line, and why.* Null while there is no answer yet.*/-export function poolRunState(- check: HostedCheck | null | undefined,-): { refused: boolean; text: string; sub?: string; wait?: string; long?: boolean; action?: BillingAction; offer?: BillingOffer; setup?: OwnSetup } | null {+export function poolRunState(check: HostedCheck | null | undefined): {+ refused: boolean;+ text: string;+ sub?: string;+ wait?: string;+ note?: string;+ held?: HeldReason;+ long?: boolean;+ action?: BillingAction;+ offer?: BillingOffer;+ setup?: OwnSetup;+} | null {const q = check?.quote;if (!q) return null;if (!q.allowed) return { refused: true, text: q.text, ...(q.sub && { sub: q.sub }), ...(q.action && { action: q.action }), ...(q.offer && { offer: q.offer }), ...(q.ownSetup && { setup: q.ownSetup }) };- const wait = check?.line ? waitWords(check.line) : null;- return { refused: false, text: q.text, ...(q.sub && { sub: q.sub }), ...(wait && { wait }), ...(check?.line?.long && { long: true }) };+ const line = check?.line;+ const wait = line ? waitWords(line) : null;+ // A run pressed now would wait to enter the line: the line under the toolbar says why, as a sentence of its own.+ const note = line?.held ? noteWords(line) : null;+ return {+ refused: false,+ text: q.text,+ ...(q.sub && { sub: q.sub }),+ ...(wait && { wait }),+ ...(note && { note }),+ ...(line?.held && { held: line.held }),+ ...(line?.long && { long: true }),+ };}/**diff --git a/src/lib/pool-line.ts b/src/lib/pool-line.tsindex 52be624d..cad8bc66 100644--- a/src/lib/pool-line.ts+++ b/src/lib/pool-line.ts@@ -3,12 +3,21 @@* when the result would be ready ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds"); a run's tile* says where it is and when ("Next in line · ready in about 40 s", "In line · 3rd · starts when a GPU is free"). A run* shows only "In line", "Working", then its result: it is taken whatever the line, and never ends for a wait.+ *+ * A run can also be made and wait to enter the line (`held`): behind the account's other runs ("In line · after your+ * other runs"), until a time ("Lots of runs today · starts in about 7 h" before Run, "In line · starts in about 7 h" on+ * its tile), or while runs there are paused ("In line · starts when a GPU is free"). Its tile still says only "In line".*/+/** Why a run made now waits to enter the line (server: pool-holds.ts). */+export type HeldReason = "mine" | "today" | "service" | "hour" | "list" | "credits";+/*** A place in line (1: next) and the wait, about (`etaSeconds`, until the result; null: unknown). `unknown`: no GPU that* could run it can take it now, so it starts when one is free; `returnAt` (epoch ms): when the first of them is due- * back, when one says. `light`: light work only (joins, trims), which needs no GPU.+ * back, when one says. `light`: light work only (joins, trims), which needs no GPU. `held`: it waits to enter the line+ * (until `startAt`, epoch ms, when it has one; `paused`: runs there are paused, with the words to say before Run in+ * `note`).*/export interface LineFacts {place: number;@@ -16,6 +25,10 @@ export interface LineFacts {unknown?: boolean;returnAt?: number;light?: boolean;+ held?: HeldReason;+ startAt?: number;+ paused?: boolean;+ note?: string;}/** "about 40 s", "about 2 min", "about 3 h". */@@ -25,12 +38,20 @@ export function aboutWords(seconds: number): string {return `about ${Math.round(seconds / 3600)} h`;}+/** "starts in about 7 h": when a run waiting for a time starts. */+const startsWords = (startAt: number | undefined, now: number): string => `starts in ${aboutWords(Math.max(0, ((startAt ?? now) - now) / 1000))}`;+/*** When the run would be done, or start, in words inside a sentence: "ready in about 40 s", "ready in seconds", "starts- * when a GPU is free", "starts in about 3 h". Null when nothing is known (no estimate yet): nothing is guessed.+ * when a GPU is free", "starts in about 3 h", "starts after your other runs". Null when nothing is known (no estimate+ * yet): nothing is guessed.*/export function waitWords(q: LineFacts, now = Date.now()): string | null {if (q.light) return "ready in seconds";+ if (q.held === "mine") return "starts after your other runs";+ if (q.held === "list") return "starts as soon as you're in";+ if (q.held === "today" || q.held === "hour" || q.held === "credits") return startsWords(q.startAt, now);+ if (q.held === "service" && q.paused) return "starts when a GPU is free";if (q.unknown) {const ms = q.returnAt ? q.returnAt - now : 0;return ms > 0 ? `starts in ${aboutWords(ms / 1000)}` : "starts when a GPU is free";@@ -42,8 +63,34 @@ export function waitWords(q: LineFacts, now = Date.now()): string | null {/** The same words opening a line of their own ("Ready in about 2 min"). */export const capitalFirst = (s: string): string => (s ? s[0].toUpperCase() + s.slice(1) : s);-/** "In line · 3rd · ready in about 2 min": a run's place on this install's GPUs (1: next), and its wait (waitWords). */+/**+ * The line under the toolbar before Run, as a sentence of its own: "Ready in about 2 min", "Starts after your other+ * runs", "Lots of runs today · starts in about 7 h", "Starts in about 7 h, when your free generations renew", the+ * service's own words while runs there are paused. Null when nothing is known.+ */+export function noteWords(q: LineFacts, now = Date.now()): string | null {+ if (q.held === "service" && q.paused && q.note) return q.note;+ const wait = waitWords(q, now);+ if (!wait) return null;+ if (q.held === "today") return `Lots of runs today · ${wait}`;+ if (q.held === "credits") return `${capitalFirst(wait)}, when your free generations renew`;+ if (q.held === "list") return "You're on the waiting list. Your runs start as soon as you're in.";+ return capitalFirst(wait);+}++/**+ * "In line · 3rd · ready in about 2 min": a run's place on this install's GPUs (1: next), and its wait (waitWords). A run+ * waiting to enter the line: "In line · after your other runs" (with when it would be ready, when known), "In line ·+ * starts in about 7 h", "In line · starts when a GPU is free"; one waiting for the service, its place as if in line.+ */export function lineWords(q: LineFacts, now = Date.now()): string {+ if (q.held === "mine") {+ const s = q.etaSeconds;+ return s !== null && Number.isFinite(s) && s >= 0 ? `In line · after your other runs · ready in ${aboutWords(s)}` : "In line · after your other runs";+ }+ if (q.held === "list") return "In line · you're on the waiting list";+ if (q.held && q.held !== "service") return `In line · ${waitWords(q, now)}`;+ if (q.held === "service" && q.paused) return "In line · starts when a GPU is free";const n = Math.max(1, Math.floor(q.place));const ord = n % 100 >= 11 && n % 100 <= 13 ? "th" : (({ 1: "st", 2: "nd", 3: "rd" } as Record<number, string>)[n % 10] ?? "th");const head = n === 1 ? "Next in line" : `In line · ${n}${ord}`;diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsindex b3f8174f..9454eba0 100644--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@ -19,9 +19,10 @@ import { queueRelease } from "./billing-outbox";import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";import { gpuTargetFor } from "./gpu/target";import { runOnPool } from "./hosted";-import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, policyWait, poolMayTake, poolOutputsCap, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";+import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, policyWait, poolMayTake, poolOutputsCap, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ReserveFacts, type ReserveWait, type ToolPoolRun } from "./hosted-run";import { cancelGeneration, captureRun } from "./generations";-import { accountActiveRuns, AdmitRefused, admitRun, clientAddress, closeAdmission, forgetAdmission, openAdmission, poolLimitRefusal } from "./pool-limits";+import { AdmitRefused, admitRun, clientAddress, closeAdmission, forgetAdmission, openAdmission, ownActiveRuns, poolLimitPlan, type AdmitPlan } from "./pool-limits";+import { heldGuessMs, holdRun, holdShape } from "./pool-holds";import { hit, unhit } from "./rate";import { withRunStamp, type RunStamp } from "./run-stamp";import { once } from "./shorts-schemas";@@ -225,10 +226,11 @@ export const poolPress = (id: string | undefined): PoolPress => ({ poolOnly: idexport const pressIdOf = (request: Request): PoolPress => poolPress(requestIdOf({ requestId: request.headers.get(PRESS_HEADER) }));/**- * An account's runs going now (queued or running), counted as runs: a run's jobs and steps share a batch, and a run let- * in whose rows are still being made counts too (pool-limits.ts accountActiveRuns).+ * An account's runs going now (queued or running) that the studio's own limit of runs at once counts, counted as runs: a+ * run's jobs and steps share a batch, and a run let in whose rows are still being made counts too. With hosted runs on,+ * its runs on its own GPU or key, and its light work (pool-limits.ts ownActiveRuns).*/-export const activeAccountRuns = (accountId: string): number => accountActiveRuns(accountId);+export const activeAccountRuns = (accountId: string): number => ownActiveRuns(accountId);/** A request body over what an account's run may weigh (its files are uploaded first): 413 before it is read. */export function bodyTooBig(request: Request): Response | null {@@ -428,12 +430,30 @@ export async function runAccountTool<T>(request: Request, account: Account, askeif (run.poolOnly && !poolMayTake(account, run.place)) return no(ownGpuTool());if (!diskHasRoom()) return no(refuse(503, ACCOUNT_MESSAGES.diskLow));if (accountUsage(id).total >= accountTotalBytes(id)) return no(refuse(413, filesFullMessage(id)));- if (activeAccountRuns(id) >= ACCOUNT_LIMITS.activeRuns) return no(refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" }));- const rate = hit(`run:${id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);- if (!rate.ok) return no(refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) }));+ // The studio's own limits of runs at once and an hour: with hosted runs off, on every run, checked first, as always;+ // with them on, on a run on its own GPU or key only (one on this install's GPUs meets the policy's limits instead),+ // checked once its place is known.+ const ownFirst = !hostedRunsOn();+ let rated = false;+ const ownLimits = (): Response | null => {+ if (activeAccountRuns(id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });+ const rate = hit(`run:${id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);+ if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });+ rated = true;+ return null;+ };+ if (ownFirst) {+ const over = ownLimits();+ if (over) return no(over);+ }+ /** A refused run gives its count of the hour back. */+ const unrate = () => {+ if (rated) unhit(`run:${id}`);+ rated = false;+ };// From here a refusal gives the run back to the hour.const back = (response: Response): AccountToolResult<T> => {- unhit(`run:${id}`);+ unrate();return no(response);};// Only files it uploaded here, or its own results (no links, no data: URIs, nobody else's).@@ -463,9 +483,14 @@ export async function runAccountTool<T>(request: Request, account: Account, askeconst there = await placeOf(account, cutSteps, "pool");if (there.kind === "refuse") return back(refuse(there.refusal.status, there.refusal.body.error, there.refusal.body, there.refusal.headers));if (there.kind !== "pool") return back(ownGpuTool());- return startOnPool(request, account, { ...run, ...cut }, cutSteps, files, there, back);+ return startOnPool(request, account, { ...run, ...cut }, cutSteps, files, there, back, { limits: ownLimits, unrate });+ }+ if (place.kind === "pool") return startOnPool(request, account, run, steps, files, place, back, { limits: ownLimits, unrate });+ // On its own GPU or key, with hosted runs on: the studio's own limits, now that its place is known.+ if (!ownFirst) {+ const over = ownLimits();+ if (over) return no(over);}- if (place.kind === "pool") return startOnPool(request, account, run, steps, files, place, back);let gpuWarning: string | undefined;let kind: MediaKind = "video";let onKey = false;@@ -538,11 +563,23 @@ async function startOnPool<T>(files: string[],pool: Extract<ToolPlace, { kind: "pool" }>,back: (response: Response) => AccountToolResult<T>,+ own: { limits: () => Response | null; unrate: () => void },): Promise<AccountToolResult<T>> {const id = account.id;+ const pressedAt = Date.now();const addr = clientAddress(request);- const over = pool.light ? null : poolLimitRefusal(id, pool.policy, addr);- if (over) return back(refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) }));+ // Light work only (free, on this install's CPU) keeps the studio's own limits of runs at once and an hour.+ if (pool.light) {+ const over = own.limits();+ if (over) return back(over);+ }+ // The policy's limits: past one it can wait out, the run is taken and waits to enter the line (when the policy says so);+ // only a press past the cap on runs waiting is refused.+ const plan = pool.light ? null : poolLimitPlan(id, pool.policy, addr);+ if (plan && "refuse" in plan) {+ const over = plan.refuse;+ return back(refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) }));+ }const kind = outputKind(pool.main.planned.op, pool.main.planned.model);const mod = await moderateRun(account, checkedRequest(steps, files), null, "pool", { kind, place: "pool" });if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));@@ -550,12 +587,18 @@ async function startOnPool<T>(const claim = await claimToolPress();if (claim && "answer" in claim) return back(fromAnswer(claim.answer));let stamp: RunStamp;+ // Why the run waits for the billing service, when it does, and what its reserve then sends.+ let wait: ReserveWait | undefined;+ let facts: ReserveFacts | undefined;if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }), ...policyWait(pool.policy) };else {// One hold per try of a press of Run: every send of the try asks for it by the same request id.- const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null, pool.policy);+ const limit = plan && "hold" in plan ? { reason: plan.hold, ...(plan.startAt !== undefined && { startAt: plan.startAt }) } : undefined;+ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null, pool.policy, { heldMs: heldGuessMs(limit) });if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));stamp = held.stamp;+ wait = held.wait;+ facts = held.facts;}const release = () => {if (stamp.hold) queueRelease(stamp.hold);@@ -563,22 +606,25 @@ async function startOnPool<T>(/** Refused from here on: after its hold was made, when one was (it goes back). */const refused = (response: Response): AccountToolResult<T> => ({ ...back(response), ...(stamp.hold && { held: true }) });const notOffered = (error: string) => refuse(403, error, { code: "not-offered" }, { [BILLING_HEADER]: "not-offered" });- /** What the start made: its value, its rows (they keep coming while an awaiting start runs) and its open admission. */- type Made = { value: T | Promise<T>; ids: string[]; start: () => void; open: string | null };+ /**+ * What the start made: its capture (its value, and its rows, which keep coming while an awaiting start runs), its open+ * admission, and what the policy's limits decided (whether it waits to enter the line).+ */+ type Made = { cap: ReturnType<typeof captureRun<T | Promise<T>>>; open: string | null; admit: AdmitPlan };const now = Date.now();let admitted: { ok: true; value: Made } | { ok: false; refusal: { status: number; error: string; code: string; retryAfterS?: number } };try {admitted = runOnPool(id, () =>withRunStamp(stamp, () =>- admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr }, now }, (): Made => {- const made = captureRun(run.start);+ admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr }, now }, (admit): Made => {+ const cap = captureRun(run.start);// A tool that makes its rows as it goes (after an await) is checked once they are all made, below. Until then// it counts as a run going (and in line) for every later request, from this same locked step: requests sent// together can't all pass the limits while its rows aren't made yet.- if (isThenable(made.value)) return { ...made, open: openAdmission(id, !pool.light, now) };- const problem = madeRunProblem(pool, made.ids);+ if (isThenable(cap.value)) return { cap, open: openAdmission(id, !pool.light, now), admit };+ const problem = madeRunProblem(pool, cap.ids);if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });- return { ...made, open: null };+ return { cap, open: null, admit };}),),);@@ -592,17 +638,18 @@ async function startOnPool<T>(return refused(r.code === "not-offered" ? notOffered(r.error) : refuse(r.status, r.error, { code: r.code }, { "Retry-After": String(r.retryAfterS ?? 30) }));}const made = admitted.value;+ const ids = made.cap.ids;/*** Stop what was made (nothing of it was sent). Each stopped row's report closes the hold (billing-outbox.ts), so the* hold goes back by itself only when no row was made.*/const undo = () => {- for (const g of made.ids) void cancelGeneration(g);- if (!made.ids.length) release();+ for (const g of ids) void cancelGeneration(g);+ if (!ids.length) release();};let value: T;try {- value = await made.value;+ value = await made.cap.value;} catch (e) {undo();return refused(errorResponse(e));@@ -610,8 +657,8 @@ async function startOnPool<T>(// Its rows exist now and count for themselves (or none will).if (made.open) closeAdmission(made.open);}- if (isThenable(made.value)) {- const problem = madeRunProblem(pool, made.ids);+ if (isThenable(made.cap.value)) {+ const problem = madeRunProblem(pool, ids);if (problem) {undo();return refused(notOffered(problem));@@ -619,12 +666,16 @@ async function startOnPool<T>(}// A start that made nothing (a tool that kept its own error, say): nothing runs, so its hold goes back, and it is not// one of the hour's runs.- if (!made.ids.length) {+ if (!ids.length) {release();if (!pool.light) forgetAdmission(id, now);- unhit(`run:${id}`);+ own.unrate();return { ok: true, value };}- made.start();+ // Past a limit it can wait out, or while the billing service doesn't answer: its tiles show "In line" now, and it+ // enters the line when its reason clears (pool-holds.ts), nothing sent until then.+ const shape = pool.light ? null : holdShape({ limit: made.admit.hold, wait });+ if (shape) holdRun({ accountId: id, rows: made.cap.rows, pressedAt, ...shape, ...(facts && { facts }) });+ else made.cap.start();return { ok: true, value };}diff --git a/src/server/billing.ts b/src/server/billing.tsindex 7d858dcd..365530af 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -88,6 +88,11 @@ export interface Quote {sub?: string;code?: RefuseCode;etaS?: number | null;+ /**+ * Allowed, but the run waits until then (epoch ms) before it enters the line: the day's GPU time is used up, an hourly+ * limit, or free generations that renew then. Absent: it may start at once.+ */+ startAt?: number;action?: Action;offer?: Offer;}@@ -106,6 +111,10 @@ export interface Policy {* `giveUpS`: how long a run there may wait before it first starts (s; 0: as long as it takes). Present, it wins over* the reserve answer's `maxWaitMs`; absent, that answer (else FUOBE_POOL_WAIT_MIN) says. `offerAfterS`: after how* long a wait the line before Run offers an account its own GPU or key for that run, once (absent: POOL_OFFER_AFTER_S).+ *+ * `held`: how many runs may wait behind an account's runs at once (`activeRuns`) before its next press is turned down+ * (0: no cap). Present (0 or more), a press past a limit is taken and waits to enter the line (pool-holds.ts), and so+ * is a press while the billing service doesn't answer; absent, those presses are refused as before.*/limits: {activeRuns: number;@@ -119,6 +128,7 @@ export interface Policy {addressRunsPerHour?: number;giveUpS?: number;offerAfterS?: number;+ held?: number;};/*** Where a run goes when the account could run it on its own GPU and on this install's: "pool" for this install's, "own"@@ -155,6 +165,8 @@ export type ReserveAnswer =/** The run's class in the line: "paid" goes before "free" (absent: "free"). */class?: "paid" | "free";text: string;+ /** The hold is made, and the run waits until then (epoch ms) before it enters the line (absent: at once). */+ startAt?: number;}| { ok: false; code: RefuseCode | "price-changed"; text: string; quote?: Quote; action?: Action; offer?: Offer };@@ -220,6 +232,8 @@ declare global {var __fuobeBillingBadUrl: boolean | undefined;var __fuobeBillingPolicies: Map<string, PolicyEntry> | undefined;var __fuobeBillingBalances: Map<string, { at: number; balance: Balance }> | undefined;+ var __fuobeBillingAnsweredAt: number | undefined;+ var __fuobeBillingQuotes: Map<string, { at: number; quote: Quote }> | undefined;}/** Is a billing service set? */@@ -228,9 +242,18 @@ export const billingConfigured = (): boolean => target() !== null;function call<T>(method: "GET" | "POST", path: string, body: unknown, timeoutMs: number): Promise<T> {const t = target();if (!t) return Promise.reject(new HookDown(HOOK, "not configured"));- return hookCall<T>({ hook: HOOK, target: t, token: process.env.FUOBE_BILLING_TOKEN || undefined, method, path, body, timeoutMs });+ return hookCall<T>({ hook: HOOK, target: t, token: process.env.FUOBE_BILLING_TOKEN || undefined, method, path, body, timeoutMs }).then((v) => {+ globalThis.__fuobeBillingAnsweredAt = Date.now();+ return v;+ });}+/**+ * When the billing service last answered a call from this process (epoch ms; 0: not yet). Runs held while it didn't+ * answer (pool-holds.ts) are tried again at once after it does.+ */+export const serviceAnsweredAt = (): number => globalThis.__fuobeBillingAnsweredAt ?? 0;+/** Log a transport problem on the server only. */function logDown(what: string, e: unknown): void {console.warn(`[fuobe] billing ${what}: ${(e as Error).message}`);@@ -337,6 +360,20 @@ export function policyGiveUpMs(p: Pick<Policy, "limits"> | null | undefined): nureturn typeof s === "number" && Number.isFinite(s) && s >= 0 ? Math.round(s * 1000) : undefined;}+/**+ * Does the policy say runs past a limit wait to enter the line instead of being refused (`limits.held` present: the+ * service of a release that knows it)? Then a press while the billing service doesn't answer waits too (pool-holds.ts).+ */+export function holdsOn(p: Pick<Policy, "limits"> | null | undefined): boolean {+ const n = p?.limits?.held;+ return typeof n === "number" && Number.isFinite(n) && n >= 0;+}++/** How many runs may wait behind an account's runs at once before a press is turned down: `limits.held` (0: no cap). */+export function heldCap(p: Pick<Policy, "limits"> | null | undefined): number {+ return holdsOn(p) ? Math.floor(p!.limits.held!) : 0;+}+/** After how long a wait the line before Run offers an account its own GPU or key, as the policy says (s). */export function policyOfferAfterS(p: Pick<Policy, "limits"> | null | undefined): number {const s = p?.limits?.offerAfterS;@@ -356,17 +393,50 @@ export function cachedPolicy(accountId: string | null): Policy | null | undefine/** A free run's quote (no service set): Run keeps its own words. */export const FREE_QUOTE: Quote = { allowed: true, amount: 0, priceVersion: "", text: "" };+/** The quotes the service gave when it didn't answer (quoteDown). */+const downQuotes = new WeakSet<Quote>();++/** Is this quote the one quote() gives when the billing service didn't answer (not an answer of its own)? */+export const quoteDown = (q: Quote): boolean => downQuotes.has(q);++/** The key a quote is kept under: the viewer and the run's facts (the same draft asks with the same facts). */+const quoteKey = (account: AccountFacts | null, run: RunFacts) => `${account?.id ?? ""}\n${JSON.stringify(run)}`;+/** The quote for a run on this install's GPUs. No service: free. The service down: a refusal with `paused`. */export async function quote(account: AccountFacts | null, run: RunFacts, queue: QueueFacts | null): Promise<Quote> {if (!billingConfigured()) return FREE_QUOTE;try {- return await call<Quote>("POST", "/v1/quote", { account, run, queue }, BILLING_TIMEOUTS.quote);+ const q = await call<Quote>("POST", "/v1/quote", { account, run, queue }, BILLING_TIMEOUTS.quote);+ const kept = (globalThis.__fuobeBillingQuotes ??= new Map());+ if (q.allowed) {+ kept.set(quoteKey(account, run), { at: Date.now(), quote: q });+ if (kept.size > 5000) kept.delete(kept.keys().next().value!);+ }+ return q;} catch (e) {logDown("quote", e);- return { allowed: false, amount: 0, priceVersion: "", text: BILLING_WAIT.quote, code: "paused" };+ const down: Quote = { allowed: false, amount: 0, priceVersion: "", text: BILLING_WAIT.quote, code: "paused" };+ downQuotes.add(down);+ return down;}}+/**+ * The last price the service gave for this run (allowed), for up to POLICY_KEEP_MS after it gave it: what Run shows+ * while it doesn't answer, when runs then wait for it (holdsOn). Null: none known.+ */+export function lastQuote(account: AccountFacts | null, run: RunFacts, now = Date.now()): Quote | null {+ const hit = globalThis.__fuobeBillingQuotes?.get(quoteKey(account, run));+ if (!hit || now - hit.at >= POLICY_KEEP_MS) return null;+ const { startAt: _startAt, etaS: _etaS, ...q } = hit.quote;+ void _startAt;+ void _etaS;+ return q;+}++/** What Run shows while the service doesn't answer and no price is known: nothing, and Run stays on (the run waits). */+export const UNKNOWN_QUOTE: Quote = { allowed: true, amount: 0, priceVersion: "", text: "" };+/*** How a reserve the service doesn't answer is tried again (ms): after `firstMs`, then twice as long each time up to* `mostMs`, for up to `forMs` in all, the last try's own time included. A press of Run waits through a short outage or@@ -375,6 +445,12 @@ export async function quote(account: AccountFacts | null, run: RunFacts, queue:*/export const RESERVE_RETRY = { forMs: 40_000, firstMs: 500, mostMs: 8_000 };+/**+ * When runs wait for the billing service (holdsOn), how long a press of Run tries its reserve before the run is made and+ * waits for the service instead (ms): the page gets its answer at once, and the run reserves when the service is back.+ */+export const RESERVE_INLINE = { ms: 5_000 };+/*** Is a failed reserve worth trying again: no connection, no answer in time, the service's own trouble (5xx) or too many* calls at once (429)? Any other answer (a wrong token, a request it refuses) is the same on every try.@@ -397,9 +473,11 @@ export interface ReserveInput {/*** How long the run's hold must stay open once a worker first takes the run, so its report always comes before the* hold's deadline: `runMs`, every attempt of every job at its lane's run ceiling, and `pausedMs`, the time a started- * run may spend back in line. The service adds the run's wait limit (`maxWaitMs`) before the first start.+ * run may spend back in line. The service adds the run's wait limit (`maxWaitMs`) before the first start. `heldMs`:+ * how long the run is expected to wait before it enters the line at all (behind the account's other runs, or until a+ * `startAt`; pool-holds.ts).*/- timing?: { runMs: number; pausedMs: number };+ timing?: { runMs: number; pausedMs: number; heldMs?: number };}/**@@ -407,11 +485,13 @@ export interface ReserveInput {* again with the same request id (RESERVE_RETRY: the service makes one hold for it however often it hears it), then a* `paused` refusal in plain words. An answer that would be the same on every try (a 4xx) is that refusal at once.* `unsure` on a refusal: a try may have made a hold the app never heard of (the caller releases it by the request id).- * Never throws.+ * `down` on a refusal: the service gave no answer at all (not a `paused` of its own). `forMs`: how long to keep trying+ * (RESERVE_RETRY.forMs; 0: one try). Never throws.*/-export async function reserve(input: ReserveInput): Promise<(ReserveAnswer & { unsure?: boolean }) | null> {+export async function reserve(input: ReserveInput, o: { forMs?: number } = {}): Promise<(ReserveAnswer & { unsure?: boolean; down?: true }) | null> {if (!billingConfigured()) return null;const start = Date.now();+ const forMs = o.forMs ?? RESERVE_RETRY.forMs;let unsure = false;for (let attempt = 0; ; attempt++) {try {@@ -425,10 +505,10 @@ export async function reserve(input: ReserveInput): Promise<(ReserveAnswer & { u}const wait = Math.min(RESERVE_RETRY.mostMs, RESERVE_RETRY.firstMs * 2 ** Math.min(attempt, 16));// The next try must end (its answer or its timeout) inside the whole wait.- if (Date.now() - start + wait + BILLING_TIMEOUTS.reserve > RESERVE_RETRY.forMs) break;+ if (Date.now() - start + wait + BILLING_TIMEOUTS.reserve > forMs) break;await new Promise((r) => setTimeout(r, wait));}- return { ok: false, code: "paused", text: BILLING_WAIT.run, ...(unsure && { unsure: true }) };+ return { ok: false, code: "paused", text: BILLING_WAIT.run, down: true, ...(unsure && { unsure: true }) };}/** The HTTP status and header for a billing refusal (the generations route; docs/billing-hook.md). */@@ -499,5 +579,6 @@ export async function sendReport(kind: "settle" | "refund" | "release", payload:export function resetBillingCache(): void {globalThis.__fuobeBillingPolicies?.clear();globalThis.__fuobeBillingBalances?.clear();+ globalThis.__fuobeBillingQuotes?.clear();globalThis.__fuobeBillingBadUrl = undefined;}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 0a53f152..86b04a36 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -8,6 +8,7 @@ import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";import { loadIndex } from "../gpu/index-file";import { hostedRunsOn } from "../hosted-switch";+import { heldView } from "../pool-holds";import { catalogVersion } from "./catalog-version";import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, taskCold, type TaskRow } from "./tasks";import { queueSettings, runCeilingMs } from "../queue-settings";@@ -1024,9 +1025,10 @@ export function poolFacts(lane: string | null): ComputerFacts {/*** The line for a new run of this workflow, for a quote or a reserve (the billing service's QueueFacts): how many tasks the* workers that may run it would serve before it, about how long until it would be done, and how many such workers can- * take work now. (The account's own runs, QueueFacts.mine, are counted by run in hosted.ts.)+ * take work now. (The account's own runs, QueueFacts.mine, are counted by run in hosted.ts.) `rankAt`: the place it+ * would take (a run that waited to enter the line at its press time: pool-holds.ts), now by default.*/-export function lineFacts(accountId: string | null, asked: string | null, now = Date.now()) {+export function lineFacts(accountId: string | null, asked: string | null, now = Date.now(), rankAt = now) {// A workflow that picks its graph at run time (`…-{n}`) has no lane yet: the whole line counts.const workflowId = asked && !asked.includes("{") ? asked : null;const lane = workflowId ? poolLane(workflowId) : null;@@ -1035,7 +1037,7 @@ export function lineFacts(accountId: string | null, asked: string | null, now =// a job ticket for this studio's catalog, which only a worker built for it takes (its place and wait, and the workers// online, count those workers only).const version = catalogVersion();- const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify({ ...needs, ...(version && { catalogVersion: version }) }) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;+ const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify({ ...needs, ...(version && { catalogVersion: version }) }) : null, rank_at: rankAt, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;const p: LinePlace = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fitsSlot({ ...probe, created_at: 0 }, w, now, slotFor(probe, w)))).length;// With none of them on now: when the first is due back, when one says.@@ -1333,12 +1335,17 @@ export function patchWorker(id: string, p: WorkerPatch, now = Date.now()): { viereturn { view: workerView(fresh, now), ...(token && { token }) };}-/** The line for workers by lane: waiting, oldest, the estimate, and which workers have it warm. */+/**+ * The line for workers by lane: waiting, oldest, the estimate, and which workers have it warm. `held`: the runs made but+ * waiting to enter the line (pool-holds.ts), by why they wait, and when the oldest was pressed: counts only (no prompt,+ * no account).+ */export function queueView(now = Date.now()) {const index = loadIndex();const rows = db().prepare("SELECT lane, COUNT(*) AS n, MIN(created_at) AS oldest FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' GROUP BY lane").all() as { lane: string | null; n: number; oldest: number }[];const workers = db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[];return {+ held: heldView(),lanes: rows.map((r) => {const last = db().prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND lane IS ? ORDER BY rank_at DESC LIMIT 1").get(r.lane) as TaskRow | undefined;return {diff --git a/src/server/db.ts b/src/server/db.tsindex a6ec8f85..831a1030 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1196,6 +1196,8 @@ function open(): Database.Database {db.exec(ACCOUNT_CANVAS_TABLES);// Where an account's runs go, as it picked (run-on.ts): read only while hosted runs are on, empty otherwise.db.exec(RUN_ON_TABLES);+ // Runs on this install's GPUs waiting to enter the line (pool-holds.ts): empty unless hosted runs are on.+ db.exec(POOL_HOLD_TABLES);// Its list reads this small summary, never every board's pages (a table made before it had the column gets it).if (!(db.prepare("PRAGMA table_info(account_canvases)").all() as { name: string }[]).some((c) => c.name === "summary_json")) {addColumn(db, "ALTER TABLE account_canvases ADD COLUMN summary_json TEXT");@@ -1241,6 +1243,34 @@ const RUN_ON_TABLES = `CREATE TABLE IF NOT EXISTS account_run_on (updated_at INTEGER NOT NULL);`;+/**+ * Runs on this install's GPUs that are made but wait to enter the line (pool-holds.ts): one row per row of the run, all+ * sharing `run_id`. Made empty on every install, and written only while hosted runs are on. Not a numbered migration.+ */+const POOL_HOLD_TABLES = `CREATE TABLE IF NOT EXISTS pool_holds (+ generation_id TEXT PRIMARY KEY,+ run_id TEXT NOT NULL,+ account_id TEXT NOT NULL,+ reason TEXT NOT NULL CHECK (reason IN ('mine', 'today', 'service', 'hour', 'list', 'credits')),+ pressed_at INTEGER NOT NULL,+ start_at INTEGER,+ rank_rule TEXT NOT NULL CHECK (rank_rule IN ('press', 'release')),+ reserved INTEGER NOT NULL DEFAULT 1,+ checked INTEGER NOT NULL DEFAULT 1,+ paused INTEGER NOT NULL DEFAULT 0,+ counted INTEGER NOT NULL DEFAULT 0,+ request_id TEXT,+ facts_json TEXT,+ job INTEGER,+ tries INTEGER NOT NULL DEFAULT 0,+ tried_at INTEGER,+ next_at INTEGER,+ holder TEXT,+ lease_until INTEGER+ );+ CREATE INDEX IF NOT EXISTS pool_holds_account ON pool_holds(account_id, pressed_at);+ CREATE INDEX IF NOT EXISTS pool_holds_run ON pool_holds(run_id);`;+/*** The runs let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they* exist (pool-limits.ts openAdmission).diff --git a/src/server/generations.ts b/src/server/generations.tsindex 65a87356..f002415d 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -124,14 +124,15 @@ import { convertMask, decodePng, encodePng } from "./png";import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";import { accountSend } from "./account-send";-import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";-import { FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";-import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";+import { stamped, stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";+import { anyHeld, dropHold, holdRun, NOT_HELD } from "./pool-holds";+import { ACTIVE_STATES, FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";+import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";import { hostedRunsOn } from "./hosted-switch";import { catalogVersion } from "./computer/catalog-version";import { gettingReady, poolLane, queueOfGeneration, type LinePlace } from "./computer/pool";import { noteCatalogProcess, processStart } from "./computer/ticket-refresh";-import { runPreviewAt } from "./computer/tasks";+import { endTask, runPreviewAt } from "./computer/tasks";import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";import { inDemoScope, outsideDemo } from "./demo-scope";@@ -355,7 +356,8 @@ const PLAIN_POOL_ERRORS = (() => {/** A pool row's place in line, as the Generation field (none once it has started). */function poolQueue(id: string): { queue: LinePlace } | Record<string, never> {- const q = placeInLine(id);+ // A run made but waiting to enter the line (pool-holds.ts): why, and where it stands as its tile says it.+ const q = heldLine(id) ?? placeInLine(id);return q ? { queue: q } : {};}@@ -1309,8 +1311,10 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =capture?.ids.push(id);if (!waits) {const start = () => void submit(id, route, providerId, plan, req, i);- if (capture) capture.submits.push(start);- else start();+ if (capture) {+ capture.submits.push(start);+ capture.jobs.set(id, i);+ } else start();}}ensureRunner();@@ -1320,6 +1324,8 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =interface RunCapture {ids: string[];submits: (() => void)[];+ /** The rows whose submit is held, by id: their job index (a later step, which waits for its earlier steps, has none). */+ jobs: Map<string, number>;}declare global {@@ -1331,12 +1337,21 @@ const captureStore = () => (globalThis.__fuobeRunCapture ??= new AsyncLocalStora/*** Run `fn` (createGenerations, and every step its chains queue) with the rows it makes noted and their submits held:* `ids` are the rows, in the order they were made, and `start()` sends the held submits. Lets a caller make a run's rows- * inside a transaction and send nothing until it commits.+ * inside a transaction and send nothing until it commits. `rows`: each row with its job index when `start()` would send+ * it (null: a later step, sent once its earlier steps are done), for a run that waits to enter the line instead+ * (pool-holds.ts): its rows are sent later from what is stored (sendHeld). (An awaiting `fn` adds rows as it goes.)*/-export function captureRun<T>(fn: () => T): { value: T; ids: string[]; start: () => void } {- const cap: RunCapture = { ids: [], submits: [] };+export function captureRun<T>(fn: () => T): { value: T; ids: string[]; readonly rows: { id: string; job: number | null }[]; start: () => void } {+ const cap: RunCapture = { ids: [], submits: [], jobs: new Map() };const value = captureStore().run(cap, fn);- return { value, ids: cap.ids, start: () => cap.submits.splice(0).forEach((s) => s()) };+ return {+ value,+ ids: cap.ids,+ get rows() {+ return cap.ids.map((id) => ({ id, job: cap.jobs.get(id) ?? null }));+ },+ start: () => cap.submits.splice(0).forEach((s) => s()),+ };}/** One row a run would make: its model, operation, provider, kind and app, and the earlier steps it waits for. */@@ -2025,7 +2040,7 @@ const poolOf = (r: Pick<Row, "request_json">): boolean => {}};-function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {+function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number, rankAt?: number): Promise<void> {if (!req.account) return submitNow(id, route, providerId, plan, req, index);// On this install's GPUs (hosted runs): as the account, on this install's ComfyUI server only.if (req.place === "pool") {@@ -2035,7 +2050,9 @@ function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: RethandOverEnds(id);return Promise.resolve();}- return runOnPool(req.account, () => withRunStamp(stampOf(req), () => submitNow(id, route, providerId, plan, req, index)));+ // (`rankAt`: a run that waited to enter the line takes its place at its press: pool-holds.ts.)+ const stamp = { ...stampOf(req), ...(rankAt !== undefined && { rankAt }) };+ return runOnPool(req.account, () => withRunStamp(stamp, () => submitNow(id, route, providerId, plan, req, index)));}const own = accountRun(req.account, providerId, "submit");if ("error" in own) {@@ -2785,23 +2802,103 @@ function startRunner(): void {/*** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. One another app- * process that still runs is sending (a deploy's overlap: an account's files waiting their turn to go) is left to it.+ * process that still runs is sending (a deploy's overlap: an account's files waiting their turn to go) is left to it, and+ * so is a run made to wait to enter the line (pool-holds.ts). With hosted runs on, a run on this install's GPUs that was+ * cut off between its row and its GPU task (a deploy, a crash) isn't failed: it waits to enter the line again at its+ * press-time place, and the release loop makes its GPU task (pool-release.ts). Every other row fails as before.*/function sweepInterrupted(): void {const now = Date.now();const rows = db().prepare(- `SELECT g.id FROM generations g WHERE g.status IN ('queued','running') AND g.external_id IS NULL AND g.depends_on IS NULL AND g.created_at < @before- AND NOT ${SENT_ELSEWHERE("g")}`,+ `SELECT g.id, g.batch_id, g.created_at, g.request_json FROM generations g WHERE g.status IN ('queued','running') AND g.external_id IS NULL AND g.depends_on IS NULL AND g.created_at < @before+ AND NOT ${SENT_ELSEWHERE("g")} AND ${NOT_HELD("g")}`,)- .all({ before: now - STALE_SUBMIT_MS, me: runnerToken(), quiet: now - QUIET_MS }) as Pick<Row, "id">[];+ .all({ before: now - STALE_SUBMIT_MS, me: runnerToken(), quiet: now - QUIET_MS }) as Pick<Row, "id" | "batch_id" | "created_at" | "request_json">[];const busy = submitting();for (const r of rows) {if (busy.has(r.id)) continue;+ if (hostedRunsOn() && holdCutOff(r)) continue;update(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null });}}+/**+ * A run on this install's GPUs cut off between its row and its GPU task: it waits to enter the line again, at its+ * press-time place (its row's time), as the job it was in its run (its seed's offset). Its rows counted against the+ * account's limits already, so it enters as soon as it can. False for any other row.+ */+function holdCutOff(r: Pick<Row, "id" | "batch_id" | "created_at" | "request_json">): boolean {+ let stored: GenerationRequest;+ try {+ stored = JSON.parse(r.request_json) as GenerationRequest;+ } catch {+ return false;+ }+ if (stored.place !== "pool" || !stored.account) return false;+ // Its job in its run: the rows of its batch made before it (each job's row is made a moment after the one before).+ const job = r.batch_id+ ? (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE batch_id = ? AND depends_on IS NULL AND created_at < ?").get(r.batch_id, r.created_at) as { n: number }).n+ : 0;+ // A GPU task made for it whose id never reached the row (cut off in between) stops: the row gets a new one.+ const orphans = db()+ .prepare(`SELECT id FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`)+ .all(r.id, ...ACTIVE_STATES) as { id: string }[];+ for (const t of orphans) endTask(t.id, "canceled");+ holdRun({ accountId: stored.account, rows: [{ id: r.id, job }], ...(r.batch_id && { runId: `batch:${r.batch_id}` }), reason: "service", rankRule: "press", pressedAt: r.created_at, reserved: true, counted: true });+ return true;+}++/**+ * Send a row of a run that waited to enter the line (pool-release.ts): planned again from its stored request, as its+ * run's place and stamp say, as job `job` of its run, taking its place at `rankAt` (its press) or now. False when it+ * doesn't wait to be sent any more (stopped meanwhile), or its plan can't be made (it fails in its words then).+ */+export function sendHeld(id: string, job: number, rankAt?: number): boolean {+ const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row | undefined;+ if (!r || r.status !== "queued" || r.external_id) return false;+ let stored: GenerationRequest;+ try {+ stored = JSON.parse(r.request_json) as GenerationRequest;+ } catch {+ return false;+ }+ const account = stored.account;+ if (!account || stored.place !== "pool") return false;+ let p: ReturnType<typeof prepare>;+ try {+ p = runOnPool(account, () => withRunStamp(stampOf(stored), () => prepare(stored)));+ } catch (e) {+ updateLive(id, { status: "failed", error: (e as Error).message, completed_at: Date.now(), message: null });+ return false;+ }+ submitting().add(id);+ void submit(id, p.route, p.providerId, p.plan, p.req, job, rankAt);+ return true;+}++/** End the rows of a run that waited to enter the line, in words (a service refused it once it answered). */+export function failWaiting(ids: string[], error: string): void {+ for (const id of ids) {+ const r = db().prepare("SELECT status, external_id FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id"> | undefined;+ if (r?.status === "queued" && !r.external_id) updateLive(id, { status: "failed", error, completed_at: Date.now(), message: null });+ }+}++/**+ * Add to the stamp of a run's rows (a run that waited for the billing service: its hold, once made; the moderation+ * service's ask to see its outputs). The rest of each row's stamp stays.+ */+export function restampRows(ids: string[], add: RunStamp): void {+ for (const id of ids) {+ const r = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "request_json"> | undefined;+ if (!r) continue;+ const stored = JSON.parse(r.request_json) as GenerationRequest;+ const next = withRunStamp({ ...stampOf(stored), ...add }, () => stamped(stored));+ update(id, { request_json: JSON.stringify(next) });+ }+}+async function pollGuarded(r: Row): Promise<void> {const polling = (globalThis.__fuobeRunner!.polling ??= new Set());if (polling.has(r.id)) return;@@ -2847,6 +2944,14 @@ async function tick(): Promise<void> {state.busy = true;try {sweepInterrupted();+ // Runs made but waiting to enter the line (hosted runs): those whose reason cleared enter it now (pool-release.ts).+ if (hostedRunsOn() && anyHeld()) {+ try {+ await (await import("./pool-release")).releaseHeldRuns();+ } catch (e) {+ console.warn(`[generations] runs waiting to enter the line: ${(e as Error).message}`);+ }+ }// The owner's jobs first, then the accounts' in turn. An account's ComfyUI may be slow to answer: its polls run on// their own, so they never hold up the owner's (pollGuarded never polls one row twice at once).const active = rowsToPoll();@@ -3720,6 +3825,8 @@ export async function cancelGeneration(id: string): Promise<void> {stopWorkerFinish(id);// Saved meanwhile (here, or by another app process while the provider was asked to stop): it stays as it is.if (!markCanceled(id)) return;+ // A run waiting to enter the line leaves it (pool-holds.ts).+ dropHold(id);// Steps waiting only to feed this one are dropped too (nothing was spent on them).dropUnused(depIds(r.depends_on));}diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 107249a5..0ab0f8f4 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -14,17 +14,24 @@ import {cachedPolicy,forgetBalance,FREE_QUOTE,+ holdsOn,lastPrefer,+ lastQuote,policy as billingPolicy,policyGiveUpMs,policyOfferAfterS,quote as billingQuote,+ quoteDown,refusalStatus,reserve,+ RESERVE_INLINE,+ UNKNOWN_QUOTE,type Policy,type Quote,type QueueFacts,type RefuseCode,+ type ReserveAnswer,+ type ReserveInput,type RunFacts,} from "./billing";import { getModel } from "@/lib/catalog";@@ -44,7 +51,8 @@ import { reserveRequestId, type Press } from "./run-requests";import type { RunStamp } from "./run-stamp";import { readRef } from "./storage";import { ACCOUNT_LIMITS } from "./account-files";-import { poolLimitRefusal } from "./pool-limits";+import { poolLimitPlan, type LimitPlan } from "./pool-limits";+import { startReason, type HoldReason } from "./pool-holds";import { runAsTenant } from "./tenant";import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";import { ADD_KEY_HEADER } from "@/lib/your-keys";@@ -585,6 +593,24 @@ export function policyWait(p: Pick<Policy, "limits"> | null | undefined): Pick<Rreturn ms === undefined ? {} : { waitMs: ms };}+/**+ * Why a run that reservePool let in waits to enter the line (pool-holds.ts): the billing service didn't answer, or said+ * runs here are paused (`service`: it reserves under `requestId` once it answers); or it answered with a time the run may+ * start (`today`, `hour`: its hold is made; `credits`: it reserves then).+ */+export type ReserveWait =+ | { reason: "service"; requestId: string; paused?: true }+ | { reason: "today" | "hour"; startAt: number }+ | { reason: "credits"; startAt: number; requestId: string };++/** What a reserve made later sends of the run (pool-release.ts): its facts, the price shown, its timing. */+export interface ReserveFacts {+ run: RunFacts;+ shown: { amount: number; priceVersion: string };+ timing: NonNullable<ReserveInput["timing"]>;+ workflowId: string | null;+}+/*** Set the run's price aside (no billing service: nothing to set aside; the run is free). Returns the stamp the run's* rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `press`: the press of@@ -594,6 +620,11 @@ export function policyWait(p: Pick<Policy, "limits"> | null | undefined): Pick<R** How long the run may wait before it first starts: the policy's `limits.giveUpS` when it says (0: as long as it takes),* which wins over the reserve answer's `maxWaitMs`; else that answer's; else the install's own (FUOBE_POOL_WAIT_MIN).+ *+ * When runs wait instead of being refused (billing.ts holdsOn), the reserve is tried for RESERVE_INLINE at most; a+ * service that doesn't answer, says runs are paused, or answers with a later start lets the run in all the same, and+ * `wait` says why it waits (the caller holds it; no hold is given back by request id: the release reserves under the+ * same one). `heldMs`: how long the run is expected to wait before it enters the line (sent with the reserve's timing).*/export async function reservePool(account: Account,@@ -604,24 +635,33 @@ export async function reservePool(steps?: RunFacts["steps"],press: Press | null = null,policy: Pick<Policy, "limits"> | null = null,-): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {+ o: { heldMs?: number } = {},+): Promise<{ ok: true; stamp: RunStamp; wait?: ReserveWait; facts?: ReserveFacts } | { ok: false; refusal: Refusal }> {const giveUp = policyGiveUpMs(policy);const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }), ...(giveUp !== undefined && { waitMs: giveUp }) };if (!billingConfigured()) return { ok: true, stamp: base };const kind = outputKind(planned.op, planned.model);const run: RunFacts = { ...runOnPool(account.id, () => runFacts(req, planned, kind)), ...(steps?.length && { steps }) };const requestId = press ? reserveRequestId(account.id, press.key, press.tries) : nanoid(16);- const a = await reserve({- requestId,- account: accountFacts(account),- run,- queue: queueFacts(account.id, planned.route.endpoint),- shown: shown ?? { amount: 0, priceVersion: "" },- // How long its hold must stay open once a worker first takes it: every attempt at its lanes' run ceilings, and the- // time it may spend back in line (the queue's settings).- timing: holdTiming(run.steps?.length ? run.steps : [{ lane: run.lane, jobs: run.jobs }], MAX_ATTEMPTS, attemptLimitMs),- });+ const waits = holdsOn(policy);+ // How long its hold must stay open once a worker first takes it: every attempt at its lanes' run ceilings, and the+ // time it may spend back in line (the queue's settings); and, for a run that waits to enter the line, about how long.+ const timing = {+ ...holdTiming(run.steps?.length ? run.steps : [{ lane: run.lane, jobs: run.jobs }], MAX_ATTEMPTS, attemptLimitMs),+ ...(o.heldMs && o.heldMs > 0 && { heldMs: Math.round(o.heldMs) }),+ };+ const facts: ReserveFacts = { run, shown: shown ?? { amount: 0, priceVersion: "" }, timing, workflowId: planned.route.endpoint ?? null };+ const queue = queueFacts(account.id, planned.route.endpoint);+ const a = await reserve({ requestId, account: accountFacts(account), run, queue, shown: facts.shown, timing }, waits ? { forMs: RESERVE_INLINE.ms } : {});if (!a) return { ok: true, stamp: base };+ if (!a.ok && waits) {+ // No answer, or runs here paused: the run is made and waits; it reserves under this same request id once the service+ // answers (so a hold an unanswered try made is the one it gets).+ if (a.code === "paused") return { ok: true, stamp: base, wait: { reason: "service", requestId, ...(!a.down && { paused: true as const }) }, facts };+ // No free generations left until they renew: it waits, and reserves then.+ const at = await renewalAt(a, account, run, queue);+ if (at !== null) return { ok: true, stamp: base, wait: { reason: "credits", startAt: at, requestId }, facts };+ }if (!a.ok) {if (a.unsure) {// A try may have made a hold the app never heard of: it goes back by its request id, and the press's next send is a@@ -635,20 +675,39 @@ export async function reservePool(return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };}forgetBalance(account.id);- // Its class and head start in the line come from the answer too (a paid run goes before every free one).+ // A later start (the day's GPU time used up, an hourly limit): the hold is made, and the run waits until then.+ const startAt = Number(a.startAt);+ const later = waits && Number.isFinite(startAt) && startAt > Date.now();+ return { ok: true, stamp: { ...base, ...heldStamp(a, giveUp) }, ...(later && { wait: { reason: startReason(startAt), startAt }, facts }) };+}++/**+ * When free generations that renew would pay for a run its reserve turned down for credit (`top-up`, with credits on):+ * the service's quote for the run says so, allowed with a later `startAt` (the refusal's own quote when it carries one).+ * Null for any other refusal, or when nothing renews in time (the refusal stands).+ */+export async function renewalAt(a: { code: string; quote?: Quote }, account: Account, run: RunFacts, queue: QueueFacts | null, now = Date.now()): Promise<number | null> {+ if (a.code !== "top-up") return null;+ const q = a.quote ?? (await billingQuote(accountFacts(account), run, queue));+ const at = Number(q.startAt);+ return q.allowed && Number.isFinite(at) && at > now ? at : null;+}++/**+ * The stamp fields a reserve's answer gives a run: its hold, the words for its charge, whether anything was set aside,+ * its wait limit (the policy's `giveUp` wins), and its class and head start in the line (a paid run goes before every+ * free one).+ */+export function heldStamp(a: Extract<ReserveAnswer, { ok: true }>, giveUp: number | undefined): RunStamp {const boost = Number(a.boostMs);return {- ok: true,- stamp: {- ...base,- hold: a.holdId,- ...(a.text && { charge: a.text }),- // Something was set aside (a free run's hold sets aside nothing): only then can a run that ends early say so.- ...(Number(a.amount) > 0 && { charged: true }),- ...(giveUp === undefined && a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),- ...(a.class === "paid" && { class: "paid" as const }),- ...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),- },+ hold: a.holdId,+ ...(a.text && { charge: a.text }),+ // Something was set aside (a free run's hold sets aside nothing): only then can a run that ends early say so.+ ...(Number(a.amount) > 0 && { charged: true }),+ ...(giveUp === undefined && a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),+ ...(a.class === "paid" && { class: "paid" as const }),+ ...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),};}@@ -661,6 +720,9 @@ export async function reservePool(* - `light`: light work only (joins, trims): ready in seconds, with no GPU.* - `long`: the wait passes the policy's `offerAfterS` (or is unknown): an account with its own GPU or key that runs it* may be offered it for this run, once.+ * - `held`: a run pressed now is taken and waits to enter the line (pool-holds.ts): "mine" after the account's runs going,+ * "today" or "hour" until `startAt`; "service" while runs here are paused (`paused`, with the service's words in+ * `note`).*/export interface PoolLine {place: number;@@ -669,6 +731,49 @@ export interface PoolLine {returnAt?: number;light?: true;long?: true;+ held?: HoldReason;+ startAt?: number;+ paused?: true;+ note?: string;+}++/**+ * The line a price check says, with why a run pressed now would wait to enter it: the service's later start (the day's+ * GPU time, an hourly limit: the offer of the account's own GPU or key shows at the daily cap), else the policy's+ * limits (behind the account's runs going, or an hourly limit).+ */+function withHeld(line: PoolLine, plan: LimitPlan | null, q: Quote, now = Date.now()): PoolLine {+ const at = Number(q.startAt);+ if (q.allowed && Number.isFinite(at) && at > now) {+ const reason = startReason(at);+ return { ...line, held: reason, startAt: at, ...(reason === "today" && { long: true as const }) };+ }+ if (plan && "hold" in plan) return { ...line, held: plan.hold, ...(plan.startAt !== undefined && { startAt: plan.startAt }) };+ return line;+}++/**+ * The quote a price check shows when the billing service doesn't answer or says runs here are paused, while runs wait for+ * it (holdsOn): the last price it gave for this run (else none), allowed, so Run stays on and a press is taken. `paused`:+ * the service's own words for the pause, shown as the line before Run.+ */+function quoteWhileQuiet(q: Quote, p: Policy | null, account: Account | null, facts: RunFacts): { q: Quote; paused?: string } {+ if (q.allowed || q.code !== "paused" || !holdsOn(p)) return { q };+ const known = lastQuote(account ? accountFacts(account) : null, facts) ?? UNKNOWN_QUOTE;+ return quoteDown(q) ? { q: known } : { q: known, paused: q.text };+}++/** A price check's quote and line, with what the policy's limits say of a run pressed now (refused only past the cap). */+function limitedCheck(q0: Quote, line: (q: Quote) => PoolLine, p: Policy | null, account: Account | null, facts: RunFacts, addr: (() => string | null) | null): { quote: Quote; line: PoolLine } {+ const quiet = quoteWhileQuiet(q0, p, account, facts);+ let q = quiet.q;+ let plan: LimitPlan | null = null;+ if (q.allowed && account && p) {+ plan = poolLimitPlan(account.id, p, addr);+ if ("refuse" in plan) q = { ...q, allowed: false, code: "limit", text: plan.refuse.error };+ }+ const shown = withHeld(line(q), plan, q);+ return { quote: q, line: quiet.paused !== undefined && q.allowed ? { ...shown, held: "service", paused: true, note: quiet.paused, long: true } : shown };}/** The line a price check says, from the queue's facts (and the service's own estimate, `q.etaS`, when it gave one). */@@ -750,13 +855,10 @@ export async function poolQuote(// Priced once for every step of a chain that uses this install's GPUs. Its facts are read as the viewer (an input's// size from its own files only: another's file reads as none, and says nothing of whether it exists).const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), ...(gate.steps && { steps: pricedSteps(gate.steps) }) };- let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);+ const q = await billingQuote(account ? accountFacts(account) : null, facts, queue);// The policy's limits on this account's runs here, as the run would meet them (pool-limits.ts): said before Run.- if (q.allowed && account && p) {- const over = poolLimitRefusal(account.id, p, o.addr ?? null);- if (over) q = { ...q, allowed: false, code: "limit", text: over.error };- }- return { planned, quote: q, line: poolLine(queue, { ...shape, q }) };+ const checked = limitedCheck(q, (quote) => poolLine(queue, { ...shape, q: quote }), p, account, facts, o.addr ?? null);+ return { planned, ...checked };}/**@@ -902,12 +1004,8 @@ export async function toolPoolQuote(const shape = { light: lightRun(gate.rows), waits: runWaits(planned, gate.rows), p };if (shape.light) return { quote: FREE_QUOTE, line: poolLine(queue, shape) };const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), steps: pricedSteps(gate.rows) };- let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);- if (q.allowed && account && p) {- const over = poolLimitRefusal(account.id, p, o.addr ?? null);- if (over) q = { ...q, allowed: false, code: "limit", text: over.error };- }- return { quote: q, line: poolLine(queue, { ...shape, q }) };+ const q = await billingQuote(account ? accountFacts(account) : null, facts, queue);+ return limitedCheck(q, (quote) => poolLine(queue, { ...shape, q: quote }), p, account, facts, o.addr ?? null);}/**diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 55d03492..a5a93d2f 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -10,6 +10,7 @@ import { lineFacts, poolLane, queueOfGeneration, workersAway, workersCanRun, typimport { db } from "./db";import { loadIndex } from "./gpu/index-file";import { hostedRunsOn } from "./hosted-switch";+import { holdOf, NOT_HELD, type HoldReason } from "./pool-holds";import { poolRunCounts } from "./pool-limits";import { getWorkflow, installComfyLocal, onInstallComfy, workerFor, workersTake } from "./providers/comfyui";import { getSetting, withCandidates } from "./settings";@@ -259,7 +260,7 @@ function myRuns(accountId: string | null): QueueFacts["mine"] {export function queueFacts(accountId: string | null, workflowId?: string | null): QueueFacts {if (poolOnWorkers()) return { ...lineFacts(accountId, workflowId ?? null), mine: myRuns(accountId) };const d = db();- const ahead = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING}`).get() as { n: number }).n;+ const ahead = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING} AND ${NOT_HELD("g")}`).get() as { n: number }).n;const typical = typicalRunMs();return {lane: POOL_LANE,@@ -271,15 +272,75 @@ export function queueFacts(accountId: string | null, workflowId?: string | null)};}+/**+ * A held row's line (pool-holds.ts): why it waits to enter it and, as its tile says it, where it stands. Waiting for the+ * service: its place and wait as if in line from its press (`paused`: the service said runs here are paused, so it+ * starts when a GPU is free). Behind the account's runs going: about when it would be ready, when known (when the first+ * of them is due done, plus a new run's wait now). Until a time: that time. Null when the row isn't held.+ */+export function heldLine(generationId: string, now = Date.now()): (LinePlace & { held: HoldReason; startAt?: number; paused?: true }) | null {+ const h = holdOf(generationId);+ if (!h) return null;+ const startAt = h.start_at !== null && h.start_at > now ? h.start_at : undefined;+ const base = { held: h.reason, ...(startAt !== undefined && { startAt }) };+ if (startAt !== undefined) return { place: 1, etaSeconds: null, ...base };+ const workflow = rowWorkflow(generationId);+ if (h.reason === "service") {+ if (h.paused) return { place: 1, etaSeconds: null, unknown: true, paused: true, ...base };+ if (!poolOnWorkers()) return { ...ownServerPlace(h.pressed_at), ...base };+ const f = lineFacts(h.account_id, workflow, now, h.pressed_at);+ return { place: f.ahead + 1, etaSeconds: f.etaS, ...(f.etaS === null && f.workersOnline === 0 && { unknown: true as const }), ...(f.nextOpenAt && { returnAt: f.nextOpenAt }), ...base };+ }+ if (h.reason === "mine") return { place: 1, etaSeconds: mineEta(h.account_id, workflow), ...base };+ return { place: 1, etaSeconds: null, ...base };+}++/** The workflow a row's job runs (its route on ComfyUI), or null. */+function rowWorkflow(generationId: string): string | null {+ const r = db().prepare("SELECT model_id, op FROM generations WHERE id = ?").get(generationId) as { model_id: string; op: string } | undefined;+ const routes = r ? (getModel(r.model_id)?.routes ?? []).filter((x) => x.provider === "comfyui") : [];+ const endpoint = (routes.find((x) => x.op === r?.op) ?? routes[0])?.endpoint;+ return endpoint && !endpoint.includes("{") ? endpoint : null;+}++/** On this install's own server: a run's place from its press among the rows waiting there. */+function ownServerPlace(pressedAt: number): LinePlace {+ const before = (db().prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING} AND ${NOT_HELD("g")} AND g.created_at < ?`).get(pressedAt) as { n: number }).n;+ const typical = typicalRunMs();+ return { place: before + 1, etaSeconds: typical === null ? null : Math.round(((before + 1) * typical) / 1000) };+}++/**+ * About when a run held behind the account's runs going would be ready: when the first of them still in line is due+ * done, plus a new run's wait now. Null when that isn't known (none of them waits in line with an estimate).+ */+function mineEta(accountId: string, workflow: string | null): number | null {+ const going = db()+ .prepare(`SELECT g.id FROM generations g WHERE ${POOL_ROWS} AND json_extract(g.request_json, '$.account') = ? AND ${NOT_HELD("g")}`)+ .all(accountId) as { id: string }[];+ let first: number | null = null;+ for (const g of going) {+ const q = placeInLine(g.id);+ if (q?.etaSeconds != null) first = first === null ? q.etaSeconds : Math.min(first, q.etaSeconds);+ }+ if (first === null) return null;+ const own = queueFacts(accountId, workflow).etaS;+ return own === null ? null : first + own;+}+/** A waiting row's place in line on this install's GPUs (1: next), and the wait, about. Null when it isn't waiting there. */export function placeInLine(generationId: string): LinePlace | null {// On the workers: its task's place in their line (back in line after an attempt, the same place).const task = queueOfGeneration(generationId);if (task || poolOnWorkers()) return task;const d = db();- const row = d.prepare(`SELECT g.created_at FROM generations g WHERE g.id = ? AND ${POOL_ROWS} AND ${WAITING}`).get(generationId) as { created_at: number } | undefined;+ const row = d.prepare(`SELECT g.created_at FROM generations g WHERE g.id = ? AND ${POOL_ROWS} AND ${WAITING} AND ${NOT_HELD("g")}`).get(generationId) as { created_at: number } | undefined;if (!row) return null;- const before = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING} AND (g.created_at < ? OR (g.created_at = ? AND g.id < ?))`).get(row.created_at, row.created_at, generationId) as { n: number }).n;+ const before = (+ d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING} AND ${NOT_HELD("g")} AND (g.created_at < ? OR (g.created_at = ? AND g.id < ?))`).get(row.created_at, row.created_at, generationId) as {+ n: number;+ }+ ).n;const typical = typicalRunMs();return { place: before + 1, etaSeconds: typical === null ? null : Math.round(((before + 1) * typical) / 1000) };}diff --git a/src/server/pool-holds.ts b/src/server/pool-holds.tsnew file mode 100644index 00000000..a8e7a417--- /dev/null+++ b/src/server/pool-holds.ts@@ -0,0 +1,308 @@+import "server-only";+import { queueRequestRelease } from "./billing-outbox";+import { db } from "./db";+import { endLease, leaseToken, MINE_NOW, takeLease } from "./run-leases";++/**+ * Runs on this install's GPUs that are made but wait to enter the line (hosted runs). One press of Run makes one run,+ * always: a press past a limit the run can wait out is taken, its tile shows at once ("In line"), and the run's GPU task+ * is made later, when the reason clears (pool-release.ts). Nothing here is read or written while hosted runs are off.+ *+ * Why a run waits (`reason`):+ * - `mine`: the account already has its runs at once in line (the policy's `activeRuns`); it enters when one of them ends.+ * - `today`: the day's GPU time is used up (the billing service's `startAt`); it enters at the renewal.+ * - `service`: the billing or moderation service didn't answer at the press (or said runs are paused), or the run was+ * cut off between its rows and its GPU task (a deploy, a crash); it reserves (and is checked) once the service answers.+ * - `hour`: an hourly limit; it enters at `start_at`.+ * - `list`: the waiting list (only when the service has one switched on).+ * - `credits`: no free generations left until they renew at `start_at` (credits on).+ *+ * Where it enters (`rank_rule`): a run held for the account's own reasons (mine, hour, list, credits) at the back of the+ * line when it is released, so ten fast presses never pass anyone; one held for the system's reasons (today, service)+ * at its press time.+ *+ * A hold row is kept for every row of the run (its jobs and the later steps of its chains), all sharing `run_id`, so the+ * runs' counts skip them and a deploy or a second app process sees them. `job` is the index of a row sent at release+ * (its seed's offset); a later step (null) waits for its earlier steps as it always does. `holder` and `lease_until`:+ * the app process releasing the run right now (pool-release.ts, run-leases.ts), so two processes never release one run+ * twice.+ */++export type HoldReason = "mine" | "today" | "service" | "hour" | "list" | "credits";+export type RankRule = "press" | "release";++export const HOLD_REASONS: readonly HoldReason[] = ["mine", "today", "service", "hour", "list", "credits"];++/** Where a released run enters the line, by why it waited. */+export const RANK_OF: Record<HoldReason, RankRule> = { mine: "release", hour: "release", list: "release", credits: "release", today: "press", service: "press" };++export interface HoldRow {+ generation_id: string;+ run_id: string;+ account_id: string;+ reason: HoldReason;+ pressed_at: number;+ start_at: number | null;+ rank_rule: RankRule;+ reserved: number;+ checked: number;+ paused: number;+ counted: number;+ request_id: string | null;+ facts_json: string | null;+ job: number | null;+ tries: number;+ tried_at: number | null;+ next_at: number | null;+ holder: string | null;+ lease_until: number | null;+}++/** A run to hold, as the press made it. */+export interface NewHold {+ accountId: string;+ /** Every row of the run, with the job index of each row sent at release (null: a later step). */+ rows: { id: string; job: number | null }[];+ /** The run its rows belong to (absent: its first row). */+ runId?: string;+ reason: HoldReason;+ pressedAt: number;+ /** Not before (epoch ms): `today`, `hour`, `credits`. */+ startAt?: number;+ /** Absent: the reason's own (RANK_OF). */+ rankRule?: RankRule;+ /** The billing service's hold is made (or none is needed). False: it reserves at release. */+ reserved: boolean;+ /** The moderation service's check passed (or none is set). False: it is checked at release. */+ checked?: boolean;+ /** The service said runs there are paused (maintenance): the tile says it starts when a GPU is free. */+ paused?: boolean;+ /**+ * The run counted against the account's limits already (one cut off between its rows and its GPU task): it enters when+ * its reason clears, never waiting for room among the account's runs.+ */+ counted?: boolean;+ /** The reserve's request id at release (the press's own, so the service makes one hold for it). */+ requestId?: string;+ /** What the reserve at release sends of the run (its facts, the price shown, its timing). */+ facts?: unknown;+}++/** Hold a run (call it inside the transaction that made its rows). Returns its run id (its first row's id). */+export function holdRun(h: NewHold, now = Date.now()): string {+ const runId = h.runId ?? h.rows[0]?.id;+ if (!runId) throw new Error("A run to hold has no rows");+ const insert = db().prepare(+ `INSERT INTO pool_holds (generation_id, run_id, account_id, reason, pressed_at, start_at, rank_rule, reserved, checked, paused, counted, request_id, facts_json, job, tries, tried_at, next_at)+ VALUES (@id, @run, @account, @reason, @pressed, @start, @rank, @reserved, @checked, @paused, @counted, @request, @facts, @job, 0, NULL, @next)+ ON CONFLICT(generation_id) DO NOTHING`,+ );+ const facts = h.facts === undefined ? null : JSON.stringify(h.facts);+ for (const r of h.rows) {+ insert.run({+ id: r.id,+ run: runId,+ account: h.accountId,+ reason: h.reason,+ pressed: h.pressedAt,+ start: h.startAt ?? null,+ rank: h.rankRule ?? RANK_OF[h.reason],+ reserved: h.reserved ? 1 : 0,+ checked: h.checked === false ? 0 : 1,+ paused: h.paused ? 1 : 0,+ counted: h.counted ? 1 : 0,+ request: h.requestId ?? null,+ facts,+ job: r.job,+ next: now,+ });+ }+ return runId;+}++/** SQL: row `alias` of generations waits to enter the line (it has a hold). */+export const HELD = (alias: string) => `EXISTS (SELECT 1 FROM pool_holds ph WHERE ph.generation_id = ${alias}.id)`;++/** SQL: row `alias` of generations is not held. */+export const NOT_HELD = (alias: string) => `NOT ${HELD(alias)}`;++/** The hold of one row, or undefined. */+export function holdOf(generationId: string): HoldRow | undefined {+ return db().prepare("SELECT * FROM pool_holds WHERE generation_id = ?").get(generationId) as HoldRow | undefined;+}++/** The rows of one held run. */+export function runHolds(runId: string): HoldRow[] {+ return db().prepare("SELECT * FROM pool_holds WHERE run_id = ? ORDER BY generation_id").all(runId) as HoldRow[];+}++/** An account's runs waiting to enter the line (one per press), all of them or for one reason. */+export function heldRuns(accountId: string, reason?: HoldReason): number {+ const r = db()+ .prepare(`SELECT COUNT(DISTINCT run_id) AS n FROM pool_holds WHERE account_id = ?${reason ? " AND reason = ?" : ""}`)+ .get(...(reason ? [accountId, reason] : [accountId])) as { n: number };+ return r.n;+}++/** Is anything held at all (the release loop looks only then)? */+export const anyHeld = (): boolean => !!db().prepare("SELECT 1 FROM pool_holds LIMIT 1").get();++/**+ * Every held run, one row each (its first), in the order runs are released: by account, then press. The release loop+ * reads this once a turn (holds are few: at most `limits.held` per account).+ */+export function heldRunHeads(): HoldRow[] {+ return db()+ .prepare(+ `SELECT h.* FROM pool_holds h JOIN (SELECT run_id, MIN(generation_id) AS first FROM pool_holds GROUP BY run_id) f ON f.first = h.generation_id+ ORDER BY h.account_id, h.pressed_at, h.run_id`,+ )+ .all() as HoldRow[];+}++/** Change every row of a held run. */+export function setRunHold(runId: string, fields: Partial<Pick<HoldRow, "reason" | "start_at" | "rank_rule" | "reserved" | "checked" | "paused" | "tries" | "tried_at" | "next_at">>): void {+ const keys = Object.keys(fields);+ if (!keys.length) return;+ db()+ .prepare(`UPDATE pool_holds SET ${keys.map((k) => `${k} = @${k}`).join(", ")} WHERE run_id = @__run`)+ .run({ ...fields, __run: runId });+}++/** How long a lease on a held run lasts: one turn of the release loop, its service calls included. */+export const HOLD_LEASE_MS = 60_000;++/** Take the release of a held run for this app process (false: another one is releasing it now: run-leases.ts). */+export const leaseRun = (runId: string, now = Date.now()): boolean => takeLease("pool_holds", runId, HOLD_LEASE_MS, now);++/** Give the lease back (the run still waits). */+export const endRunLease = (runId: string): void => endLease("pool_holds", runId);++/**+ * The run enters the line now: its holds go, in one step that only this app process's lease may take, and only for the+ * rows that still wait (one cancelled meanwhile is left out). Returns its rows to send (job index set) and the rank they+ * enter at, or null when it isn't this process's to release any more.+ */+export function takeRun(runId: string, now = Date.now()): { send: { id: string; job: number }[]; rankAt: number | undefined } | null {+ const d = db();+ return d+ .transaction(() => {+ const rows = d.prepare(`SELECT * FROM pool_holds WHERE run_id = ? AND ${MINE_NOW}`).all(runId, leaseToken(), now) as HoldRow[];+ if (!rows.length) return null;+ d.prepare("DELETE FROM pool_holds WHERE run_id = ?").run(runId);+ const live = d.prepare("SELECT 1 FROM generations WHERE id = ? AND status = 'queued' AND external_id IS NULL");+ const send = rows.filter((r) => r.job !== null && live.get(r.generation_id)).map((r) => ({ id: r.generation_id, job: r.job! }));+ const head = rows[0];+ return { send, rankAt: head.rank_rule === "press" ? head.pressed_at : undefined };+ })+ .immediate();+}++/** A held run ended before it entered the line (a service refused it): its holds go. */+export function dropRun(runId: string): void {+ db().prepare("DELETE FROM pool_holds WHERE run_id = ?").run(runId);+}++type Dropped = Pick<HoldRow, "run_id" | "reserved" | "request_id">;++/** Delete the holds `where` names (SQL on pool_holds), in one step; then give back what their runs never heard of. */+function dropWhere(where: string, ...params: unknown[]): number {+ const d = db();+ const gone = d+ .transaction(() => {+ const rows = d.prepare(`SELECT run_id, reserved, request_id FROM pool_holds WHERE ${where}`).all(...params) as Dropped[];+ if (rows.length) d.prepare(`DELETE FROM pool_holds WHERE ${where}`).run(...params);+ return rows;+ })+ .immediate();+ releaseUnheard(gone);+ return gone.length;+}++/**+ * Runs that stopped waiting before their reserve was ever answered (cancelled, deleted, the account gone): a try at the+ * press may have made a hold the app never heard of, so it goes back by the press's request id once none of the run's+ * rows waits any more (billing-outbox.ts queueRequestRelease; a service that holds nothing for it does nothing).+ */+function releaseUnheard(rows: Dropped[]): void {+ const left = db().prepare("SELECT 1 FROM pool_holds WHERE run_id = ? LIMIT 1");+ const seen = new Set<string>();+ for (const r of rows) {+ if (r.reserved || !r.request_id || seen.has(r.run_id)) continue;+ seen.add(r.run_id);+ if (!left.get(r.run_id)) queueRequestRelease(r.request_id);+ }+}++/** Holds whose row no longer waits to be sent (stopped, failed, deleted, or sent by another way) go. */+export const dropGone = (): number =>+ dropWhere("NOT EXISTS (SELECT 1 FROM generations g WHERE g.id = pool_holds.generation_id AND g.status = 'queued' AND g.external_id IS NULL)");++/** A row stopped (cancelled, failed, deleted): its hold goes. */+export const dropHold = (generationId: string): void => void dropWhere("generation_id = ?", generationId);++/** A deleted account leaves no holds. */+export const clearHolds = (accountId: string): void => void dropWhere("account_id = ?", accountId);++/** For the owner's view of the line: held runs by reason (counts only), and when the oldest was pressed. */+export function heldView(): Record<HoldReason, number> & { oldestAt: number | null } {+ const rows = db().prepare("SELECT reason, COUNT(DISTINCT run_id) AS n, MIN(pressed_at) AS oldest FROM pool_holds GROUP BY reason").all() as { reason: HoldReason; n: number; oldest: number }[];+ const out = Object.fromEntries(HOLD_REASONS.map((r) => [r, 0])) as Record<HoldReason, number>;+ let oldestAt: number | null = null;+ for (const r of rows) {+ out[r.reason] = r.n;+ oldestAt = oldestAt === null ? r.oldest : Math.min(oldestAt, r.oldest);+ }+ return { ...out, oldestAt };+}++/** Why a run just made waits, if it does: the policy's limits, the billing service's answer, the moderation service. */+export interface HoldCauses {+ /** The policy's limits (pool-limits.ts AdmitPlan): behind the account's runs going, or an hourly limit until `startAt`. */+ limit?: { reason: "mine" | "hour"; startAt?: number };+ /** The billing service's answer (hosted-run.ts ReserveWait). */+ wait?: { reason: "service" | "today" | "hour" | "credits"; startAt?: number; requestId?: string; paused?: true };+ /** The moderation service didn't answer: the run is checked before it enters the line. */+ unchecked?: boolean;+}++/**+ * The hold for a run with these causes, or null when it goes into line now. Its reason is the one its tile tells: a later+ * start first (the day's GPU time, an hourly limit, free generations that renew), then the service, then the account's+ * runs going. It enters at its press time only when every cause is the system's (the day's GPU time, the service), at+ * the back of the line when the account's own limits held it too. It reserves at release when the service didn't+ * answer, or for free generations that renew.+ */+export function holdShape(c: HoldCauses): Pick<NewHold, "reason" | "startAt" | "rankRule" | "reserved" | "checked" | "paused" | "requestId"> | null {+ if (!c.limit && !c.wait && !c.unchecked) return null;+ const starts = [c.limit?.startAt, c.wait?.startAt].filter((n): n is number => typeof n === "number");+ const startAt = starts.length ? Math.max(...starts) : undefined;+ const reason: HoldReason =+ startAt !== undefined ? (c.wait?.startAt === startAt ? c.wait.reason : (c.limit?.reason ?? "hour")) : c.wait?.reason === "service" || c.unchecked ? "service" : (c.limit?.reason ?? "service");+ const own = !!c.limit || c.wait?.reason === "hour" || c.wait?.reason === "credits";+ return {+ reason,+ ...(startAt !== undefined && { startAt }),+ rankRule: own ? "release" : "press",+ reserved: c.wait?.reason !== "service" && c.wait?.reason !== "credits",+ checked: !c.unchecked,+ ...(c.wait?.paused && { paused: true }),+ ...(c.wait?.requestId && { requestId: c.wait.requestId }),+ };+}++/**+ * About how long a run waits before it enters the line, for the billing service's hold (ReserveRequest.timing.heldMs):+ * until its later start, else an hour behind the account's runs going (the service keeps the hold of a run still+ * waiting open longer).+ */+export function heldGuessMs(limit: HoldCauses["limit"] | undefined, now = Date.now()): number {+ if (!limit) return 0;+ return limit.startAt !== undefined ? Math.max(0, limit.startAt - now) : 60 * 60_000;+}++/**+ * The reason a billing service's `startAt` gives a run (it says none): at a UTC midnight, the day's GPU time renews+ * ("today", entering at its press time); any other time is an hourly limit ("hour", entering when released).+ */+export const startReason = (startAt: number): "today" | "hour" => (startAt % 86_400_000 === 0 ? "today" : "hour");diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.tsindex bbb8660f..92c609f6 100644--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@ -3,8 +3,10 @@ import crypto from "node:crypto";import { ACTIVE_RUNS_CODE } from "@/lib/guest-access";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "./account-files";import { LoginGuard } from "./auth";-import type { Policy } from "./billing";+import { heldCap, holdsOn, type Policy } from "./billing";import { db } from "./db";+import { hostedRunsOn } from "./hosted-switch";+import { heldRuns, NOT_HELD } from "./pool-holds";/*** The limits on an account's runs, counted in SQLite so that requests that arrive together, in one process or in two@@ -21,6 +23,12 @@ import { db } from "./db";** admitRun counts and makes the run's rows in one `BEGIN IMMEDIATE` transaction: SQLite lets one writer in at a time,* across processes, so the count it reads is the count it adds to.+ *+ * When the policy says runs wait instead (`limits.held` present: billing.ts holdsOn), a press past the runs at once, the+ * runs in line or an hourly limit is taken all the same and waits to enter the line (pool-holds.ts): poolLimitPlan says+ * "hold". Only a press past the cap on runs waiting (`limits.held`) is turned down. Runs waiting there don't count as+ * going. While hosted runs are on, the studio's own limit of runs at once counts runs on the account's own GPU or key+ * and its light work only (ownActiveRuns): its other runs on this install's GPUs meet the policy's limits instead.*/const HOUR = 60 * 60_000;@@ -33,6 +41,8 @@ export const POOL_LIMIT_WORDS = {waiting: (n: number) => `You have ${n} ${n === 1 ? "run" : "runs"} in line. Start this one when one of them starts.`,hourly: "That's a lot of runs this hour. Try again later.",address: "That's a lot of runs from your network this hour. Try again later.",+ /** The one press that is turned down while runs wait: past the cap on runs waiting (`n`: the account's runs on the way). */+ heldCap: (n: number) => `You have ${n} ${n === 1 ? "run" : "runs"} on the way. Add more when one is done.`,};export interface LimitRefusal {@@ -84,9 +94,27 @@ export function accountActiveRuns(accountId: string): number {return r.n + openCount(accountId, false);}+/**+ * An account's runs going now that the studio's own limit of runs at once counts (ACCOUNT_LIMITS.activeRuns): with+ * hosted runs off, every run (accountActiveRuns, as always); with them on, its runs on its own GPU or its own key, and+ * its light work (joins, trims: free, on this install's CPU, and counted by none of the policy's limits), as its other+ * runs on this install's GPUs meet the policy's limits instead.+ */+export function ownActiveRuns(accountId: string): number {+ if (!hostedRunsOn()) return accountActiveRuns(accountId);+ const r = db()+ .prepare(+ `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?+ AND (json_extract(request_json, '$.place') IS NOT 'pool' OR json_extract(request_json, '$.light') IS 1)`,+ )+ .get(accountId) as { n: number };+ return r.n + openCount(accountId, false) - openCount(accountId, true);+}+/*** An account's runs going now on this install's GPUs, and how many of them haven't started yet (no row of theirs has).- * Runs of light work only (joins, trims) don't count. A run let in whose rows are still being made counts as one in line.+ * Runs of light work only (joins, trims) don't count, nor do runs waiting to enter the line (pool-holds.ts). A run let in+ * whose rows are still being made counts as one in line.*/export function poolRunCounts(accountId: string): { active: number; waiting: number } {const r = db()@@ -95,7 +123,7 @@ export function poolRunCounts(accountId: string): { active: number; waiting: numSELECT COALESCE(g.batch_id, g.id) AS k, MAX(CASE WHEN r.started_at IS NOT NULL THEN 1 ELSE 0 END) AS startedFROM generations g LEFT JOIN generation_runs r ON r.id = g.idWHERE g.status IN ('queued', 'running') AND json_extract(g.request_json, '$.account') = ? AND json_extract(g.request_json, '$.place') = 'pool'- AND json_extract(g.request_json, '$.light') IS NOT 1+ AND json_extract(g.request_json, '$.light') IS NOT 1 AND ${NOT_HELD("g")}GROUP BY k)`,).get(accountId) as { active: number; waiting: number };@@ -164,36 +192,102 @@ const since = (column: "account" | "addr", value: string, from: number) =>const retryAfter = (oldest: number | null, now: number) => Math.max(60, Math.ceil(((oldest ?? now) + HOUR - now) / 1000));/**- * The first of the policy's limits this run would pass, or null. `addr` may be a function: it is asked only when the- * policy counts runs per address.+ * When the next run past an hourly limit may start (epoch ms), counting each run from its start (a run told to wait+ * counts from then), so runs past the limit start in batches of `max`, an hour apart; null when it fits now.*/-export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null | (() => string | null), now = Date.now()): LimitRefusal | null {+function hourStart(column: "account" | "addr", value: string, max: number, now: number): number | null {+ const ats = db().prepare(`SELECT at FROM pool_admissions WHERE ${column} = ? AND at > ? ORDER BY at`).pluck().all(value, now - HOUR) as number[];+ return ats.length < max ? null : ats[ats.length - max] + HOUR;+}++/**+ * What the policy's limits say of a new run on this install's GPUs: it goes into line now (`go`), it is taken and waits+ * to enter the line (`hold`: "mine" behind the account's runs going, or "hour" until `startAt`), or it is turned down+ * (`refuse`). Without holds (billing.ts holdsOn: the policy has no `limits.held`), every limit refuses, as before. With+ * them, only a press past the cap on runs waiting is refused; and a run of an account whose runs already wait behind its+ * own waits behind them too, so its presses enter in the order they were made. `addr` may be a function: it is asked+ * only when the policy counts runs per address.+ */+export type LimitPlan = { go: true } | { hold: "mine" | "hour"; startAt?: number } | { refuse: LimitRefusal };++export function poolLimitPlan(accountId: string, policy: Pick<Policy, "limits">, addr: string | null | (() => string | null), now = Date.now()): LimitPlan {const lim = policy.limits ?? ({} as Policy["limits"]);- const positive = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);const activeMax = positive(lim.activeRuns);const waitingMax = positive(lim.waiting);const hourMax = positive(lim.runsPerHour);const addrMax = positive(lim.addressRunsPerHour);- if (activeMax || waitingMax) {- const c = poolRunCounts(accountId);- if (activeMax && c.active >= activeMax) return { status: 429, error: POOL_LIMIT_WORDS.active(c.active), code: ACTIVE_RUNS_CODE, retryAfterS: 30 };- if (waitingMax && c.waiting >= waitingMax) return { status: 429, error: POOL_LIMIT_WORDS.waiting(c.waiting), code: ACTIVE_RUNS_CODE, retryAfterS: 30 };+ const holds = holdsOn(policy);+ const c = activeMax || waitingMax || holds ? poolRunCounts(accountId) : { active: 0, waiting: 0 };+ const overActive = !!activeMax && c.active >= activeMax;+ const overWaiting = !!waitingMax && c.waiting >= waitingMax;+ if (!holds) {+ if (overActive) return { refuse: { status: 429, error: POOL_LIMIT_WORDS.active(c.active), code: ACTIVE_RUNS_CODE, retryAfterS: 30 } };+ if (overWaiting) return { refuse: { status: 429, error: POOL_LIMIT_WORDS.waiting(c.waiting), code: ACTIVE_RUNS_CODE, retryAfterS: 30 } };}+ let startAt: number | null = null;if (hourMax) {- const h = since("account", accountId, now - HOUR);- if (h.n >= hourMax) return { status: 429, error: POOL_LIMIT_WORDS.hourly, code: "limit", retryAfterS: retryAfter(h.oldest, now) };+ if (holds) startAt = hourStart("account", accountId, hourMax, now);+ else {+ const h = since("account", accountId, now - HOUR);+ if (h.n >= hourMax) return { refuse: { status: 429, error: POOL_LIMIT_WORDS.hourly, code: "limit", retryAfterS: retryAfter(h.oldest, now) } };+ }}const address = addrMax ? (typeof addr === "function" ? addr() : addr) : null;if (address) {- const h = since("addr", address, now - HOUR);- if (h.n >= addrMax) return { status: 429, error: POOL_LIMIT_WORDS.address, code: "limit", retryAfterS: retryAfter(h.oldest, now) };+ if (holds) {+ const at = hourStart("addr", address, addrMax, now);+ if (at !== null) startAt = Math.max(startAt ?? 0, at);+ } else {+ const h = since("addr", address, now - HOUR);+ if (h.n >= addrMax) return { refuse: { status: 429, error: POOL_LIMIT_WORDS.address, code: "limit", retryAfterS: retryAfter(h.oldest, now) } };+ }}- return null;+ if (!holds) return { go: true };+ // The one press turned down while runs wait: past the cap on the account's runs on the way, whatever this one would+ // wait for (behind its own runs, the day's GPU time, a quiet service).+ const refusal = heldCapRefusal(accountId, policy, c);+ if (refusal) return { refuse: refusal };+ const behindOwn = heldRuns(accountId, "mine") > 0;+ if (!overActive && !overWaiting && !behindOwn && startAt === null) return { go: true };+ return startAt !== null ? { hold: "hour", startAt } : { hold: "mine" };}-/** The studio's own limit of runs at once (every account run, wherever it goes), as a refusal. */+const positive = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);++/**+ * How many more of an account's runs may go into line now: the policy's runs at once and runs in line, less its runs+ * going there (`c`: poolRunCounts; held runs don't count). Infinity when the policy limits neither.+ */+export function lineRoom(policy: Pick<Policy, "limits">, c: { active: number; waiting: number }): number {+ const activeMax = positive(policy.limits?.activeRuns);+ const waitingMax = positive(policy.limits?.waiting);+ return Math.max(0, Math.min(activeMax ? activeMax - c.active : Infinity, waitingMax ? waitingMax - c.waiting : Infinity));+}++/**+ * A press past the cap on an account's runs on the way (billing.ts heldCap: the policy's `limits.held` waiting behind+ * its runs at once, 8 behind 2 at launch: 10 in all; 0: no cap), as a refusal; null while there is room. Runs held for+ * any reason count, so a quiet service or the day's GPU time used up never lets more wait than that. `c`: its runs going+ * now (poolRunCounts), counted with the waiting ones in the words.+ */+export function heldCapRefusal(accountId: string, policy: Pick<Policy, "limits">, c = poolRunCounts(accountId)): LimitRefusal | null {+ const cap = heldCap(policy);+ if (!cap) return null;+ const held = heldRuns(accountId);+ const room = lineRoom(policy, c);+ if (held < cap + (Number.isFinite(room) ? room : 0)) return null;+ return { status: 429, error: POOL_LIMIT_WORDS.heldCap(c.active + held), code: ACTIVE_RUNS_CODE, retryAfterS: 30 };+}++/** The first of the policy's limits this run would be refused for, or null (poolLimitPlan; a run that waits is no refusal). */+export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null | (() => string | null), now = Date.now()): LimitRefusal | null {+ const plan = poolLimitPlan(accountId, policy, addr, now);+ return "refuse" in plan ? plan.refuse : null;+}++/** The studio's own limit of runs at once (ownActiveRuns), as a refusal. */function accountLimitRefusal(accountId: string): LimitRefusal | null {- return accountActiveRuns(accountId) >= ACCOUNT_LIMITS.activeRuns ? { status: 429, error: ACCOUNT_MESSAGES.activeRuns, code: ACTIVE_RUNS_CODE, retryAfterS: 30 } : null;+ return ownActiveRuns(accountId) >= ACCOUNT_LIMITS.activeRuns ? { status: 429, error: ACCOUNT_MESSAGES.activeRuns, code: ACTIVE_RUNS_CODE, retryAfterS: 30 } : null;}/** A refusal thrown inside admitRun's transaction, so nothing `make` wrote is kept. */@@ -206,10 +300,18 @@ export class AdmitRefused extends Error {/** What admitRun answers: the run made, the refusal, or (with `prior`) what this same request made already. */export type Admitted<T, P = never> = { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | ([P] extends [never] ? never : { ok: false; prior: P });+/** What admitRun decided for a run it lets in on this install's GPUs: none (it goes into line now), or that it waits. */+export interface AdmitPlan {+ hold?: { reason: "mine" | "hour"; startAt?: number };+}+/**- * Count, and make the run (`make`) only if it fits: the studio's own limit for every account run, and with `pool` the- * policy's limits on runs on this install's GPUs. All in one BEGIN IMMEDIATE transaction; a run on this install's GPUs is- * noted for the hourly counts in the same transaction. `make` may throw AdmitRefused (or anything else) to keep nothing.+ * Count, and make the run (`make`) only if it fits: with `pool`, the policy's limits on runs on this install's GPUs;+ * without, the studio's own limit of runs at once (ownActiveRuns: a run on the account's own GPU or key, light work, and+ * every run while hosted runs are off). A run the policy's limits hold is made all the same: `make` is+ * told so (AdmitPlan), and holds it instead of sending it (pool-holds.ts). All in one BEGIN IMMEDIATE transaction; a run on+ * this install's GPUs is noted for the hourly counts in the same transaction (one told to wait for an hourly limit, at+ * the time it may start). `make` may throw AdmitRefused (or anything else) to keep nothing.* `prior`, looked at first in the same transaction: what this same request made already (a resend of one press of Run,* run-requests.ts); when it says anything, nothing is counted or made, and it is the answer. `refused`, called in the* same transaction when the run is not made (a limit, AdmitRefused, or another error from `make`, which is thrown again@@ -223,7 +325,7 @@ export function admitRun<T, P = never>(prior?: () => P | null;refused?: (why: AdmitRefused["refusal"] | Error) => void;},- make: () => T,+ make: (plan: AdmitPlan) => T,): Admitted<T, P> {type Answer = { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P };const now = o.now ?? Date.now();@@ -236,17 +338,19 @@ export function admitRun<T, P = never>(.transaction((): Answer | null => {const prior = o.prior?.() ?? null;if (prior !== null) return { ok: false, prior };- const refusal = accountLimitRefusal(o.accountId) ?? (o.pool ? poolLimitRefusal(o.accountId, o.pool.policy, o.pool.addr, now) : null);+ const plan: LimitPlan = o.pool ? poolLimitPlan(o.accountId, o.pool.policy, o.pool.addr, now) : { go: true };+ const refusal = (o.pool ? null : accountLimitRefusal(o.accountId)) ?? ("refuse" in plan ? plan.refuse : null);if (refusal) {refused?.(refusal);return { ok: false, refusal };}+ const admit: AdmitPlan = "hold" in plan ? { hold: { reason: plan.hold, ...(plan.startAt !== undefined && { startAt: plan.startAt }) } } : {};let value: T;- if (!refused) value = make();+ if (!refused) value = make(admit);else {try {// In a savepoint: a make that refuses or fails keeps nothing it wrote, and the refusal is still noted.- value = d.transaction(make)();+ value = d.transaction(() => make(admit))();} catch (e) {refused(e instanceof AdmitRefused ? e.refusal : e instanceof Error ? e : new Error(String(e)));if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };@@ -255,7 +359,7 @@ export function admitRun<T, P = never>(}}if (o.pool) {- d.prepare("INSERT INTO pool_admissions (account, addr, at) VALUES (?, ?, ?)").run(o.accountId, o.pool.addr, now);+ d.prepare("INSERT INTO pool_admissions (account, addr, at) VALUES (?, ?, ?)").run(o.accountId, o.pool.addr, admit.hold?.startAt ?? now);prunePoolAdmissions(now, true);}return { ok: true, value };diff --git a/src/server/pool-release.ts b/src/server/pool-release.tsnew file mode 100644index 00000000..c1d944b4--- /dev/null+++ b/src/server/pool-release.ts@@ -0,0 +1,197 @@+import "server-only";+import type { GenerationRequest } from "@/lib/catalog/types";+import { accountById } from "./auth";+import { accountFacts, billingConfigured, forgetBalance, policy as billingPolicy, policyGiveUpMs, reserve, serviceAnsweredAt } from "./billing";+import { db } from "./db";+import { failWaiting, previewGeneration, restampRows, sendHeld } from "./generations";+import { queueFacts, runOnPool } from "./hosted";+import { heldStamp, moderateRun, renewalAt, type ReserveFacts } from "./hosted-run";+import { dropGone, dropRun, endRunLease, heldRunHeads, leaseRun, runHolds, setRunHold, startReason, takeRun, type HoldRow } from "./pool-holds";+import { lineRoom, poolRunCounts } from "./pool-limits";+import { stampOf, withoutStamp, withRunStamp } from "./run-stamp";++/**+ * The release loop of runs made but waiting to enter the line on this install's GPUs (pool-holds.ts). It runs in the+ * generations runner's turn (every app process, every 1.5 s), only while hosted runs are on and something waits:+ *+ * 1. A run waits until its `start_at` (the day's GPU time renews, an hourly limit, free generations renew).+ * 2. A run the billing or moderation service didn't answer for is checked and reserved, under its press's own request id+ * (so a hold an unanswered try made at the press is the one it gets): tried again with a growing wait (1 s, doubling,+ * at most 30 s), and at once after the service answers any call. An answer with a later start waits for it; a refusal+ * ends the run in the service's words (its tile says it plainly).+ * 3. It enters when the account has room among its runs going (the policy's runs at once and in line), its presses in the+ * order they were made; a run that counted already (one cut off by a deploy or a crash) needs no room.+ * 4. It enters the line at its press time (the system's reasons) or at the back (the account's own), and its rows are+ * sent from what is stored, as a run is sent again after its GPU lost it.+ *+ * Each run is leased to one app process while it is released (pool-holds.ts leaseRun), so two processes during a deploy+ * never release one run twice, and a process that stops mid-way leaves it to the other once its lease ends.+ */++/** Service calls one turn of the loop makes at most: a service that hangs holds up nothing else for long. */+const SERVICE_TRIES_PER_TURN = 3;++/** How long a run waiting for a service waits before it asks again (ms): 1 s, doubling, at most 30 s. */+export const holdBackoffMs = (tries: number): number => Math.min(30_000, 1000 * 2 ** Math.min(Math.max(0, tries), 5));++/** After how long runs waiting for the billing service are said in the owner's log (the service can't say so itself). */+export const SERVICE_WAIT_SAID_MS = 5 * 60_000;++declare global {+ var __fuobeHoldServiceSaid: number | undefined;+}++/** The owner's log, at most every SERVICE_WAIT_SAID_MS: how many runs wait for the billing service (counts only). */+function sayServiceWait(heads: HoldRow[], now: number): void {+ const long = heads.filter((h) => (!h.reserved || !h.checked) && now - h.pressed_at > SERVICE_WAIT_SAID_MS);+ if (!long.length || now - (globalThis.__fuobeHoldServiceSaid ?? 0) < SERVICE_WAIT_SAID_MS) return;+ globalThis.__fuobeHoldServiceSaid = now;+ const oldest = Math.round((now - Math.min(...long.map((h) => h.pressed_at))) / 60_000);+ console.warn(`[fuobe] runs waiting for the billing service: ${long.length} (oldest ${oldest} min)`);+}++/**+ * How many more of an account's runs may enter the line now (pool-limits.ts lineRoom: held runs don't count). Null when+ * its policy isn't known (the service is quiet and nothing is kept): its runs wait.+ */+async function roomFor(accountId: string, kept: Map<string, number | null>): Promise<number | null> {+ if (kept.has(accountId)) return kept.get(accountId)!;+ const p = await billingPolicy(accountId);+ const left = p ? lineRoom(p, poolRunCounts(accountId)) : null;+ kept.set(accountId, left);+ return left;+}++/** Ask again later: one more try, and the next one after a growing wait (`paused`: the service said runs are paused). */+function later(h: HoldRow, now: number, paused?: boolean): void {+ setRunHold(h.run_id, { tries: h.tries + 1, tried_at: now, next_at: now + holdBackoffMs(h.tries), ...(paused !== undefined && { paused: paused ? 1 : 0 }) });+}++/** A service refused the run once it answered: its rows end in its words (the tile says it plainly), its holds go. */+function end(h: HoldRow, ids: string[], error: string): "ended" {+ failWaiting(ids, error || "This run couldn't be made.");+ dropRun(h.run_id);+ return "ended";+}++/**+ * The checks a run that waited for the services still needs: the moderation service's, then the billing service's hold.+ * "ready" once both are done; "wait" for a later start or another try; "down" when the service gave no answer at all+ * (no more calls this turn); "ended" when one refused it.+ */+async function serviceStep(h: HoldRow, now: number): Promise<"ready" | "wait" | "down" | "ended"> {+ const rows = runHolds(h.run_id);+ const ids = rows.map((r) => r.generation_id);+ const account = accountById(h.account_id);+ if (!account) return "wait";+ const first = rows.find((r) => r.job !== null) ?? rows[0];+ const row = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(first.generation_id) as { request_json: string } | undefined;+ if (!row) return "wait";+ const stored = JSON.parse(row.request_json) as GenerationRequest;+ if (!h.checked) {+ const req = withoutStamp(stored) as GenerationRequest;+ let planned: ReturnType<typeof previewGeneration>;+ try {+ planned = runOnPool(account.id, () => withRunStamp(stampOf(stored), () => previewGeneration(req)));+ } catch (e) {+ return end(h, ids, (e as Error).message);+ }+ const mod = await moderateRun(account, req, planned, "pool");+ if (!mod.ok) {+ if (mod.refusal.body.code !== "paused") return end(h, ids, mod.refusal.body.error);+ later(h, now);+ return "down";+ }+ if (mod.checkOutputs) restampRows(ids, { checkOutputs: true });+ setRunHold(h.run_id, { checked: 1 });+ }+ if (!h.reserved) {+ if (!billingConfigured()) {+ setRunHold(h.run_id, { reserved: 1, paused: 0 });+ return "ready";+ }+ const facts = h.facts_json ? (JSON.parse(h.facts_json) as ReserveFacts) : null;+ if (!facts || !h.request_id) return end(h, ids, "");+ const queue = queueFacts(account.id, facts.workflowId);+ const a = await reserve({ requestId: h.request_id, account: accountFacts(account), run: facts.run, queue, shown: facts.shown, timing: facts.timing }, { forMs: 0 });+ if (!a) {+ setRunHold(h.run_id, { reserved: 1, paused: 0 });+ return "ready";+ }+ if (!a.ok) {+ // No answer (or one that may have made a hold: the same request id gets it next time), or runs paused there.+ if (a.code === "paused" || a.down || a.unsure) {+ later(h, now, a.code === "paused" && !a.down);+ return a.down ? "down" : "wait";+ }+ // No free generations left until they renew: it waits for them, and reserves then.+ const renews = await renewalAt(a, account, facts.run, queue, now);+ if (renews !== null) {+ setRunHold(h.run_id, { reason: "credits", start_at: renews, rank_rule: "release", tries: 0, next_at: null, paused: 0 });+ return "wait";+ }+ return end(h, ids, a.text);+ }+ forgetBalance(account.id);+ restampRows(ids, heldStamp(a, policyGiveUpMs(await billingPolicy(account.id))));+ const at = Number(a.startAt);+ if (Number.isFinite(at) && at > Date.now()) {+ // Its hold is made, and it starts later (the day's GPU time, an hourly limit).+ const reason = startReason(at);+ setRunHold(h.run_id, { reserved: 1, paused: 0, reason, start_at: at, ...(reason === "hour" && { rank_rule: "release" as const }) });+ return "wait";+ }+ setRunHold(h.run_id, { reserved: 1, paused: 0 });+ }+ return "ready";+}++/**+ * One turn of the release loop: every held run whose reason cleared enters the line. Returns how many runs entered.+ * Holds whose rows no longer wait (stopped, deleted) go first.+ */+export async function releaseHeldRuns(now = Date.now()): Promise<number> {+ dropGone();+ const heads = heldRunHeads();+ if (!heads.length) return 0;+ sayServiceWait(heads, now);+ const room = new Map<string, number | null>();+ let released = 0;+ let serviceCalls = 0;+ let serviceDown = false;+ for (const h of heads) {+ // Not before its time.+ if (h.start_at !== null && h.start_at > now) continue;+ const needsService = !h.reserved || !h.checked;+ if (needsService) {+ if (serviceDown || serviceCalls >= SERVICE_TRIES_PER_TURN) continue;+ const due = h.next_at === null || h.next_at <= now || (h.tried_at !== null && serviceAnsweredAt() > h.tried_at);+ if (!due) continue;+ }+ if (!leaseRun(h.run_id, now)) continue;+ try {+ if (needsService) {+ serviceCalls++;+ const step = await serviceStep(h, now);+ if (step === "down") serviceDown = true;+ if (step !== "ready") continue;+ }+ if (!h.counted) {+ const left = await roomFor(h.account_id, room);+ if (left === null || left <= 0) {+ // Its own reason cleared, but the account's runs going fill its room: it waits behind them, as its tile says.+ if (h.reason !== "mine") setRunHold(h.run_id, { reason: "mine", start_at: null, paused: 0 });+ continue;+ }+ }+ const taken = takeRun(h.run_id);+ if (!taken) continue;+ for (const s of taken.send) sendHeld(s.id, s.job, taken.rankAt);+ if (!h.counted) room.set(h.account_id, (room.get(h.account_id) ?? 1) - 1);+ released++;+ } finally {+ endRunLease(h.run_id);+ }+ }+ return released;+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 10f70acd..331a7f7d 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -289,11 +289,15 @@ export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this machfunction accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string }) {const stamp = runStamp();const run = generationId ? runPlaceOf(generationId) : null;+ // A run that waited to enter the line for the system's reasons (the day's GPU time, a quiet service) enters at its+ // press, with its head start (pool-holds.ts).+ const pressed = run?.rankAt == null && stamp?.rankAt !== undefined ? stamp.rankAt - Math.max(0, Math.min(stamp.boostMs ?? 0, 24 * 60 * 60_000)) : undefined;return poolFields(workflowId, {account,class: stamp?.class ?? "free",boostMs: stamp?.boostMs,...(run?.rankAt != null && { rankAt: run.rankAt }),+ ...(pressed !== undefined && { rankAt: pressed }),waitMs: run?.started || run?.later ? undefined : (stamp?.waitMs ?? poolWaitMs()),size: o.size,catalogVersion: o.catalogVersion,diff --git a/src/server/run-leases.ts b/src/server/run-leases.tsnew file mode 100644index 00000000..55598ac4--- /dev/null+++ b/src/server/run-leases.ts@@ -0,0 +1,38 @@+import "server-only";+import { nanoid } from "nanoid";+import { db } from "./db";++/**+ * Leases on rows that one app process works on at a time: two app processes (a deploy's overlap) never take the same row+ * twice, and a process that stops mid-way leaves it to another once its lease ends. A leased table has `holder` (the+ * process's token) and `lease_until` (epoch ms) columns, and is named here with the column its rows are leased by:+ * - `pool_holds` by `run_id`: runs waiting to enter the line on this install's GPUs (pool-holds.ts, pool-release.ts).+ */+const LEASED = { pool_holds: "run_id" } as const;++export type LeasedTable = keyof typeof LEASED;++declare global {+ var __fuobeLeaseToken: string | undefined;+}++/** This app process's name on its leases (new after a restart). */+export const leaseToken = (): string => (globalThis.__fuobeLeaseToken ??= `${process.pid}:${nanoid(10)}`);++/** Take the lease on `key`'s rows for `ms` (false: another process holds it now). Taking it again extends it. */+export function takeLease(table: LeasedTable, key: string, ms: number, now = Date.now()): boolean {+ const col = LEASED[table];+ return (+ db()+ .prepare(`UPDATE ${table} SET holder = @me, lease_until = @until WHERE ${col} = @key AND (holder IS NULL OR holder = @me OR lease_until IS NULL OR lease_until < @now)`)+ .run({ me: leaseToken(), until: now + ms, key, now }).changes > 0+ );+}++/** Give the lease on `key`'s rows back (they stay, for any process to take). */+export function endLease(table: LeasedTable, key: string): void {+ db().prepare(`UPDATE ${table} SET holder = NULL, lease_until = NULL WHERE ${LEASED[table]} = ? AND holder = ?`).run(key, leaseToken());+}++/** SQL: a row of a leased table this process holds the lease on now (parameters: leaseToken(), now). */+export const MINE_NOW = "holder = ? AND lease_until >= ?";diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex 44fa2b47..67c35fec 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -34,6 +34,11 @@ export interface RunStamp {boostMs?: number;/** Light work only (hosted-run.ts lightRun): free, and not counted against the policy's limits. */light?: boolean;+ /**+ * In scope only, never stored (not a STAMP_FIELDS field): the time a run that waited to enter the line takes its place+ * at (its press, pool-holds.ts), when its first job is sent. Absent: the time it is sent.+ */+ rankAt?: number;}declare global {diff --git a/tests/hosted-guest-draft.test.ts b/tests/hosted-guest-draft.test.tsindex db1d4263..e76748c2 100644--- a/tests/hosted-guest-draft.test.ts+++ b/tests/hosted-guest-draft.test.ts@@ -132,6 +132,15 @@ describe("the run a guest pressed", () => {expect(step({ shown: { amount: 0, priceVersion: "", text: "" }, quote: { allowed: true, amount: 0, text: "" } })).toBe("start");});+ it("starts for a run the server takes and keeps waiting: behind the account's other runs, until a time, or while the price can't be known", () => {+ // The line says it waits (the price is the one shown): the run is taken all the same.+ expect(step({ quote: { allowed: true, amount: 0, text: "Free" } })).toBe("start");+ // The billing service doesn't answer and no price is known now: allowed with no words, the run waits for it.+ expect(step({ quote: { allowed: true, amount: 0, text: "" } })).toBe("start");+ // But never with nothing shown to compare.+ expect(step({ shown: null, quote: { allowed: true, amount: 0, text: "" } })).toBe("none");+ });+it("never starts without a kept file that didn't come back, even in a slot the run could do without", () => {// When every run costs the same ("Free") and a reference photo or start frame is optional, only the lost file// stops it, and the person is asked to add it again.diff --git a/tests/hosted-tool-runs.test.ts b/tests/hosted-tool-runs.test.tsindex 59337428..164d67a0 100644--- a/tests/hosted-tool-runs.test.ts+++ b/tests/hosted-tool-runs.test.ts@@ -437,11 +437,12 @@ describe("hosted runs on", () => {expect(db().prepare("SELECT COUNT(*) AS n FROM open_admissions WHERE account = ?").get(account.id)).toEqual({ n: 0 });const third = await go();expect(third.ok).toBe(false);- // The account's own limit of runs at once counts such a run too, while its rows are being made.+ // The studio's own limit of runs at once (4) counts runs on the account's own GPU or key only while hosted runs are+ // on: runs here meet the policy's limits, so with none set every one sent together is taken.db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), activeRuns: 0, waiting: 0 } };const many = await Promise.all(Array.from({ length: 6 }, go));- expect(many.filter((r) => r.ok)).toHaveLength(4);+ expect(many.filter((r) => r.ok)).toHaveLength(6);});it("a start that makes no rows gives its hold back, answers as the tool does, and isn't one of the hour's runs", async () => {diff --git a/tests/pool-holds.test.ts b/tests/pool-holds.test.tsnew file mode 100644index 00000000..259ada04--- /dev/null+++ b/tests/pool-holds.test.ts@@ -0,0 +1,586 @@+import crypto from "node:crypto";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { lineWords, noteWords } from "@/lib/pool-line";+import { startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";+import { tempDir } from "./helpers/temp-dir";++/**+ * Runs on this install's GPUs that are made but wait to enter the line (src/server/pool-holds.ts, pool-release.ts): one+ * press makes one run, always. A press past the account's runs at once is taken and enters at the back when one of them+ * ends (so ten fast presses never pass another account); the day's GPU time used up keeps runs back until it renews,+ * then they enter in press order; a press while the billing service doesn't answer is taken and reserves once it is+ * back, at its press-time place; a run cut off between its row and its GPU task waits again instead of failing; only a+ * press past the cap on runs waiting is refused. Leases keep two app processes from releasing one run twice.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = tempDir("fuobe-pool-holds-");+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 pool = await import("@/server/computer/pool");+const { catalogVersion } = await import("@/server/computer/catalog-version");+const billing = await import("@/server/billing");+const limits = await import("@/server/pool-limits");+const holds = await import("@/server/pool-holds");+const release = await import("@/server/pool-release");+const { loadManifest } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");+const { cancelGeneration, getGeneration } = await import("@/server/generations");+const { ACCOUNT_LIMITS, 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" };+const SHOWN = { shown: { amount: 7, priceVersion: "v7" } };++let fake: FakeBilling;+let n = 0;++function account() {+ const a = auth.createAccount(`holds-${++n}@example.com`, "long enough");+ return { id: a.id, cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` };+}++type Answer = { status: number; body: { items?: { id: string; place?: string; queue?: Record<string, unknown> }[]; code?: string; error?: string; held?: { reason: string }; quote?: Record<string, unknown>; line?: Record<string, unknown> } };++const send = async (url: string, body: Record<string, unknown>, cookie: string): Promise<Answer> => {+ const text = JSON.stringify(body);+ const r = await generationsRoute.POST(+ new Request(url, { 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 Answer["body"] };+};+const press = (cookie: string, extra: Record<string, unknown> = {}) => send(`http://${HOST}/api/generations`, { ...IMAGE, ...SHOWN, requestId: `p-${crypto.randomUUID()}`, ...extra }, cookie);+const check = (cookie: string) => send(`http://${HOST}/api/generations?preview=1`, { ...IMAGE }, cookie);++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 = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);+ return w;+}++/** Runs wait instead of being refused: a policy with `limits.held` (8 waiting behind 2 at once, as at launch). */+const withHolds = (lim: Record<string, unknown> = {}) => {+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ fake.policy = { ...FAKE_POLICY, limits: { ...FAKE_POLICY.limits, activeRuns: 2, waiting: 0, runsPerHour: 0, outputsPerRun: 4, held: 8, ...lim }, 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;+ fake.down = false;+ fake.refuse = null;+ fake.reserveExtra = {};+ fake.quoteAnswer = 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();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ db().prepare("DELETE FROM pool_holds").run();+ standInWorker();+ withHolds();+});++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 id, state, rank_at, created_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL ORDER BY created_at DESC").get(generationId) as+ | { id: string; state: string; rank_at: number; created_at: number }+ | undefined;+const heldOf = (generationId: string) => holds.holdOf(generationId);+const idOf = (r: Answer) => r.body.items![0].id;+const tile = (id: string) => {+ const g = getGeneration(id)!;+ return g.queue ? lineWords(g.queue) : null;+};+/** The account's runs going stop (the first ends): room opens for a run that waits behind them. */+async function stop(ids: string[]) {+ for (const id of ids) await cancelGeneration(id);+}++describe("the third press (behind the account's own runs)", () => {+ it("A2: three fast presses make three runs; the third waits after the others and enters at the back when the first ends", async () => {+ const a = account();+ const b = account();+ const [one, two, three] = [await press(a.cookie), await press(a.cookie), await press(a.cookie)];+ for (const r of [one, two, three]) expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(one.body.held).toBeUndefined();+ expect(two.body.held).toBeUndefined();+ // The third: made at once, its tile "In line", and no GPU task yet.+ expect(three.body.held).toEqual({ reason: "mine" });+ expect(three.body.items![0].queue).toMatchObject({ held: "mine" });+ expect(taskOf(idOf(three))).toBeUndefined();+ expect(tile(idOf(three))).toMatch(/^In line · after your other runs/);+ // A reload changes nothing: the same tile, and still no task.+ await tick();+ expect(tile(idOf(three))).toMatch(/^In line · after your other runs/);+ expect(taskOf(idOf(three))).toBeUndefined();+ // Another account's press meanwhile goes into line now.+ const other = await press(b.cookie);+ expect(other.body.held).toBeUndefined();+ const otherTask = await until(() => taskOf(idOf(other)));+ // The first ends: the third enters, at the back (behind the other account's run, pressed after it).+ await stop([idOf(one)]);+ const t = await until(() => taskOf(idOf(three)));+ expect(t, "the third entered the line").toBeTruthy();+ expect(t!.rank_at).toBeGreaterThan(otherTask!.rank_at);+ expect(heldOf(idOf(three))).toBeUndefined();+ // One run per press: three rows for three presses, each with one hold at the service.+ const reserves = fake.calls_of("/v1/reserve").map((c) => (c.body as { requestId: string }).requestId);+ expect(new Set(reserves).size).toBe(reserves.length);+ });++ it("ten presses never pass another account: the held ones enter behind a run pressed after them", async () => {+ const a = account();+ const b = account();+ const ids: string[] = [];+ for (let i = 0; i < 10; i++) {+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ ids.push(idOf(r));+ }+ expect(holds.heldRuns(a.id)).toBe(8);+ const other = await press(b.cookie);+ const otherTask = await until(() => taskOf(idOf(other)));+ await stop(ids.slice(0, 2));+ await until(() => taskOf(ids[2]) && taskOf(ids[3]));+ for (const id of ids.slice(2, 4)) expect(taskOf(id)!.rank_at).toBeGreaterThan(otherTask!.rank_at);+ // Its presses enter in the order they were made, two at a time: the next ones still wait.+ expect(taskOf(ids[4])).toBeUndefined();+ expect(holds.heldRuns(a.id)).toBe(6);+ });++ it("the held cap: the 11th press (10 on the way) is the only one turned down, before Run and when pressed", async () => {+ const a = account();+ for (let i = 0; i < 10; i++) expect((await press(a.cookie)).status).toBe(201);+ const p = await check(a.cookie);+ expect(p.body.quote).toMatchObject({ allowed: false, code: "limit", text: limits.POOL_LIMIT_WORDS.heldCap(10) });+ const eleventh = await press(a.cookie);+ expect(eleventh.status).toBe(429);+ expect(eleventh.body.error).toBe("You have 10 runs on the way. Add more when one is done.");+ expect(limits.POOL_LIMIT_WORDS.heldCap(10)).toBe(eleventh.body.error);+ });++ it("before Run: 'Starts after your other runs' while two go, and Run stays on", async () => {+ const a = account();+ await press(a.cookie);+ await press(a.cookie);+ const p = await check(a.cookie);+ expect(p.body.quote).toMatchObject({ allowed: true });+ expect(p.body.line).toMatchObject({ held: "mine" });+ expect(noteWords(p.body.line as never)).toBe("Starts after your other runs");+ });++ it("A19: six presses meet no 'You have 4 runs going' and no hourly refusal of the studio's own; the 11th meets the held cap only", async () => {+ const a = account();+ // The studio's own hourly count, made small: runs on this install's GPUs never meet it.+ const lim = ACCOUNT_LIMITS as unknown as { runsPerHour: number };+ const was = lim.runsPerHour;+ try {+ lim.runsPerHour = 3;+ for (let i = 0; i < 10; i++) {+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.error).not.toBe(ACCOUNT_MESSAGES.activeRuns);+ }+ expect((await press(a.cookie)).body.error).toBe(limits.POOL_LIMIT_WORDS.heldCap(10));+ } finally {+ lim.runsPerHour = was;+ }+ });++ it("an hourly limit holds a run until the hour's oldest run is an hour old, and it enters at the back then", async () => {+ withHolds({ activeRuns: 0, runsPerHour: 2 });+ const a = account();+ await press(a.cookie);+ await press(a.cookie);+ const third = await press(a.cookie);+ expect(third.body.held).toEqual({ reason: "hour" });+ const h = heldOf(idOf(third))!;+ expect(h.start_at! - Date.now()).toBeGreaterThan(59 * 60_000);+ expect(tile(idOf(third))).toMatch(/^In line · starts in about \d+ (min|h)$/);+ // Not before its time; then it enters.+ expect(await release.releaseHeldRuns()).toBe(0);+ expect(await release.releaseHeldRuns(h.start_at! + 1)).toBe(1);+ expect(await until(() => taskOf(idOf(third)))).toBeTruthy();+ });++ it("cancel: a held run stops like any other, its hold goes, and nothing is ever sent for it", async () => {+ const a = account();+ const [one] = [await press(a.cookie), await press(a.cookie)];+ const third = await press(a.cookie);+ await cancelGeneration(idOf(third));+ expect(getGeneration(idOf(third))!.status).toBe("canceled");+ expect(heldOf(idOf(third))).toBeUndefined();+ await stop([idOf(one)]);+ await tick();+ expect(taskOf(idOf(third))).toBeUndefined();+ });++ it("C17: the owner sees held runs by why (counts only), and a deleted account leaves no holds", async () => {+ const a = account();+ for (let i = 0; i < 4; i++) await press(a.cookie);+ const v = pool.queueView();+ expect(v.held.mine).toBe(2);+ expect(v.held.oldestAt).toBeTypeOf("number");+ expect(JSON.stringify(v.held)).not.toContain(a.id);+ holds.clearHolds(a.id);+ expect(holds.heldRuns(a.id)).toBe(0);+ });+});++describe("the daily cap (H2)", () => {+ /** The next UTC midnight: the time the billing service says the day's GPU time renews. */+ const midnight = () => (Math.floor(Date.now() / 86_400_000) + 1) * 86_400_000;++ it("A4: past the day's GPU time a press makes a held run; before Run 'Lots of runs today'; at the renewal they enter in press order", async () => {+ const at = midnight();+ fake.reserveExtra = { startAt: at };+ fake.quoteAnswer = { allowed: true, amount: 7, priceVersion: "v7", text: "7 units", startAt: at };+ const a = account();+ const b = account();+ const p = await check(a.cookie);+ expect(p.body.quote).toMatchObject({ allowed: true });+ expect(p.body.line).toMatchObject({ held: "today", startAt: at, long: true });+ expect(noteWords(p.body.line as never)).toMatch(/^Lots of runs today · starts in about \d+ (h|min)$/);+ const first = await press(b.cookie);+ await new Promise((r) => setTimeout(r, 5));+ const second = await press(a.cookie);+ for (const r of [first, second]) {+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "today" });+ }+ expect(tile(idOf(second))).toMatch(/^In line · starts in about \d+ (h|min)$/);+ // Its hold is made at the press (the service keeps it until then).+ expect(heldOf(idOf(second))!.reserved).toBe(1);+ expect(await release.releaseHeldRuns()).toBe(0);+ // A run pressed now, after the renewal, by a third account.+ fake.reserveExtra = {};+ const c = account();+ const later = await press(c.cookie);+ const laterTask = await until(() => taskOf(idOf(later)));+ expect(await release.releaseHeldRuns(at + 1)).toBe(2);+ const t1 = await until(() => taskOf(idOf(first)));+ const t2 = await until(() => taskOf(idOf(second)));+ // Press order, at their press-time places (ahead of the run pressed after them).+ expect(t1!.rank_at).toBeLessThan(t2!.rank_at);+ expect(t2!.rank_at).toBeLessThan(laterTask!.rank_at);+ });++ it("H6: no free generations left (credits on): the press is taken, waits for the renewal, and reserves then", async () => {+ const at = midnight();+ // The reserve turns it down for credit; the quote says the free generations that renew then pay for it.+ fake.refuse = { code: "top-up", text: "This needs 7 units. You have 0." };+ fake.quoteAnswer = { allowed: true, amount: 7, priceVersion: "v7", text: "7 units", startAt: at };+ const a = account();+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "credits" });+ const id = idOf(r);+ expect(tile(id)).toMatch(/^In line · starts in about \d+ (h|min)$/);+ const h = heldOf(id)!;+ expect(h).toMatchObject({ reserved: 0, rank_rule: "release", start_at: at });+ expect(await release.releaseHeldRuns()).toBe(0);+ // Renewed: it reserves under its press's request id and enters the line.+ fake.refuse = null;+ expect(await release.releaseHeldRuns(at + 1)).toBe(1);+ expect(await until(() => taskOf(id))).toBeTruthy();+ expect([...fake.holds.values()].filter((x) => x.requestId === h.request_id).length).toBe(1);+ });++ it("a refusal for credit with nothing that renews in time stays a refusal, as before", async () => {+ fake.refuse = { code: "top-up", text: "This needs 7 units. You have 0." };+ fake.quoteAnswer = { allowed: false, amount: 7, priceVersion: "v7", text: "This needs 7 units. You have 0.", code: "top-up" };+ const a = account();+ const r = await press(a.cookie);+ expect(r.status).toBe(402);+ expect(r.body.held).toBeUndefined();+ });+});++describe("service blips (H3)", () => {+ it("A3: the service stops across a press: the run is made (no card, no toast), and reserves and enters at its press-time place once it is back", async () => {+ const was = { ...billing.RESERVE_INLINE };+ try {+ billing.RESERVE_INLINE.ms = 300;+ const a = account();+ // The policy is known (the service answered a moment ago).+ expect((await check(a.cookie)).status).toBe(200);+ fake.down = "error";+ const before = Date.now();+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "service" });+ const id = idOf(r);+ // "In line" with its place as if in line, never a bare "In line".+ expect(tile(id)).toMatch(/^(Next in line|In line · \d+(st|nd|rd|th))/);+ // Before Run, while the service is quiet: the last price it gave, and Run stays on.+ const quiet = await check(a.cookie);+ expect(quiet.body.quote).toMatchObject({ allowed: true, text: "7 units" });+ await tick();+ expect(taskOf(id)).toBeUndefined();+ const requestId = heldOf(id)!.request_id;+ expect(requestId).toBeTruthy();+ // Back: it reserves under its press's request id (one hold for the press) and enters the line.+ fake.down = false;+ const t = await until(() => taskOf(id));+ expect(t).toBeTruthy();+ expect(t!.rank_at).toBeLessThanOrEqual(before);+ const made = [...fake.holds.values()].filter((h) => h.requestId === requestId);+ expect(made.length).toBe(1);+ const g = db().prepare("SELECT json_extract(request_json, '$.hold') AS hold FROM generations WHERE id = ?").get(id) as { hold: string | null };+ expect(g.hold).toBeTruthy();+ } finally {+ Object.assign(billing.RESERVE_INLINE, was);+ }+ });++ it("the cap counts runs waiting for any reason: while the service is quiet, ten presses are taken and the 11th is turned down", async () => {+ const was = { ...billing.RESERVE_INLINE };+ try {+ billing.RESERVE_INLINE.ms = 100;+ const a = account();+ await check(a.cookie);+ fake.down = "error";+ for (let i = 0; i < 10; i++) {+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "service" });+ }+ const eleventh = await press(a.cookie);+ expect(eleventh.status).toBe(429);+ expect(eleventh.body.error).toBe(limits.POOL_LIMIT_WORDS.heldCap(10));+ } finally {+ Object.assign(billing.RESERVE_INLINE, was);+ }+ });++ it("a run cancelled while it waits for the service gives back any hold a try at the press made, by its request id", async () => {+ const was = { ...billing.RESERVE_INLINE };+ try {+ billing.RESERVE_INLINE.ms = 100;+ const a = account();+ await check(a.cookie);+ fake.down = "error";+ const r = await press(a.cookie);+ expect(r.body.held).toEqual({ reason: "service" });+ const requestId = heldOf(idOf(r))!.request_id!;+ await cancelGeneration(idOf(r));+ expect(heldOf(idOf(r))).toBeUndefined();+ const out = db().prepare("SELECT kind, payload_json FROM billing_outbox WHERE key = ?").get(`release:request:${requestId}`) as { kind: string; payload_json: string } | undefined;+ expect(out?.kind).toBe("release");+ expect(JSON.parse(out!.payload_json)).toEqual({ requestId, reason: "not-created" });+ } finally {+ Object.assign(billing.RESERVE_INLINE, was);+ }+ });++ it("H3p: while the service says runs here are paused, a press is taken and waits ('starts when a GPU is free')", async () => {+ fake.refuse = { code: "paused", text: "Runs on our GPUs are paused for now. Your own GPU or key still works." };+ const a = account();+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "service" });+ expect(tile(idOf(r))).toBe("In line · starts when a GPU is free");+ fake.refuse = null;+ expect(await until(() => taskOf(idOf(r)))).toBeTruthy();+ });++ it("a refusal once the service answers ends the run in plain words", async () => {+ const was = { ...billing.RESERVE_INLINE };+ try {+ billing.RESERVE_INLINE.ms = 200;+ const a = account();+ await check(a.cookie);+ fake.down = "error";+ const r = await press(a.cookie);+ expect(r.body.held).toEqual({ reason: "service" });+ fake.down = false;+ fake.refuse = { code: "closed", text: "Your account can't run on our GPUs right now. Your own GPU or key still works." };+ await until(() => getGeneration(idOf(r))!.status === "failed");+ expect(getGeneration(idOf(r))!.error).toBe("Sorry, this one couldn't be made.");+ expect(heldOf(idOf(r))).toBeUndefined();+ } finally {+ Object.assign(billing.RESERVE_INLINE, was);+ }+ });++ it("a policy without `held` (an older service): the press while it is down is refused as before", async () => {+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ fake.policy = { ...FAKE_POLICY, ttlS: 0 };+ billing.resetBillingCache();+ const wasRetry = { ...billing.RESERVE_RETRY };+ try {+ Object.assign(billing.RESERVE_RETRY, { forMs: 600, firstMs: 100 });+ const a = account();+ await check(a.cookie);+ fake.down = "error";+ const r = await press(a.cookie);+ expect(r.status).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ } finally {+ Object.assign(billing.RESERVE_RETRY, wasRetry);+ }+ });+});++describe("a deploy or crash between a run's row and its GPU task (C5, A18)", () => {+ it("the row waits in line again at its press-time place instead of failing, and its GPU task is made", async () => {+ const a = account();+ const made = await press(a.cookie);+ const src = db().prepare("SELECT * FROM generations WHERE id = ?").get(idOf(made)) as Record<string, unknown>;+ await cancelGeneration(idOf(made));+ // A row made three minutes ago whose GPU task never came (the app stopped in between).+ const id = `cut-${++n}`;+ const at = Date.now() - 3 * 60_000;+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at)+ VALUES (@id, NULL, @feature, NULL, @model_id, @engine, @provider, @op, @kind, 'queued', NULL, 'Submitting', @prompt, @request_json, '[]', NULL, 0, @at, @at)`,+ )+ .run({ ...src, id, at });+ const t = await until(() => taskOf(id));+ expect(t, JSON.stringify(getGeneration(id))).toBeTruthy();+ expect(getGeneration(id)!.status).not.toBe("failed");+ expect(t!.rank_at).toBeLessThanOrEqual(at);+ });++ it("a GPU task made for the row whose id never reached it stops, so the row runs once", async () => {+ const a = account();+ const made = await press(a.cookie);+ const first = await until(() => taskOf(idOf(made)));+ const src = db().prepare("SELECT * FROM generations WHERE id = ?").get(idOf(made)) as Record<string, unknown>;+ await cancelGeneration(idOf(made));+ const id = `cut-${++n}`;+ const at = Date.now() - 3 * 60_000;+ // Its row and a waiting GPU task for it, but the row never got the task's id (the app stopped in between).+ const orphan = `orphan${String(++n).padStart(10, "0")}`;+ const d = db();+ d.transaction(() => {+ d.prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at)+ VALUES (@id, NULL, @feature, NULL, @model_id, @engine, @provider, @op, @kind, 'queued', NULL, 'Submitting', @prompt, @request_json, '[]', NULL, 0, @at, @at)`,+ ).run({ ...src, id, at });+ d.exec("CREATE TEMP TABLE orphan_task AS SELECT * FROM relay_tasks WHERE 0");+ d.prepare("INSERT INTO orphan_task SELECT * FROM relay_tasks WHERE id = ?").run(first!.id);+ d.prepare("UPDATE orphan_task SET id = ?, generation_id = ?, state = 'waiting', created_at = ?, rank_at = ?").run(orphan, id, at, at);+ d.exec("INSERT INTO relay_tasks SELECT * FROM orphan_task; DROP TABLE orphan_task");+ })();+ const fresh = () => d.prepare("SELECT id FROM relay_tasks WHERE generation_id = ? AND id != ? AND state != 'canceled'").get(id, orphan) as { id: string } | undefined;+ expect(await until(fresh), "a new GPU task for the row").toBeTruthy();+ expect((d.prepare("SELECT state FROM relay_tasks WHERE id = ?").get(orphan) as { state: string }).state).toBe("canceled");+ expect(getGeneration(id)!.status).not.toBe("failed");+ });+});++describe("two app processes and a restart", () => {+ it("a run another process is releasing is left to it until its lease ends; holds survive a restart", async () => {+ const a = account();+ const [one] = [await press(a.cookie), await press(a.cookie)];+ const third = await press(a.cookie);+ const run = heldOf(idOf(third))!.run_id;+ db().prepare("UPDATE pool_holds SET holder = 'other:1', lease_until = ? WHERE run_id = ?").run(Date.now() + 60_000, run);+ await stop([idOf(one)]);+ expect(await release.releaseHeldRuns()).toBe(0);+ expect(taskOf(idOf(third))).toBeUndefined();+ // That process stopped: its lease ends, and this one (a new process after a restart) releases it.+ db().prepare("UPDATE pool_holds SET lease_until = ? WHERE run_id = ?").run(Date.now() - 1, run);+ globalThis.__fuobeLeaseToken = undefined;+ expect(await release.releaseHeldRuns()).toBe(1);+ expect(await until(() => taskOf(idOf(third)))).toBeTruthy();+ // Released once: a second turn finds nothing to release.+ expect(await release.releaseHeldRuns()).toBe(0);+ });+});++describe("the studio's own limit of runs at once, while hosted runs are on (C6)", () => {+ it("counts runs on the account's own GPU or key and its light work, never its other runs on this install's GPUs", () => {+ const a = account();+ const row = (id: string, extra: Record<string, unknown>) =>+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at)+ VALUES (?, NULL, 'image', NULL, 'oss-z-image-turbo', 'open', 'comfyui', 'generate', 'image', 'queued', NULL, NULL, 'a fox', ?, '[]', NULL, 0, ?, ?)`,+ )+ .run(id, JSON.stringify({ ...IMAGE, account: a.id, ...extra }), Date.now(), Date.now());+ row(`own-${++n}`, {});+ row(`site-${++n}`, { place: "pool" });+ row(`site-${++n}`, { place: "pool" });+ row(`light-${++n}`, { place: "pool", light: true });+ expect(limits.ownActiveRuns(a.id)).toBe(2);+ expect(limits.accountActiveRuns(a.id)).toBe(4);+ });+});++describe("hold shapes", () => {+ it("the account's own limits enter at the back; the system's keep the press; the service reserves later", () => {+ expect(holds.holdShape({})).toBeNull();+ expect(holds.holdShape({ limit: { reason: "mine" } })).toMatchObject({ reason: "mine", rankRule: "release", reserved: true, checked: true });+ expect(holds.holdShape({ wait: { reason: "today", startAt: 86_400_000 } })).toMatchObject({ reason: "today", rankRule: "press", reserved: true, startAt: 86_400_000 });+ expect(holds.holdShape({ wait: { reason: "service", requestId: "r_1" } })).toMatchObject({ reason: "service", rankRule: "press", reserved: false, requestId: "r_1" });+ expect(holds.holdShape({ limit: { reason: "mine" }, wait: { reason: "today", startAt: 86_400_000 } })).toMatchObject({ reason: "today", rankRule: "release" });+ expect(holds.holdShape({ unchecked: true })).toMatchObject({ reason: "service", checked: false, reserved: true });+ expect(holds.startReason(2 * 86_400_000)).toBe("today");+ expect(holds.startReason(2 * 86_400_000 + 60_000)).toBe("hour");+ });+});diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 612bc86b..bbb5947e 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -260,7 +260,7 @@ describe("runs at once on this install's GPUs", () => {expect(kept()).toBe(3);});- it("runs on the account's own GPU never count against the policy, and keep the studio's own limit of 4", async () => {+ it("runs on the account's own GPU never count against the policy, and keep the studio's own limit of 4 (counting runs there only)", async () => {withBilling({ limits: { activeRuns: 1, waiting: 0, runsPerHour: 0 } });const a = account({ gpu: "online" });for (let i = 0; i < 3; i++) {@@ -273,9 +273,15 @@ describe("runs at once on this install's GPUs", () => {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.+ // The studio's own 4 counts the runs on its own GPU or key only while hosted runs are on: a fourth there is made,+ // a fifth is refused in today's words.+ const fourth = await post(IMAGE, a.cookie);+ expect(fourth.status, JSON.stringify(fourth.body)).toBe(201);+ expect(limits.ownActiveRuns(a.id)).toBe(4);+ expect(limits.accountActiveRuns(a.id)).toBe(5);const fifth = await post(IMAGE, a.cookie);expect(fifth.status).toBe(429);+ expect(fifth.body.error).toBe(ACCOUNT_MESSAGES.activeRuns);});it("a press of Run is kept only for a run on this install's GPUs: on the account's own GPU each send makes its run, as before", async () => {diff --git a/tests/self-host-unchanged.test.ts b/tests/self-host-unchanged.test.tsindex 7778d3b5..e20d9ea3 100644--- a/tests/self-host-unchanged.test.ts+++ b/tests/self-host-unchanged.test.ts@@ -266,4 +266,33 @@ describe("a self-hosted install with hosted runs off", () => {expect(retryRequest({ request }, false)).toBe(request);expect(pickerRules({ gpu: { connected: true }, pool: { deny: ["x"] } })).toBeUndefined();});++ it("runs that wait to enter the line: none is ever made, a run cut off before it started fails in today's words, and the limit of 4 counts every run", async () => {+ const { db } = await import("@/server/db");+ const { ensureRunner } = await import("@/server/generations");+ const { accountActiveRuns, ownActiveRuns } = await import("@/server/pool-limits");+ const a = auth.createAccount("[email protected]", "long enough");+ const row = (id: string, place: "pool" | null, at: number) =>+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at)+ VALUES (?, NULL, 'image', NULL, 'oss-z-image-turbo', 'open', 'comfyui', 'generate', 'image', 'queued', NULL, 'Submitting', 'a fox', ?, '[]', NULL, 0, ?, ?)`,+ )+ .run(id, JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", account: a.id, ...(place && { place }) }), at, at);+ // The studio's own limit of runs at once counts every run of the account, wherever it goes, as before.+ row("self-host-own-1", null, Date.now());+ row("self-host-site-1", "pool", Date.now());+ expect(ownActiveRuns(a.id)).toBe(accountActiveRuns(a.id));+ expect(ownActiveRuns(a.id)).toBe(2);+ // Rows whose GPU task never came (the app stopped in between), three minutes old: both fail as before, nothing waits.+ const old = Date.now() - 3 * 60_000;+ db().prepare("UPDATE generations SET created_at = ?, updated_at = ? WHERE id IN ('self-host-own-1', 'self-host-site-1')").run(old, old);+ ensureRunner();+ await globalThis.__fuobeRunner?.tick();+ for (const id of ["self-host-own-1", "self-host-site-1"]) {+ const g = db().prepare("SELECT status, error FROM generations WHERE id = ?").get(id) as { status: string; error: string };+ expect(g).toEqual({ status: "failed", error: "This run stopped before it started. Press Retry." });+ }+ expect((db().prepare("SELECT COUNT(*) AS n FROM pool_holds").get() as { n: number }).n).toBe(0);+ });});