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
Hosted runs: one press of Run makes one run, and a reserve never waits past 40 s
Adarshe63a40247252
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex f951cfae..cf5fcb55 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -29,8 +29,8 @@ twice: the service must treat a repeated call (the same `requestId`, or the same| `GET /v1/policy?account=<id>` | 1 s | before a run on this install's GPUs, and for the status (cached for the answer's `ttlS`) || `GET /v1/policy` | 1 s | a guest's status and price check: the policy for someone not signed in (cached the same way) || `POST /v1/quote` | 1 s | the price check before Run (`POST /api/generations?preview=1`), asked again 300 ms after each change |-| `POST /v1/reserve` | 2 s a try; with no answer, tried again with the same `requestId` for up to 60 s (backoff from 0.5 s, doubling, up to 8 s) | just before the run's rows are made |-| `POST /v1/release` | 5 s, through the outbox | the rows couldn't be made after a reserve |+| `POST /v1/reserve` | 2 s a try; with no answer, a 5xx or a 429, tried again with the same `requestId` for up to 40 s in all, the last try included (backoff from 0.5 s, doubling, up to 8 s). Any other answer is not tried again. | just before the run's rows are made |+| `POST /v1/release` | 5 s, through the outbox | the rows couldn't be made after a reserve; or a reserve was given up after a try that may have made a hold (sent a minute later) || `POST /v1/settle` | 5 s, through the outbox | each row that succeeded || `POST /v1/refund` | 5 s, through the outbox | each row that failed, was stopped, or was removed by an output check || `GET /v1/balance?account=<id>` | 1 s | the balance pill and the account menu's balance (cached 10 s) |@@ -110,14 +110,15 @@ run named no place, Fuobe asks (409, `code: "own-gpu-offline"`, header `x-fuobe-to this install's GPUs, but only for a run this install's GPUs would take. Any other run goes to the account's own GPU,as before. While the policy is cached, a run on an account's own GPU never waits for the service; when a policy callgets no answer, the last answer (or none) stands for 5 seconds (60 for a guest) before the service is asked again. The-last answer the service gave stands for up to 10 minutes while it doesn't answer; after that, runs on this install's-GPUs wait until it answers again.+last answer the service gave stands for up to 10 minutes while it doesn't answer. After that, a run on this install's+GPUs is refused in plain words (503, "Try again in a moment."), and the price check turns Run off until the service+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/release` | `{ holdId, reason: "not-created" }` | `{ ok: true }` |+| `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 }` || `GET /v1/balance` | | `{ amount, chip, text, sub?, refillAt?, detail: { label, text }[], action?, offer? }` |@@ -132,6 +133,16 @@ estimate. A quote with `allowed: false` turns Run off and puts its `text` in theor a chain's later step), so Run never fails on them once pressed. The page asks for a quote again by itself: every15 s while it is refused, every 30 s while it is allowed, and at once when a run starts or ends.+`requestId` names one press of Run. The page sends an id with each press, and sends the same press again when its+answer is lost on the way (the network dropped, or a proxy in between gave up on a slow answer). Fuobe makes the+reserve's `requestId` from the account and that id, so every send of one press reserves under one id, and no other+account's press can name it. Fuobe makes the run once: a resend gets the run the first send made. A request with no+page id (a script) reserves under an id of its own.++A release names the hold, or, when no try of a reserve got an answer that said what happened, the reserve's+`requestId`. The service releases whatever it holds for that id, and nothing when it holds none. Fuobe sends a release+by `requestId` a minute after it gave up, so the reserve comes first. A resend of that press is refused at once.+`shown` is the price the person saw before pressing Run. A service must never charge more than it: when the price wouldbe higher, it refuses with `price-changed` and the new quote, and the person sees the new price before running again.@@ -204,6 +215,6 @@ process saves a finished run's results.|---|---|| 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 60 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, 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. |The service's address and its errors are written to the server's log only. A browser never sees them.diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 4d5fdb86..ec95eb1e 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -25,11 +25,13 @@ 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 } from "@/server/billing";+import { BILLING_HEADER, BILLING_WAIT } from "@/server/billing";import { queueRelease } from "@/server/billing-outbox";import { runOnPool } from "@/server/hosted";import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";import { withRunStamp, type RunStamp } from "@/server/run-stamp";+import { hostedRunsOn } from "@/server/hosted-switch";+import { notePress, pressSeen, readPressId } from "@/server/run-requests";/*** List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,@@ -115,6 +117,17 @@ export async function POST(request: Request) {if (account) unhit(`run:${account.id}`);return refuse(r.status, r.body.error, r.body, r.headers);};+ // With hosted runs on, an account's press of Run is made once however often the page sends it (run-requests.ts): a+ // resend gets the run the first one made, and one that was refused because the billing service didn't answer is+ // refused again (a new press starts afresh).+ const pressId = account && !preview && hostedRunsOn() ? readPressId(body) : null;+ const paused = () => refuse(503, BILLING_WAIT.run, { code: "paused" }, { [BILLING_HEADER]: "paused" });+ const madeAlready = (ids: string[]) => Response.json({ items: ids.map((id) => getGeneration(id)).filter((g) => !!g) }, { status: 201 });+ if (account && pressId) {+ const seen = pressSeen(account.id, pressId);+ if (seen === "gave-up") return paused();+ if (seen) return madeAlready(seen.ids);+ }const notes: string[] = [];if (account && !preview) {// Room on the server, room in the account's files, and a fair share of runs.@@ -247,7 +260,7 @@ export async function POST(request: Request) {// 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 }) };} else if (onPool) {- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps);+ const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, pressId);if (!held.ok) return refusedBy(held.refusal);stamp = held.stamp;} else if (mod.checkOutputs) stamp = { checkOutputs: true };@@ -263,15 +276,31 @@ export async function POST(request: Request) {// sent until they are kept.const pool = onPool;const admitted = inScope(() => {- const r = admitRun({ accountId: account.id, pool: pool && !pool.light ? { policy: pool.policy, addr } : null }, () => {- 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" });- return run;- });+ const r = admitRun(+ {+ accountId: account.id,+ pool: pool && !pool.light ? { policy: pool.policy, addr } : null,+ // A resend of this press that got here first made the run (or gave up): nothing is made twice.+ ...(pressId && { prior: () => pressSeen(account.id, pressId) }),+ },+ () => {+ 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" });+ if (pressId) notePress(account.id, pressId, run.value.map((g) => g.id), stamp?.hold ?? null);+ return run;+ },+ );if (r.ok) r.value.start();return r;});+ if (!admitted.ok && "prior" in admitted) {+ unhit(`run:${account.id}`);+ const prior = admitted.prior;+ // The service gives one press one hold; a different one (a service that made a second) goes back.+ if (stamp?.hold && (prior === "gave-up" || stamp.hold !== prior.hold)) queueRelease(stamp.hold);+ return prior === "gave-up" ? paused() : madeAlready(prior.ids);+ }if (!admitted.ok) {unhit(`run:${account.id}`);if (stamp?.hold) queueRelease(stamp.hold);diff --git a/src/lib/api.ts b/src/lib/api.tsindex 03559ac3..f306aed3 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -540,16 +540,44 @@ export function useMakingPoolRuns(): { at: number; request: GenerationRequest }[return pending.filter((p): p is { at: number; request: GenerationRequest } => goesToPool(p.request));}+/** A new id for one press of Run: every send of that press carries it, so the studio makes its run once. */+export function newPressId(): string {+ const c = globalThis.crypto;+ if (typeof c?.randomUUID === "function") return c.randomUUID();+ const b = new Uint8Array(16);+ if (typeof c?.getRandomValues === "function") c.getRandomValues(b);+ else for (let i = 0; i < b.length; i++) b[i] = Math.floor(Math.random() * 256);+ return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");+}++/** How often, and after how long, a press of Run whose answer was lost on the way is sent again (the same press). */+export const PRESS_RESEND = { times: 2, afterMs: 1500 };++/**+ * Send one press of Run. A run on this studio's GPUs whose answer is lost on the way (the network dropped, or a proxy in+ * between gave up on a slow answer: 502, 504) is sent again with the same press id, and the studio answers with the run+ * the first send made (it makes one run, and sets its price aside once). Other runs are sent once, as before.+ */+export async function sendPress(send: () => Promise<Response>, again: boolean, wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))): Promise<Response> {+ for (let i = 0; ; i++) {+ const last = !again || i >= PRESS_RESEND.times;+ try {+ const res = await send();+ if (last || (res.status !== 502 && res.status !== 504)) return res;+ } catch (e) {+ if (last) throw e;+ }+ await wait(PRESS_RESEND.afterMs);+ }+}+export function useCreateGeneration() {const qc = useQueryClient();return useMutation({mutationKey: CREATE_GENERATION_KEY,mutationFn: async (req: GenerationRequest) => {- const res = await fetch("/api/generations", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(req),- });+ const body = JSON.stringify({ ...req, requestId: newPressId() });+ const res = await sendPress(() => fetch("/api/generations", { method: "POST", headers: { "Content-Type": "application/json" }, body }), goesToPool(req));// Stopped by the GPU pre-flight: the guided fix opens (watchGuestRefusals), so no error toast on top of it.if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {const b = (await res.json().catch(() => ({}))) as { error?: string };diff --git a/src/server/billing-outbox.ts b/src/server/billing-outbox.tsindex 6c8f4e6d..708a2e0c 100644--- a/src/server/billing-outbox.ts+++ b/src/server/billing-outbox.ts@@ -133,6 +133,23 @@ export function queueRelease(holdId: string, now = Date.now()): void {void sweepBilling();}+/**+ * How long a release by request id waits before it is sent: a reserve the app stopped waiting for may still be on its+ * way to the service, and the release must come after it.+ */+export const REQUEST_RELEASE_AFTER_MS = 60_000;++/**+ * A hold the app may not know of: a reserve whose tries got no clear answer (billing.ts reserve `unsure`), so nothing+ * was made. The service releases whatever it holds for that request id (none: nothing to do). Sent after+ * REQUEST_RELEASE_AFTER_MS.+ */+export function queueRequestRelease(requestId: string, now = Date.now()): void {+ db()+ .prepare("INSERT OR IGNORE INTO billing_outbox (key, kind, hold_id, payload_json, tries, next_at, created_at) VALUES (?, 'release', '', ?, 0, ?, ?)")+ .run(`release:request:${requestId}`, JSON.stringify({ requestId, reason: "not-created" }), now + REQUEST_RELEASE_AFTER_MS, now);+}+interface OutboxRow {key: string;kind: "settle" | "refund" | "release";diff --git a/src/server/billing.ts b/src/server/billing.tsindex 48b81724..24636fea 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -312,10 +312,23 @@ export async function quote(account: AccountFacts | null, run: RunFacts, queue:/*** 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. A press of Run waits through a short outage or a restart of the service, and the- * run starts with its place once it answers.+ * `mostMs`, for up to `forMs` in all, the last try's own time included. A press of Run waits through a short outage or+ * a restart of the service, and the run starts with its place once it answers. The whole wait stays well under the+ * time a front proxy gives a request (often 60 s), so the page always gets an answer.*/-export const RESERVE_RETRY = { forMs: 60_000, firstMs: 500, mostMs: 8_000 };+export const RESERVE_RETRY = { forMs: 40_000, firstMs: 500, mostMs: 8_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.+ */+const retryable = (e: unknown): boolean => {+ const status = e instanceof HookDown ? e.why.status : undefined;+ return status === undefined || status >= 500 || status === 429;+};++/** Might a failed try have made a hold at the service (it was sent, and no answer said it wasn't)? */+const mayHaveHeld = (e: unknown): boolean => !(e instanceof HookDown) || !(e.why.refused || (e.why.status !== undefined && e.why.status < 500));/** What a reserve sends (docs/billing-hook.md). */export interface ReserveInput {@@ -335,11 +348,14 @@ export interface ReserveInput {/*** Set the run's price aside before it is created. No service: null (no hold; the run is free). The service down: tried* 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. Never throws.+ * `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.*/-export async function reserve(input: ReserveInput): Promise<ReserveAnswer | null> {+export async function reserve(input: ReserveInput): Promise<(ReserveAnswer & { unsure?: boolean }) | null> {if (!billingConfigured()) return null;const start = Date.now();+ let unsure = false;for (let attempt = 0; ; attempt++) {try {const a = await call<ReserveAnswer>("POST", "/v1/reserve", input, BILLING_TIMEOUTS.reserve);@@ -347,12 +363,15 @@ export async function reserve(input: ReserveInput): Promise<ReserveAnswer | nullreturn a;} catch (e) {logDown(`reserve (try ${attempt + 1})`, e);+ if (mayHaveHeld(e)) unsure = true;+ if (!retryable(e)) break;}const wait = Math.min(RESERVE_RETRY.mostMs, RESERVE_RETRY.firstMs * 2 ** Math.min(attempt, 16));- if (Date.now() - start + wait > RESERVE_RETRY.forMs) break;+ // 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;await new Promise((r) => setTimeout(r, wait));}- return { ok: false, code: "paused", text: BILLING_WAIT.run };+ return { ok: false, code: "paused", text: BILLING_WAIT.run, ...(unsure && { unsure: true }) };}/** The HTTP status and header for a billing refusal (the generations route; docs/billing-hook.md). */diff --git a/src/server/db.ts b/src/server/db.tsindex 78602626..ebbcd988 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -845,10 +845,11 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (/*** The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and release- * the billing service must get, kept until it takes it (billing-outbox.ts). output_checks: each output of a run whose- * outputs the moderation service sees first, and where its check is. reports_inbox: "Report this result" when no- * moderation service is set, for the owner. Made here rather than as numbered migrations (other branches add those at- * the same time). Safe to run on every start; empty and unread while no service is set.+ * the billing service must get, kept until it takes it (billing-outbox.ts). run_requests: each press of Run an account+ * made with hosted runs on, by the page's id for it, and the run it made (run-requests.ts). output_checks: each output+ * of a run whose outputs the moderation service sees first, and where its check is. reports_inbox: "Report this+ * result" when no moderation service is set, for the owner. Made here rather than as numbered migrations (other+ * branches add those at the same time). Safe to run on every start; empty and unread while no service is set.*/export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (key TEXT PRIMARY KEY,@@ -883,6 +884,16 @@ export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox ();CREATE INDEX IF NOT EXISTS pool_admissions_account ON pool_admissions(account, at);CREATE INDEX IF NOT EXISTS pool_admissions_addr ON pool_admissions(addr, at);+ CREATE TABLE IF NOT EXISTS run_requests (+ account TEXT NOT NULL,+ request_id TEXT NOT NULL,+ ids_json TEXT,+ hold_id TEXT,+ gave_up INTEGER NOT NULL DEFAULT 0,+ at INTEGER NOT NULL,+ PRIMARY KEY (account, request_id)+ );+ CREATE INDEX IF NOT EXISTS run_requests_at ON run_requests(at);CREATE TABLE IF NOT EXISTS reports_inbox (id TEXT PRIMARY KEY,target_json TEXT NOT NULL,diff --git a/src/server/generations.ts b/src/server/generations.tsindex 032a56d4..126a5af1 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -525,6 +525,7 @@ export const ASSET_FREE: Record<string, string> = {"gpu_snapshots.report_json": "readiness built from that inventory","generations.external_meta_json": "the provider's job handles","billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file",+ "run_requests.ids_json": "the ids of the runs one press of Run made, never a file","reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file","admin_tokens.scopes_json": "an admin token's scope names","admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL",diff --git a/src/server/hook-client.ts b/src/server/hook-client.tsindex 1fe2aacf..ae41df44 100644--- a/src/server/hook-client.ts+++ b/src/server/hook-client.ts@@ -15,6 +15,11 @@ export class HookDown extends Error {constructor(readonly hook: string,detail: string,+ /**+ * What went wrong, as far as it is known: the HTTP status it answered, no answer in time, or no connection at all+ * (`refused`: nothing was sent, so the service did nothing).+ */+ readonly why: { status?: number; timedOut?: boolean; refused?: boolean } = {},) {super(`${hook}: ${detail}`);}@@ -94,14 +99,14 @@ export function hookCall<T>(c: HookCall): Promise<T> {let settled = false;// The whole call, connection to last byte, within timeoutMs.const timer = setTimeout(() => {- fail(`no answer in ${c.timeoutMs} ms from ${c.method} ${c.path}`);+ fail(`no answer in ${c.timeoutMs} ms from ${c.method} ${c.path}`, { timedOut: true });req.destroy();}, c.timeoutMs);- const fail = (why: string) => {+ const fail = (detail: string, why: HookDown["why"] = {}) => {if (settled) return;settled = true;clearTimeout(timer);- reject(new HookDown(c.hook, why));+ reject(new HookDown(c.hook, detail, why));};const req = lib.request(opts, (res) => {const chunks: Buffer[] = [];@@ -118,7 +123,7 @@ export function hookCall<T>(c: HookCall): Promise<T> {res.on("end", () => {if (settled) return;const status = res.statusCode ?? 0;- if (status < 200 || status > 299) return fail(`HTTP ${status} from ${c.method} ${c.path}`);+ if (status < 200 || status > 299) return fail(`HTTP ${status} from ${c.method} ${c.path}`, { status });try {const text = Buffer.concat(chunks).toString("utf8");const value = (text ? JSON.parse(text) : {}) as T;@@ -131,7 +136,8 @@ export function hookCall<T>(c: HookCall): Promise<T> {});res.on("error", (e) => fail(e.message));});- req.on("error", (e) => fail(e.message));+ // No connection (refused, no such socket): nothing reached the service.+ req.on("error", (e: NodeJS.ErrnoException) => fail(e.message, e.code === "ECONNREFUSED" || e.code === "ENOENT" ? { refused: true } : {}));if (payload) req.write(payload);req.end();});diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex cf1d4b06..11aaa012 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -34,6 +34,8 @@ import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRuimport { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";+import { queueRequestRelease } from "./billing-outbox";+import { notePressGaveUp, reserveRequestId } from "./run-requests";import type { RunStamp } from "./run-stamp";import { readRef } from "./storage";import { readSnapshot } from "./gpu/snapshots";@@ -412,7 +414,9 @@ export async function moderateRun(/*** 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).+ * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `pressId`: the page's+ * id for this press of Run (run-requests.ts), so every resend of it reserves under one request id; none (a script): an+ * id of this request's own. A reserve given up after a try that may have made a hold releases it by its request id.*/export async function reservePool(account: Account,@@ -421,13 +425,15 @@ export async function reservePool(shown: { amount: number; priceVersion: string } | null,checkOutputs: boolean,steps?: RunFacts["steps"],+ pressId: string | null = null,): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }) };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 = pressId ? reserveRequestId(account.id, pressId) : nanoid(16);const a = await reserve({- requestId: nanoid(16),+ requestId,account: accountFacts(account),run,queue: queueFacts(account.id, planned.route.endpoint),@@ -438,6 +444,11 @@ export async function reservePool(});if (!a) return { ok: true, stamp: base };if (!a.ok) {+ if (a.unsure) {+ // A try may have made a hold the app never heard of: it goes back, and a resend of this press is refused at once.+ if (pressId) notePressGaveUp(account.id, pressId);+ queueRequestRelease(requestId);+ }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);diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.tsindex b8f30258..6860d0e7 100644--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@ -163,13 +163,20 @@ export class AdmitRefused extends Error {* 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.+ * `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.*/-export function admitRun<T>(o: { accountId: string; pool: { policy: Pick<Policy, "limits">; addr: string | null } | null; now?: number }, make: () => T): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } {+export function admitRun<T, P = never>(+ o: { accountId: string; pool: { policy: Pick<Policy, "limits">; addr: string | null } | null; now?: number; prior?: () => P | null },+ make: () => T,+): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P } {const now = o.now ?? Date.now();const d = db();try {return d- .transaction((): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } => {+ .transaction((): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P } => {+ 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);if (refusal) return { ok: false, refusal };const value = make();diff --git a/src/server/run-requests.ts b/src/server/run-requests.tsnew file mode 100644index 00000000..de711bf1--- /dev/null+++ b/src/server/run-requests.ts@@ -0,0 +1,64 @@+import "server-only";+import crypto from "node:crypto";+import { db } from "./db";++/**+ * One press of Run, by the id the page sends with it (the same on every resend of that press). With hosted runs on, an+ * account's press makes its run once: a resend (an answer lost on the way, a proxy that cut a slow request short) gets+ * the run the first one made, and the external billing service sees one reserve request id for it, so it makes one hold.+ * Without hosted runs, nothing is noted and a run is made as before.+ */++/** A press id as a page sends it. */+const PRESS_ID = /^[A-Za-z0-9_-]{8,64}$/;++/** The press id beside a run request (the body's `requestId`), or null. */+export function readPressId(body: unknown): string | null {+ const v = (body as { requestId?: unknown } | null)?.requestId;+ return typeof v === "string" && PRESS_ID.test(v) ? v : null;+}++/** How long a press is remembered (a resend comes within a minute; a day is plenty). */+export const PRESS_KEEP_MS = 24 * 3_600_000;++/**+ * The reserve's request id for a press: made from the account and the page's id, so the same press always gives the+ * same one and no other account's press can ever name it.+ */+export const reserveRequestId = (accountId: string, pressId: string): string =>+ `r_${crypto.createHash("sha256").update(`${accountId}\n${pressId}`).digest("hex").slice(0, 32)}`;++/**+ * What a press made already: its run's rows (the first ones, as the route answered them) and the hold they carry;+ * "gave-up" when its reserve was given up (the billing service didn't answer in time and the press was refused); null+ * when it is new.+ */+export type PressSeen = { ids: string[]; hold: string | null } | "gave-up" | null;++export function pressSeen(accountId: string, pressId: string, now = Date.now()): PressSeen {+ const r = db()+ .prepare("SELECT ids_json, hold_id, gave_up FROM run_requests WHERE account = ? AND request_id = ? AND at > ?")+ .get(accountId, pressId, now - PRESS_KEEP_MS) as { ids_json: string | null; hold_id: string | null; gave_up: number } | undefined;+ if (!r) return null;+ if (r.gave_up) return "gave-up";+ let ids: string[] = [];+ try {+ ids = JSON.parse(r.ids_json ?? "[]") as string[];+ } catch {}+ return { ids, hold: r.hold_id };+}++/** Note the run a press made (inside the transaction that makes it), and forget presses older than a day. */+export function notePress(accountId: string, pressId: string, ids: string[], hold: string | null, now = Date.now()): void {+ const d = db();+ d.prepare("DELETE FROM run_requests WHERE at < ?").run(now - PRESS_KEEP_MS);+ d.prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, ?, ?, 0, ?)").run(accountId, pressId, JSON.stringify(ids), hold, now);+}++/**+ * Note a press whose reserve was given up: a resend of it is refused at once (its hold, if the service made one, is+ * being released by its request id), and a new press of Run starts afresh.+ */+export function notePressGaveUp(accountId: string, pressId: string, now = Date.now()): void {+ db().prepare("INSERT OR IGNORE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, NULL, NULL, 1, ?)").run(accountId, pressId, now);+}diff --git a/tests/helpers/standin-billing.ts b/tests/helpers/standin-billing.tsindex c726a173..fabfc000 100644--- a/tests/helpers/standin-billing.ts+++ b/tests/helpers/standin-billing.ts@@ -9,7 +9,7 @@** By default every run is free: the quote says "Free" with an amount of 0, and a reserve sets nothing aside. `priced`* gives runs a price (`price` per run). A reserve must name its request (`requestId`, else 400), and a repeated- * reserve with the same request id is the same hold. A hold is kept until its deadline (`closeBy`: the run's wait limit plus the time the+ * reserve with the same request id is the same hold. A release names the hold, or the reserve's request id. A hold is kept until its deadline (`closeBy`: the run's wait limit plus the time the* reserve's `timing` asks for, or `holdLifeMs` when it sends none or `readTiming` is off); a report after it is refused* and counted as late.*/@@ -57,8 +57,11 @@ export interface StandInBilling {holdLifeMs: number;/** Read the reserve's `timing` (on by default). Off: every hold lasts `holdLifeMs`, as a service with a fixed rule. */readTiming: boolean;- /** Wait this long before every answer. */+ /** Wait this long before every answer (only calls to `slowPath`, when it is set). */slowMs: number;+ slowPath: string | null;+ /** Answer every reserve with this HTTP status, doing nothing (null: answer it). */+ reserveStatus: number | null;/*** Hold every call to `path` until `count` of them have come in, or `maxMs` has passed since the first: then answer* them all. Null: answer each at once.@@ -122,6 +125,8 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringholdLifeMs: 2 * 3_600_000,readTiming: true,slowMs: 0,+ slowPath: null as string | null,+ reserveStatus: null as number | null,gather: null as StandInBilling["gather"],};@@ -151,7 +156,7 @@ export async function startStandInBilling(o: { socket?: boolean; token?: string} catch {}const url = req.url ?? "/";f.calls.push({ method: req.method ?? "GET", path: url, body, at: Date.now() });- if (f.slowMs) await new Promise((r) => setTimeout(r, f.slowMs));+ if (f.slowMs && (!f.slowPath || url.split("?")[0] === f.slowPath)) await new Promise((r) => setTimeout(r, f.slowMs));const g = f.gather;if (g && url.split("?")[0] === g.path) await gathered(g);const json = (status: number, v: unknown) => {@@ -165,6 +170,7 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringif (p === "/v1/health") return json(200, { ok: true });if (p === "/v1/policy") return json(200, f.policy);if (p === "/v1/quote") return json(200, quote());+ if (p === "/v1/reserve" && f.reserveStatus !== null) return json(f.reserveStatus, { error: "refused" });if (p === "/v1/reserve") {// Every reserve names its request (one per press of Run): a repeat with the same id is the same hold.const requestId = typeof body.requestId === "string" ? body.requestId : "";@@ -198,7 +204,7 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringreturn json(200, p === "/v1/settle" ? { ok: true, charged: h.amount } : { ok: true, text: "Not charged" });}if (p === "/v1/release") {- const h = f.holds.get(String(body.holdId));+ const h = typeof body.holdId === "string" ? f.holds.get(body.holdId) : [...f.holds.values()].find((x) => typeof body.requestId === "string" && x.requestId === body.requestId);if (h) h.released = true;return json(200, { ok: true });}diff --git a/tests/hosted-run-tiles.test.ts b/tests/hosted-run-tiles.test.tsindex 26598fed..1b16dee8 100644--- a/tests/hosted-run-tiles.test.ts+++ b/tests/hosted-run-tiles.test.ts@@ -18,7 +18,7 @@ vi.mock("next/navigation", () => ({const { POOL_WORDS } = await import("@/lib/relay");const { PendingTile, FailedTile, Feed } = await import("@/components/studio/feed");-const { CREATE_GENERATION_KEY, goesToPool } = await import("@/lib/api");+const { CREATE_GENERATION_KEY, goesToPool, newPressId, PRESS_RESEND, sendPress } = await import("@/lib/api");const { AiTag } = await import("@/components/studio/ai-tag");const { TooltipProvider } = await import("@/components/ui/tooltip");@@ -140,3 +140,59 @@ describe("a run on this studio's GPUs between Run and its answer", () => {expect(goesToPool(undefined)).toBe(false);});});++describe("one press of Run", () => {+ const answer = (status: number) => new Response(JSON.stringify({ items: [] }), { status });++ it("each press gets its own id, made of plain letters and digits", () => {+ const a = newPressId();+ const b = newPressId();+ expect(a).toMatch(/^[A-Za-z0-9_-]{8,64}$/);+ expect(b).not.toBe(a);+ });++ it("on this studio's GPUs, a press whose answer is lost on the way is sent again as it was, a few times at most", async () => {+ const waits: number[] = [];+ const wait = async (ms: number) => void waits.push(ms);+ // The network dropped, then a proxy gave up on a slow answer, then the answer came.+ const seen: string[] = [];+ const outcomes: (() => Response)[] = [+ () => {+ throw new TypeError("Failed to fetch");+ },+ () => answer(504),+ () => answer(201),+ ];+ const res = await sendPress(async () => (seen.push("send"), outcomes[seen.length - 1]()), true, wait);+ expect(res.status).toBe(201);+ expect(seen).toHaveLength(3);+ expect(waits).toEqual([PRESS_RESEND.afterMs, PRESS_RESEND.afterMs]);+ // Never more than PRESS_RESEND.times again: the last answer stands.+ let n = 0;+ const last = await sendPress(async () => (n++, answer(502)), true, wait);+ expect(last.status).toBe(502);+ expect(n).toBe(PRESS_RESEND.times + 1);+ // The studio's own answers (a refusal, a busy line) are never sent again.+ n = 0;+ expect((await sendPress(async () => (n++, answer(503)), true, wait)).status).toBe(503);+ expect(n).toBe(1);+ });++ it("every other run is sent once, as before", async () => {+ let n = 0;+ expect((await sendPress(async () => (n++, answer(504)), false, async () => {})).status).toBe(504);+ expect(n).toBe(1);+ n = 0;+ await expect(+ sendPress(+ async () => {+ n++;+ throw new TypeError("Failed to fetch");+ },+ false,+ async () => {},+ ),+ ).rejects.toThrow("Failed to fetch");+ expect(n).toBe(1);+ });+});diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 2e0e303a..6136292c 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -5,6 +5,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }import { runnerByHand, startAppProcess, tick, type AppProcess } from "./helpers/app-process";import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";import { plainFailure, RunWatch, type RunLike } from "./helpers/run-watch";+import { startFakeModeration } from "./helpers/fake-billing";import { FREE_RUNS_POLICY, startStandInBilling, type StandInBilling } from "./helpers/standin-billing";import { startStandInComfy, type StandInComfy } from "./helpers/standin-comfy";import { tempDir } from "./helpers/temp-dir";@@ -130,10 +131,10 @@ beforeEach(async () => {process.env.FUOBE_BILLING_URL = svc.address;process.env.FUOBE_BILLING_TOKEN = svc.token;delete process.env.FUOBE_HOSTED_FREE;- Object.assign(svc, { priced: false, slowMs: 0, gather: null, maxWaitMs: 20 * MIN, holdLifeMs: 105 * MIN, readTiming: true, policy: JSON.parse(JSON.stringify(FREE_RUNS_POLICY)) });+ Object.assign(svc, { priced: false, slowMs: 0, slowPath: null, reserveStatus: null, gather: null, maxWaitMs: 20 * MIN, holdLifeMs: 105 * MIN, readTiming: true, policy: JSON.parse(JSON.stringify(FREE_RUNS_POLICY)) });await svc.start();await comfy.start();- comfy.inner.restart({ stall: false, failNext: undefined, loseNext: 0, steps: 4, stepMs: 20 });+ comfy.inner.restart({ stall: false, failNext: undefined, loseNext: 0, steps: 4, stepMs: 20, previewPicture: undefined });settings();db().prepare("DELETE FROM relay_workers").run();db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();@@ -572,18 +573,165 @@ describe("a run's preview picture while it works", () => {await expectOnce(id, watch, { place: 1 });});- it("a picture that isn't a JPEG, is over 64 KB or comes within 2 s of the last is dropped; a person's own computer keeps none", () => {- const now = 1_000_000;- const t = { id: "t".repeat(16), pools: "pool", preview_at: null };+ it("a picture that isn't a JPEG, is over 64 KB or comes within 2 s of the last is dropped; a person's own computer keeps none", async () => {+ standInWorker();+ const { id, task } = await pressRun();+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'this-attempt' WHERE id = ?").run(task.id);+ const now = Date.now();+ const t = { ...taskOf(id)!, preview_at: null };expect(tasks.notePreview(t, Buffer.from("not a picture").toString("base64"), now)).toBe(false);expect(tasks.notePreview(t, jpegBase64(1, 70 * 1024), now)).toBe(false);expect(tasks.notePreview(t, "%%%", now)).toBe(false);expect(tasks.notePreview({ ...t, pools: null }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview: 0 }, jpegBase64(1), now)).toBe(false);expect(tasks.notePreview({ ...t, preview_at: now - 1000 }, jpegBase64(1), now)).toBe(false);expect(tasks.notePreview({ ...t, preview_at: now - 2000 }, jpegBase64(1), now)).toBe(true);tasks.dropProgress(t.id);});+ it("a step or a picture that comes after another app process sent the task back in line, or gave it to another attempt, leaves nothing behind", async () => {+ standInWorker();+ const { id, task } = await pressRun();+ const folder = path.join(tasks.relayDir(), "tasks", task.id);+ const left = () => (fs.existsSync(folder) ? fs.readdirSync(folder).filter((f) => f.startsWith("preview")) : []);+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'first-attempt' WHERE id = ?").run(task.id);+ const late = { ...taskOf(id)! };+ const now = Date.now();+ // The other process sent it back in line meanwhile.+ db().prepare("UPDATE relay_tasks SET state = 'waiting', lease_hash = NULL WHERE id = ?").run(task.id);+ tasks.noteProgress(task.id, { value: 3, max: 4 }, now, late.lease_hash);+ expect(tasks.notePreview(late, jpegBase64(1), now)).toBe(false);+ expect(taskOf(id)).toMatchObject({ progress_json: null, preview_at: null });+ expect(left()).toEqual([]);+ // Another worker took it again (a new lease): the first attempt's late report still leaves nothing.+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'second-attempt' WHERE id = ?").run(task.id);+ tasks.noteProgress(task.id, { value: 3, max: 4 }, now, late.lease_hash);+ expect(tasks.notePreview(late, jpegBase64(1), now)).toBe(false);+ expect(taskOf(id)).toMatchObject({ progress_json: null, preview_at: null });+ expect(left()).toEqual([]);+ // The attempt that holds it now is kept.+ tasks.noteProgress(task.id, { value: 1, max: 4 }, now, "second-attempt");+ expect(tasks.notePreview({ ...taskOf(id)! }, jpegBase64(2), now)).toBe(true);+ expect(tasks.taskProgress(taskOf(id)!)).toMatchObject({ value: 1, max: 4 });+ expect(left()).toEqual(["preview.jpg"]);+ // Ended: both go.+ tasks.endTask(task.id, "canceled");+ expect(left()).toEqual([]);+ });++ it("a task a worker claims again shows nothing of the attempt before it until the new one reports", async () => {+ const w = standInWorker();+ const { id, task } = await pressRun();+ const file = path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg");+ db()+ .prepare("UPDATE relay_tasks SET state = 'waiting', lease_hash = NULL, worker_id = NULL, progress_json = ?, preview_at = ? WHERE id = ?")+ .run(JSON.stringify({ value: 3, max: 4, at: Date.now() }), Date.now(), task.id);+ // Left from an attempt before (a process that stopped part way never dropped it).+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, Buffer.from(jpegBase64(1), "base64"));+ const d = driver(w);+ let atClaim: { progress_json: string | null; preview_at: number | null; file: boolean } | null = null;+ d.onStep((step) => {+ if (step === "claim" && !atClaim) atClaim = { ...taskOf(id)!, file: fs.existsSync(file) };+ });+ await workAll(d);+ expect(atClaim).toMatchObject({ progress_json: null, preview_at: null, file: false });+ expect((await ended(id))?.status).toBe("succeeded");+ });++ it("the worker's own runner sends ComfyUI's preview pictures with its reports: the Working tile shows the latest, at most one every 2 s", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 8;+ comfy.inner.opts.stepMs = 600;+ const frame = (step: number) => Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from(`step ${step} `), Buffer.alloc(1500, step)]);+ comfy.inner.opts.previewPicture = (step) => ({ type: "image/jpeg", data: frame(step) });+ // No help from the driver: the pictures are ComfyUI's, on its socket.+ const d = driver(w);+ const sent: number[] = [];+ const shown: string[] = [];+ d.onStep(async (step, _path, report) => {+ await tick();+ await watch.look();+ if (step !== "running") return;+ if (typeof report?.preview === "string") sent.push(Date.now());+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ if (g.preview) shown.push(Buffer.from(await (await previewGet(a1, g.preview)).arrayBuffer()).subarray(4, 9).toString("latin1"));+ });+ await workAll(d);+ expect(sent.length, "pictures sent").toBeGreaterThanOrEqual(2);+ for (let i = 1; i < sent.length; i++) expect(sent[i] - sent[i - 1]).toBeGreaterThanOrEqual(1500);+ expect(shown.length).toBeGreaterThan(0);+ for (const s of shown) expect(s).toBe("step ");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("ComfyUI's PNG previews go as JPEGs the worker program makes; with nothing to make them, none is sent and the run goes on", async () => {+ const w = standInWorker();+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 500;+ const types: string[] = [];+ const made = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from("made "), Buffer.alloc(500, 7)]);+ const shownWith = async (d: WorkerDriver, id: string) => {+ const shown: string[] = [];+ d.onStep(async (step) => {+ await tick();+ if (step !== "running") return;+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ if (g.preview) shown.push(Buffer.from(await (await previewGet(a1, g.preview)).arrayBuffer()).subarray(4, 9).toString("latin1"));+ });+ await workAll(d);+ expect((await ended(id))?.status).toBe("succeeded");+ return shown;+ };+ const first = await pressRun();+ const withMaker = workerDriver({ routes, token: w.token, comfy, jpeg: async (_data, type) => (types.push(type), new Uint8Array(made)) });+ drivers.push(withMaker);+ const shown = await shownWith(withMaker, first.id);+ expect(types.length).toBeGreaterThan(0);+ expect(new Set(types)).toEqual(new Set(["image/png"]));+ expect(shown.length).toBeGreaterThan(0);+ for (const s of shown) expect(s).toBe("made ");+ withMaker.stop();+ const second = await pressRun();+ expect(await shownWith(driver(w), second.id)).toEqual([]);+ });++ it("a run whose outputs the moderation service sees first shows no preview while it works: no address, and the picture's address answers nothing", async () => {+ const mod = await startFakeModeration();+ process.env.FUOBE_MODERATION_URL = mod.url;+ // An answer with no checkOutputs field: its outputs are checked first.+ mod.run = { allowed: true };+ try {+ const w = standInWorker();+ const { id, task } = await pressRun();+ expect(taskOf(id)!.preview, "its ComfyUI is asked for no previews").toBe(0);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 300;+ comfy.inner.opts.previewPicture = (step) => ({ type: "image/jpeg", data: Buffer.from(jpegBase64(step), "base64") });+ const d = driver(w);+ // A worker that sends a picture anyway.+ d.previews(() => jpegBase64(1));+ const looks: { preview?: string; route: number }[] = [];+ d.onStep(async (step) => {+ if (step !== "running") return;+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ looks.push({ preview: g.preview, route: (await previewGet(a1, `/api/generations/${id}/preview?at=1`)).status });+ });+ await workAll(d);+ expect(looks.length).toBeGreaterThan(0);+ expect(looks.every((l) => l.preview === undefined && l.route === 404), JSON.stringify(looks)).toBe(true);+ expect(taskOf(id)!.preview_at).toBeNull();+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg"))).toBe(false);+ // Its result shows once the check passes.+ await until(async () => (await tick(), getGeneration(id)?.status === "succeeded"));+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ await mod.close();+ }+ });+it("a worker's report with a picture over 64 KB is taken without the picture, and the run goes on", async () => {const w = standInWorker();const { id } = await pressRun();@@ -624,8 +772,8 @@ describe("the owner's own job on the workers", () => {});describe("a press of Run sent twice (a network drop at submit)", () => {- it("makes a second run and a second hold today: the run route reads no request id from the page, so each press reserves under an id of its own", async () => {- standInWorker();+ it("makes one run and one hold: the resend gets the run the first send made", async () => {+ const w = standInWorker();const holds = svc.holds.size;const rows = made();const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };@@ -634,12 +782,120 @@ describe("a press of Run sent twice (a network drop at submit)", () => {const again = await run(press);expect(first.status, JSON.stringify(first.body)).toBe(201);expect(again.status, JSON.stringify(again.body)).toBe(201);- expect(again.body.items![0].id).not.toBe(first.body.items![0].id);- expect(made() - rows, "runs made").toBe(2);- expect(svc.holds.size - holds, "holds made").toBe(2);- const ids = svc.callsOf("/v1/reserve").slice(-2).map((c) => (c.body as { requestId?: string }).requestId);- expect(new Set(ids).size).toBe(2);+ const id = first.body.items![0].id;+ expect(again.body.items!.map((g) => g.id)).toEqual(first.body.items!.map((g) => g.id));+ expect(made() - rows, "runs made").toBe(1);+ expect(svc.holds.size - holds, "holds made").toBe(1);+ // The reserve names the press, as the account's own (never the page's id as it is).+ const ids = svc.callsOf("/v1/reserve").slice(-1).map((c) => (c.body as { requestId?: string }).requestId);+ expect(ids[0]).toMatch(/^r_[0-9a-f]{32}$/);expect(ids).not.toContain(press.requestId);+ // Another account's press under the same page id is its own press.+ const theirs = await run(press, b1);+ expect(theirs.status, JSON.stringify(theirs.body)).toBe(201);+ expect(theirs.body.items![0].id).not.toBe(id);+ expect(svc.holds.size - holds, "holds made").toBe(2);+ const d = driver(w);+ const watch = watchOf(id);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a resend that comes while the first send still waits for the billing service makes no second run or hold", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const holds = svc.holds.size;+ const rows = made();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ await svc.downFor(3000);+ const first = run(press);+ await sleep(1000);+ // A proxy cut the first request short: the page sends the press again.+ const again = run(press);+ const [a, b] = await Promise.all([first, again]);+ expect(a.status, JSON.stringify(a.body)).toBe(201);+ expect(b.status, JSON.stringify(b.body)).toBe(201);+ expect(b.body.items!.map((g) => g.id)).toEqual(a.body.items!.map((g) => g.id));+ expect(made() - rows, "runs made").toBe(1);+ expect(svc.holds.size - holds, "holds made").toBe(1);+ });++ it("with hosted runs off, a press id changes nothing: each request makes its run, as before", async () => {+ delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_BILLING_URL;+ try {+ standInWorker();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const first = await run(press, owner);+ const again = await run(press, owner);+ expect(first.status, JSON.stringify(first.body)).toBe(201);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ expect(again.body.items![0].id).not.toBe(first.body.items![0].id);+ expect((db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE request_id = ?").get(press.requestId) as { n: number }).n).toBe(0);+ } finally {+ process.env.FUOBE_HOSTED_RUNS = "1";+ }+ });+});++describe("a reserve the billing service refuses or never answers", () => {+ it("an answer that would be the same on every try (a refused request) is a refusal in plain words at once, not after the whole wait", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const reserves = svc.callsOf("/v1/reserve").length;+ svc.reserveStatus = 401;+ const t = Date.now();+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(Date.now() - t).toBeLessThan(5000);+ expect(svc.callsOf("/v1/reserve").length - reserves, "tries").toBe(1);+ expect(made()).toBe(rows);+ // Nothing was held there, so nothing is released.+ expect((db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE key LIKE 'release:request:%' AND created_at >= ?").get(t) as { n: number }).n).toBe(0);+ });++ it("a press whose tries got no answer in time is refused within the whole wait, the hold the service made meanwhile goes back, and a resend of it is refused at once", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const was = { ...billing.RESERVE_RETRY };+ Object.assign(billing.RESERVE_RETRY, { forMs: 3000, firstMs: 200 });+ // The service takes each reserve, but answers only after the app stopped waiting.+ Object.assign(svc, { slowMs: 2500, slowPath: "/v1/reserve" });+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ try {+ const t = Date.now();+ const r = await run(press);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(Date.now() - t, "within the whole wait").toBeLessThanOrEqual(3000 + 500);+ expect(made()).toBe(rows);+ await sleep(600);+ const held = [...svc.holds.values()].filter((h) => h.account === A && !h.released && h.createdAt >= t);+ expect(held.length, "the service made a hold the app never heard of").toBe(1);+ // Its release waits a minute (a reserve still on its way is answered first), then goes.+ await outbox.drainOutbox(Date.now() + 1000);+ expect(held[0].released).toBe(false);+ await outbox.drainOutbox(Date.now() + outbox.REQUEST_RELEASE_AFTER_MS + 1000);+ expect(held[0].released, "released by its request id").toBe(true);+ expect(svc.callsOf("/v1/release").some((c) => (c.body as { requestId?: string }).requestId === held[0].requestId)).toBe(true);+ // The page sends the same press again: refused at once, nothing made, no new reserve.+ Object.assign(svc, { slowMs: 0, slowPath: null });+ const reserves = svc.callsOf("/v1/reserve").length;+ const again = await run(press);+ expect(again.status).toBe(503);+ expect(again.body.error).toBe(billing.BILLING_WAIT.run);+ expect(svc.callsOf("/v1/reserve").length).toBe(reserves);+ expect(made()).toBe(rows);+ // A new press works.+ expect((await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` })).status).toBe(201);+ } finally {+ Object.assign(billing.RESERVE_RETRY, was);+ }});});@@ -1256,6 +1512,50 @@ describe("two app processes on one database (a deploy's overlap)", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});+ it("a run stopped while its result is saved stays stopped, and the file saved for it goes (none is left filling the account's space)", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ // The stop lands while the result is saved: as its file is kept, the run is stopped (a cancel from another tab).+ db().exec(`CREATE TEMP TRIGGER stop_while_saved AFTER INSERT ON assets WHEN NEW.generation_id = '${id}' BEGIN UPDATE generations SET status = 'canceled' WHERE id = '${id}'; END`);+ try {+ await workAll(d);+ await until(() => assetsOf(id) === 0 && getGeneration(id)?.status === "canceled");+ for (let i = 0; i < 5; i++) await tick();+ } finally {+ db().exec("DROP TRIGGER IF EXISTS stop_while_saved");+ }+ expect(getGeneration(id)).toMatchObject({ status: "canceled" });+ expect(assetsOf(id)).toBe(0);+ });++ it("with the moderation service checking outputs, a run stopped while its result is saved is never brought back to wait for its check", async () => {+ const mod = await startFakeModeration();+ process.env.FUOBE_MODERATION_URL = mod.url;+ mod.run = { allowed: true, checkOutputs: true };+ try {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ db().exec(`CREATE TEMP TRIGGER stop_while_saved AFTER INSERT ON assets WHEN NEW.generation_id = '${id}' BEGIN UPDATE generations SET status = 'canceled' WHERE id = '${id}'; END`);+ try {+ await workAll(d);+ await until(() => assetsOf(id) === 0 && getGeneration(id)?.status === "canceled");+ for (let i = 0; i < 5; i++) await tick();+ } finally {+ db().exec("DROP TRIGGER IF EXISTS stop_while_saved");+ }+ expect(getGeneration(id)).toMatchObject({ status: "canceled" });+ expect((db().prepare("SELECT stage FROM generations WHERE id = ?").get(id) as { stage: string | null }).stage).toBeNull();+ expect((db().prepare("SELECT COUNT(*) AS n FROM output_checks WHERE generation_id = ?").get(id) as { n: number }).n).toBe(0);+ expect(assetsOf(id)).toBe(0);+ expect(mod.calls_of("/v1/check-output")).toEqual([]);+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ await mod.close();+ }+ });+it("a look at a run that comes back after another process saved it, or while another process saves it, changes nothing", async () => {const w = standInWorker();const { id } = await pressRun();