Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Hosted runs: limits counted with the run, the policy's default place, and chains priced once

Adarsh25ee57256911
diff --git a/docs/billing-hook.md b/docs/billing-hook.md
index 6960b65a..3e9adf4f 100644
--- a/docs/billing-hook.md
+++ b/docs/billing-hook.md
@@ -27,6 +27,7 @@ twice: the service must treat a repeated call (the same `requestId`, or the same
| Call | Timeout | When |
|---|---|---|
| `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, one retry with the same `requestId` | 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 |
@@ -48,6 +49,7 @@ type RunFacts = {
kind: "image" | "video" | "audio" | "text" | "model3d"; engine: "open" | "cloud"; provider: string;
jobs: number; outputsPerJob: number; megapixels: number | null; seconds: number | null; fps: number | null;
loras: number; inputs: { image: number; video: number; audio: number }; lane: string | null; providerUsd: number | null;
+ steps?: { model: string; op: string | null; kind: RunFacts["kind"]; jobs: number; lane: string | null }[];
};
type QueueFacts = { lane: string; ahead: number; etaS: number | null; workersOnline: number; nextOpenAt: number | null; mine: { waiting: number; running: number } };
type Action = { label: string; url: string }; // Fuobe opens url as given (https, or a path on this site)
@@ -59,11 +61,34 @@ type Policy = {
hosted: boolean; // may this account use this install's GPUs at all
pool: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; // models and apps there
uploads: { image: boolean; video: boolean; audio: boolean }; // which of its own files those runs may use
- limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number };
+ limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number; addressRunsPerHour?: number };
+ prefer?: "pool" | "own"; // the default place (absent: "own")
+ kinds?: { image?: boolean; video?: boolean; audio?: boolean; text?: boolean; model3d?: boolean }; // absent: all
links?: Action[]; notice?: { id: string; text: string; url?: string }; ttlS: number;
};
```
+`megapixels` is the size of each picture or frame the run makes, about: the canvas the request names, else its aspect
+ratio and resolution (the model's defaults where it names none). It is null for sound, text and 3D.
+
+`steps` lists every step of the run that uses this install's GPUs, the run's own step first: a chain (a film of
+several shots, a picture and then a step on it) is priced once, with one quote and one hold, for one press of Run.
+Steps that need no model (joins, trims) and text steps are left out: they cost nothing. Every step must be one the
+policy allows (`pool`, `kinds`), or the run isn't offered here.
+
+The policy's limits count runs on this install's GPUs only, never runs on the account's own GPU or key (those keep the
+install's own limits). A run is one press of Run: its jobs and chain steps count once. `activeRuns` counts runs going
+now (waiting or running), `waiting` those not started yet, `runsPerHour` those started in the last hour, and
+`addressRunsPerHour` those started from one client address in the last hour, across accounts (only when the install
+trusts its proxy, `FUOBE_TRUST_PROXY=1`; the address is kept as a salted hash for two hours). 0 or absent means no such
+limit. Fuobe counts them in its database together with making the run's rows, so requests that arrive together (or
+reach two servers during a deploy) never pass a limit together. They apply with or without a billing service.
+
+`prefer: "pool"` sends a run to this install's GPUs first even when the account's own GPU is online. A place the
+request names always wins, so the account can still pick its own GPU. When the account's own GPU doesn't answer and the
+run named no place, Fuobe asks (409, `code: "own-gpu-offline"`, header `x-fuobe-place-ask`) instead of moving the run
+to this install's GPUs.
+
| Call | Request | Answer |
|---|---|---|
| `POST /v1/quote` | `{ account: AccountFacts \| null, run: RunFacts, queue: QueueFacts \| null }` | `Quote` |
diff --git a/docs/public-signup.md b/docs/public-signup.md
index d74ddf22..ec91d109 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -360,8 +360,11 @@ Where the runs go:
With it on:
- An account with no GPU of its own can run in the studios (generations, camera motions, effects, apps).
-- An account whose own GPU is online runs there by default. The composer shows where a run goes ("Your GPU" or "This
- studio's GPUs"), and the person can pick either.
+- An account whose own GPU is online runs there by default, unless the billing service's policy puts the studio's
+ GPUs first (`prefer: "pool"`). The composer shows where a run goes ("Your GPU" or "This studio's GPUs"), and the
+ person can pick either. When the account's own GPU doesn't answer and the run named no place, the run is not moved
+ to the studio's GPUs: the page asks first, and runs it there if the person says so.
+- A guest is told what the billing service's policy for guests says (without one, what any account gets).
- Every other tool still needs the account's own GPU ("This tool doesn't run on your own GPU yet" stays as it is).
Image to 3D and extra LoRAs added to a request stay on the account's own GPU. So do clips and sound as inputs,
unless the policy and the studio's GPUs both take them.
@@ -381,7 +384,11 @@ With it on:
default; [gpu-workers.md](gpu-workers.md#the-queue)).
- In a run's `params.extra`, a file input is used only when the run sent that file itself. A name of a file in the
GPUs' folders is dropped. The graph is checked before it is queued or sent: it reads only the files this run sent.
-- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.
+- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space. The policy's limits
+ for runs on the studio's GPUs (runs at once, runs waiting, runs an hour, runs from one address an hour) count those
+ runs only, never runs on the account's own GPU or key. They are counted in the database as the run is made, so
+ requests sent together never pass them together. A chain counts once, and each of its steps must be one the policy
+ allows.
Two optional services can go with it:
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 2054c6ff..43525a4f 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -16,19 +16,19 @@ import { wantsVoiceFirst } from "@/lib/av/voice-first";
import { relightRunTitle } from "@/lib/relight/engine";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
import { accountInputProblem } from "@/server/account-inputs";
-import { db } from "@/server/db";
import { findView, requestViewKey } from "@/server/any-angle";
-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";
+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 { 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 { billingConfigured } from "@/server/billing";
+import { BILLING_HEADER } from "@/server/billing";
import { queueRelease } from "@/server/billing-outbox";
import { runOnPool } from "@/server/hosted";
-import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, type PlaceDecision, type Refusal } from "@/server/hosted-run";
+import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";
import { withRunStamp, type RunStamp } from "@/server/run-stamp";
/**
@@ -46,16 +46,6 @@ export async function GET(request: Request) {
return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: viewer.kind === "account" ? viewer.account.id : undefined }) });
}
-/** An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. */
-function activeRuns(accountId: string): number {
- 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') = ?",
- )
- .get(accountId) as { n: number };
- return r.n;
-}
-
/** What the sign-in proxy passes on of a request body (next.config.ts proxyClientMaxBodySize). */
const PROXY_BODY_BYTES = 4 * 1024 * 1024;
const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first (POST /api/uploads), then send their /api/files/ paths.";
@@ -130,7 +120,7 @@ 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 (activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
+ 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 ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {
@@ -179,13 +169,17 @@ export async function POST(request: Request) {
if (decision.kind === "refuse") return refusedBy(decision.refusal);
}
let onPool = decision.kind === "pool" ? decision : null;
- if (account && onPool && billingConfigured()) {
- // The billing service's limits for runs on this install's GPUs (never above the studio's own).
- const lim = onPool.policy.limits;
- if (lim.activeRuns > 0 && activeRuns(account.id) >= lim.activeRuns) {
+ // 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;
+ 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): said now, before anything is checked or set aside, and counted again as the run is made (admitRun).
+ const over = poolLimitRefusal(account.id, onPool.policy, addr);
+ if (over) {
unhit(`run:${account.id}`);
- return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
+ return refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) });
}
+ const lim = onPool.policy.limits;
if (lim.outputsPerRun > 0 && (req.params?.numOutputs ?? 1) > lim.outputsPerRun) {
req = { ...req, params: { ...req.params, numOutputs: lim.outputsPerRun } };
notes.push(ACCOUNT_MESSAGES.outputsCapped);
@@ -251,22 +245,39 @@ export async function POST(request: Request) {
const mod = await moderateRun(account, req, onPool?.planned ?? null, onPool ? "pool" : "own");
if (!mod.ok) return refusedBy(mod.refusal);
if (onPool) {
- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs);
+ const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps);
if (!held.ok) return refusedBy(held.refusal);
stamp = held.stamp;
} else if (mod.checkOutputs) stamp = { checkOutputs: true };
}
- // Counted again just before the run is stored, with nothing awaited in between: requests that arrived together all
- // passed the first count while the checks above waited.
- if (account && activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) {
- unhit(`run:${account.id}`);
- if (stamp?.hold) queueRelease(stamp.hold);
- return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });
- }
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>;
try {
- items = account && onPool ? runOnPool(account.id, () => withRunStamp(stamp ?? { place: "pool" }, make)) : stamp ? onOwn(() => withRunStamp(stamp, make)) : onOwn(make);
+ 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.
+ const pool = onPool;
+ const admitted = inScope(() => {
+ const r = admitRun({ accountId: account.id, pool: pool ? { 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;
+ });
+ if (r.ok) r.value.start();
+ return r;
+ });
+ if (!admitted.ok) {
+ unhit(`run:${account.id}`);
+ if (stamp?.hold) queueRelease(stamp.hold);
+ const r = admitted.refusal;
+ return refuse(r.status, r.error, { code: r.code }, r.code === "not-offered" ? { [BILLING_HEADER]: "not-offered" } : { "Retry-After": String(r.retryAfterS ?? 30) });
+ }
+ items = admitted.value.value;
+ } else items = make();
} catch (e) {
// Nothing was made: what was set aside goes back.
if (stamp?.hold) queueRelease(stamp.hold);
diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsx
index f54f97af..6c7aa976 100644
--- a/src/components/guest-prompt.tsx
+++ b/src/components/guest-prompt.tsx
@@ -27,6 +27,7 @@ import {
import { ConnectField, useSettings } from "@/components/connect-field";
import { FAL_KEYS_URL } from "@/lib/connections";
import { CLOUD_KEY } from "@/lib/your-keys";
+import { RUNS_CHANGED_EVENT } from "@/lib/guest-access";
/**
* The cards a public studio shows when something is refused (watchGuestRefusals): "Create a free
@@ -116,10 +117,16 @@ export function GuestPrompt() {
setGpuOnly(!!d.gpuOnly);
};
window.addEventListener(GUEST_PROMPT_EVENT, guest);
+ // A run started from a toast (not a page's own button): the lists show it.
+ const runs = () => {
+ for (const key of ["generations", "library", "library-facets"]) void qc.invalidateQueries({ queryKey: [key] });
+ };
window.addEventListener(CONNECT_GPU_EVENT, gpu);
+ window.addEventListener(RUNS_CHANGED_EVENT, runs);
return () => {
window.removeEventListener(GUEST_PROMPT_EVENT, guest);
window.removeEventListener(CONNECT_GPU_EVENT, gpu);
+ window.removeEventListener(RUNS_CHANGED_EVENT, runs);
};
}, [qc]);
return (
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 4d7d13e4..de6c4e78 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -590,11 +590,11 @@ export function Composer({ docked }: { docked: boolean }) {
const { mentions, sketched, signed } = prepare(draft);
// Hosted runs: an open model may run on this studio's GPUs. Its price there is the server's (the words of the
// studio's billing service, or free), asked again 300 ms after a change. With the account's own GPU online, that
- // GPU is the default; the person can pick either.
+ // GPU is the default, unless the studio puts its own GPUs first; the person can pick either.
const viewerInfo = status?.viewer;
const ownOnline = !!viewerInfo?.gpu.connected && !!viewerInfo.gpu.online;
const [runOnPick, setRunOn] = useState<RunOn | null>(null);
- const runOn: RunOn = runOnPick ?? (ownOnline ? "own" : "pool");
+ const runOn: RunOn = runOnPick ?? (ownOnline && viewerInfo?.prefer !== "pool" ? "own" : "pool");
const hostedHere = !!viewerInfo?.hosted && model?.engine === "open";
const poolPrice = hostedHere && runOn === "pool";
const priceBody = useSettled(poolPrice ? quoteBody(signed.request, runOn) : null);
diff --git a/src/components/studio/run-place-chip.tsx b/src/components/studio/run-place-chip.tsx
index a89951b8..72fa5c37 100644
--- a/src/components/studio/run-place-chip.tsx
+++ b/src/components/studio/run-place-chip.tsx
@@ -24,18 +24,24 @@ const ICONS: Record<RunPlace["where"], typeof Cloud> = { cloud: Cloud, gpu: Cpu,
* before, so a chip never says "Not available here" to the owner and then takes it back. With it, the account's own GPU
* and its first key (who its paid runs are billed to).
*/
-export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: boolean; payer: RunPlaceInput["payer"] } | null {
+export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: boolean; preferPool: boolean; payer: RunPlaceInput["payer"] } | null {
const hydrated = useHydrated();
const viewer = useViewer().data;
const status = useStatus().data;
if (!hydrated || !viewer) return null;
const audience: RunAudience = viewer.owner ? "owner" : viewer.account ? "account" : "guest";
const keys = status?.viewer?.keys ?? [];
- return { audience, gpu: !!status?.viewer?.gpu.connected, hosted: !!status?.viewer?.hosted, payer: keys.includes("fal") ? "fal" : (keys[0] ?? null) };
+ return {
+ audience,
+ gpu: !!status?.viewer?.gpu.connected,
+ hosted: !!status?.viewer?.hosted,
+ preferPool: !!status?.viewer?.hosted && status.viewer.prefer === "pool",
+ payer: keys.includes("fal") ? "fal" : (keys[0] ?? null),
+ };
}
/** The place and price for this viewer (null until the viewer is known). */
-export function useRunPlace(input: Omit<RunPlaceInput, "audience" | "format" | "gpu" | "hosted" | "payer">): RunPlace | null {
+export function useRunPlace(input: Omit<RunPlaceInput, "audience" | "format" | "gpu" | "hosted" | "preferPool" | "payer">): RunPlace | null {
const who = useRunViewer();
return who ? runPlace({ ...input, ...who, format: formatCost }) : null;
}
@@ -49,7 +55,7 @@ export function useRunPlace(input: Omit<RunPlaceInput, "audience" | "format" | "
*/
export function useOpenRunPlace(models: readonly string[], request: GenerationRequest | null, o: { count?: number; ownGpuOnly?: boolean } = {}): RunPlace | null {
const viewer = useRunViewer();
- const mayPool = !!viewer && !o.ownGpuOnly && viewer.audience !== "owner" && viewer.hosted && !viewer.gpu;
+ const mayPool = !!viewer && !o.ownGpuOnly && viewer.audience !== "owner" && viewer.hosted && (!viewer.gpu || viewer.preferPool);
const checked = useHostedQuote(useSettled(mayPool ? quoteBody(request, "pool") : null)).data;
if (!viewer) return null;
// This studio's GPUs only on the server's word (as the studio composer asks it): a model it doesn't offer there, or
diff --git a/src/lib/api.ts b/src/lib/api.ts
index f30b5438..515fc6b3 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -27,7 +27,8 @@ import {
} from "./generation-stream";
import { fetchWithin, READ_LIMIT_MS } from "./fetch-within";
import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";
-import { markRefusalShown, responseError } from "./refusals";
+import { markRefusalShown, refusalShown, responseError } from "./refusals";
+import { PLACE_ASK_HEADER, RUNS_CHANGED_EVENT } from "./guest-access";
import { postFile } from "./upload";
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
@@ -886,6 +887,8 @@ export interface StatusInfo {
paidAllowed?: boolean;
/** Hosted runs (FUOBE_HOSTED_RUNS=1): runs may go to this studio's GPUs, so a GPU of one's own is optional. */
hosted?: boolean;
+ /** "pool": runs go to this studio's GPUs first, even with its own GPU online (either can still be picked). */
+ prefer?: "pool";
/** The billing service's words for the account's balance (src/server/billing.ts). */
balance?: HostedBalance;
links?: BillingAction[];
@@ -1391,6 +1394,23 @@ export function refusalCard(kind: RefusalCard["kind"], at: { pathname: string; s
* card. Never on the sign-in page (refusalCard). Installed once. A refused upload's card says so ("add your own
* files"), not "run this".
*/
+/** Send a run again on this studio's GPUs (the toast a run that named no place gets when its own GPU didn't answer). */
+async function runOnPool(sent: string): Promise<void> {
+ let body: Record<string, unknown>;
+ try {
+ body = JSON.parse(sent) as Record<string, unknown>;
+ } catch {
+ return;
+ }
+ try {
+ const res = await window.fetch("/api/generations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, place: "pool" }) });
+ if (res.ok) window.dispatchEvent(new Event(RUNS_CHANGED_EVENT));
+ else await json(res).catch((e: unknown) => void (refusalShown(e) || toast.error((e as Error).message)));
+ } catch {
+ toast.error("That didn't start. Try again.");
+ }
+}
+
export function watchGuestRefusals(): void {
const w = window as typeof window & { __fuobeGuestFetch?: boolean };
if (w.__fuobeGuestFetch) return;
@@ -1431,6 +1451,17 @@ export function watchGuestRefusals(): void {
.then((b: Omit<BillingRefusalDetail, "code">) => window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing } })))
.catch(() => {});
}
+ // A run that named no place, whose account's own GPU didn't answer: offered on this studio's GPUs, never moved there
+ // by itself.
+ if (res.status === 409 && res.headers.get(PLACE_ASK_HEADER) === "1" && method === "POST" && requestPath(input) === "/api/generations" && typeof init?.body === "string") {
+ markRefusalShown(res);
+ const sent = init.body;
+ res
+ .clone()
+ .json()
+ .then((b: { error?: string }) => toast(b.error ?? "Your GPU isn't answering right now.", { action: { label: "Run on this studio's GPUs", onClick: () => void runOnPool(sent) } }))
+ .catch(() => {});
+ }
// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.
if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {
res
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index d4f0ee60..19519d9f 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -277,6 +277,15 @@ export const ACTIVE_RUNS_CODE = "active-runs";
export const OWN_GPU_TOOL_MESSAGE = "This tool isn't available here. Try the Image, Video or Audio studio, or an app, effect or camera motion.";
+/**
+ * The header of an account's run the server asks about instead of moving (409): its own GPU didn't answer, and the run
+ * named no place. The page offers to run it on this studio's GPUs (watchGuestRefusals).
+ */
+export const PLACE_ASK_HEADER = "x-fuobe-place-ask";
+
+/** Fired when a run started from a toast or a card (not from a page's own button), so the lists show it. */
+export const RUNS_CHANGED_EVENT = "fuobe:runs-changed";
+
/** Set on an account's refused run: the client shows "Connect your GPU to run this". */
export const CONNECT_GPU_HEADER = "x-fuobe-connect-gpu";
/** Beside it on the owner's refused run (Demo mode off, nothing connected): what would run it, "gpu", "key" or "any". */
diff --git a/src/lib/run-place.ts b/src/lib/run-place.ts
index 1bffab85..0445eac5 100644
--- a/src/lib/run-place.ts
+++ b/src/lib/run-place.ts
@@ -30,6 +30,8 @@ export interface RunPlaceInput {
gpu?: boolean;
/** Hosted runs are on: an open model may run on this studio's GPUs when the viewer has no GPU of its own. */
hosted?: boolean;
+ /** Runs go to this studio's GPUs first, even when the viewer has a GPU of its own (the studio's policy). */
+ preferPool?: boolean;
/** The price of a run on this studio's GPUs (the billing service's words; empty text: free), undefined while pricing. */
pool?: { text: string; sub?: string } | null;
/** The provider an account's paid run is billed to (its own key), or null when it has no key for this model. */
@@ -100,7 +102,7 @@ export function runPlace(input: RunPlaceInput): RunPlace {
const withModels = models.length ? ` with ${list(models)}` : "";
// Hosted runs: an account (or a guest, once signed up) with no GPU of its own runs open models on this studio's GPUs,
// at the billing service's price (the studio composer's "This studio's GPUs" chip).
- if (open && input.hosted && audience !== "owner" && !input.gpu) {
+ if (open && input.hosted && audience !== "owner" && (!input.gpu || input.preferPool)) {
const signup = audience === "guest";
const poolPrice = input.demo ? price : input.pool ? input.pool.text || "Free" : "";
const tip = input.demo
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 0871b516..e423f44a 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -12,7 +12,7 @@ import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
-import { balance as billingBalance, OPEN_POLICY, policy as billingPolicy, type Action, type Balance } from "./billing";
+import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";
import { poolReady } from "./hosted";
/**
@@ -181,6 +181,11 @@ export interface VisitorView {
* connecting a GPU of its own is optional.
*/
hosted?: boolean;
+ /**
+ * "pool": runs go to this install's GPUs first, even when the account's own GPU is online (the billing service's
+ * policy says so). Absent: its own GPU first, as before. Either can always be picked.
+ */
+ prefer?: "pool";
/** The billing service's words for the account's balance (billing.ts): the top bar's chip and the account menu. */
balance?: Balance;
/** Extra links the billing service sends for the menu. */
@@ -209,8 +214,10 @@ export async function visitorStatus(account: Account | null) {
};
// Hosted runs and the billing hook: nothing of either with them off.
if (poolReady()) {
- const p = account ? await billingPolicy(account.id) : OPEN_POLICY;
+ // A guest is told what the billing service's policy for guests says (no service: what any account gets).
+ const p = await billingPolicy(account?.id ?? null);
if (p?.hosted) viewer.hosted = true;
+ if (p?.hosted && p.prefer === "pool") viewer.prefer = "pool";
if (account && p?.links?.length) viewer.links = p.links;
if (account && p?.notice) viewer.notice = p.notice;
const b = account ? await billingBalance(account.id) : null;
diff --git a/src/server/billing.ts b/src/server/billing.ts
index 6acb2930..aa2a1412 100644
--- a/src/server/billing.ts
+++ b/src/server/billing.ts
@@ -46,6 +46,12 @@ export interface RunFacts {
inputs: { image: number; video: number; audio: number };
lane: string | null;
providerUsd: number | null;
+ /**
+ * Every step of the run that uses this install's GPUs, its own step first, so one quote and one hold cover a whole
+ * chain (one press of Run). Steps that need no model (joins, trims) and text steps are left out: they cost nothing.
+ * Absent: the run is its own one step.
+ */
+ steps?: { model: string; op: string | null; kind: RunFacts["kind"]; jobs: number; lane: string | null }[];
}
export interface QueueFacts {
@@ -92,7 +98,18 @@ export interface Policy {
pool: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } };
/** Which of its own files a run on this install's GPUs may use. */
uploads: { image: boolean; video: boolean; audio: boolean };
- limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number };
+ /**
+ * Limits on runs on this install's GPUs, counted on those runs only (never on runs on the account's own GPU or key).
+ * 0 or absent: no such limit. `addressRunsPerHour`: runs there from one client address an hour.
+ */
+ limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number; addressRunsPerHour?: 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"
+ * (or absent) for its own GPU, as before. A place the request names always wins.
+ */
+ prefer?: "pool" | "own";
+ /** Which kinds of run may use this install's GPUs (absent: all; a kind set to false: not that kind). */
+ kinds?: { image?: boolean; video?: boolean; audio?: boolean; text?: boolean; model3d?: boolean };
links?: Action[];
notice?: { id: string; text: string; url?: string };
ttlS: number;
@@ -203,18 +220,19 @@ export const OPEN_POLICY: Policy = {
};
/**
- * The account's policy (cached for its `ttlS`). No service: OPEN_POLICY. The service down: null (the caller treats
- * runs on this install's GPUs as paused).
+ * The account's policy (cached for its `ttlS`), or a guest's (`accountId` null: GET /v1/policy with no account). No
+ * service: OPEN_POLICY. The service down: null (the caller treats runs on this install's GPUs as paused).
*/
-export async function policy(accountId: string): Promise<Policy | null> {
+export async function policy(accountId: string | null): Promise<Policy | null> {
if (!billingConfigured()) return OPEN_POLICY;
const cache = (globalThis.__fuobeBillingPolicies ??= new Map());
- const hit = cache.get(accountId);
+ const key = accountId ?? "";
+ const hit = cache.get(key);
if (hit && Date.now() - hit.at < hit.ttlMs) return hit.policy;
try {
- const p = await call<Policy>("GET", `/v1/policy?account=${encodeURIComponent(accountId)}`, undefined, BILLING_TIMEOUTS.policy);
+ const p = await call<Policy>("GET", accountId ? `/v1/policy?account=${encodeURIComponent(accountId)}` : "/v1/policy", undefined, BILLING_TIMEOUTS.policy);
const ttlMs = Math.max(0, Math.min(3600, Number(p.ttlS) || 0)) * 1000;
- cache.set(accountId, { at: Date.now(), ttlMs, policy: p });
+ cache.set(key, { at: Date.now(), ttlMs, policy: p });
if (cache.size > 5000) cache.delete(cache.keys().next().value!);
return p;
} catch (e) {
diff --git a/src/server/db.ts b/src/server/db.ts
index e784c5b1..82c73a6d 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -865,6 +865,14 @@ export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (
);
CREATE INDEX IF NOT EXISTS output_checks_generation ON output_checks(generation_id);
CREATE INDEX IF NOT EXISTS output_checks_due ON output_checks(state, next_at);
+ CREATE TABLE IF NOT EXISTS pool_admissions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ account TEXT NOT NULL,
+ addr TEXT,
+ at INTEGER NOT NULL
+ );
+ 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 reports_inbox (
id TEXT PRIMARY KEY,
target_json TEXT NOT NULL,
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 6699e7cf..9b292f30 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -1,4 +1,5 @@
import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
@@ -1101,12 +1102,80 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =
// What the run leaves out or changes (LoRAs a cloud run can't carry, a length the API rounds) goes back
// with it, so the composer and API clients can say so; it isn't stored.
created.push(notes.length ? { ...toGeneration(row), notes } : toGeneration(row));
- if (!waits) void submit(id, route, providerId, plan, req, i);
+ const capture = captureStore().getStore();
+ capture?.ids.push(id);
+ if (!waits) {
+ const start = () => void submit(id, route, providerId, plan, req, i);
+ if (capture) capture.submits.push(start);
+ else start();
+ }
}
ensureRunner();
return created;
}
+interface RunCapture {
+ ids: string[];
+ submits: (() => void)[];
+}
+
+declare global {
+ var __fuobeRunCapture: AsyncLocalStorage<RunCapture> | undefined;
+}
+
+const captureStore = () => (globalThis.__fuobeRunCapture ??= new AsyncLocalStorage<RunCapture>());
+
+/**
+ * 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.
+ */
+export function captureRun<T>(fn: () => T): { value: T; ids: string[]; start: () => void } {
+ const cap: RunCapture = { ids: [], submits: [] };
+ const value = captureStore().run(cap, fn);
+ return { value, ids: cap.ids, 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. */
+export interface PlannedStep {
+ id: string;
+ modelId: string;
+ op: string;
+ provider: string;
+ kind: string;
+ presetId: string | null;
+ waits: boolean;
+}
+
+const ROLLED_BACK = Symbol("rolled back");
+
+/**
+ * Every row `fn` (createGenerations) would make, made and thrown away inside one transaction: nothing is kept and
+ * nothing is sent. A chain's later steps are planned exactly as the real run plans them.
+ */
+export function plannedSteps(fn: () => unknown): PlannedStep[] {
+ const d = db();
+ let steps: PlannedStep[] = [];
+ try {
+ d.transaction(() => {
+ steps = stepsOf(captureRun(fn).ids);
+ throw ROLLED_BACK;
+ })();
+ } catch (e) {
+ if (e !== ROLLED_BACK) throw e;
+ }
+ return steps;
+}
+
+/** The rows of a run (by id) as steps. */
+export function stepsOf(ids: string[]): PlannedStep[] {
+ const q = db().prepare("SELECT id, model_id, op, provider, kind, preset_id, depends_on FROM generations WHERE id = ?");
+ return ids.flatMap((id) => {
+ const r = q.get(id) as { id: string; model_id: string; op: string; provider: string; kind: string; preset_id: string | null; depends_on: string | null } | undefined;
+ return r ? [{ id: r.id, modelId: r.model_id, op: r.op, provider: r.provider, kind: r.kind, presetId: r.preset_id, waits: !!r.depends_on }] : [];
+ });
+}
+
/** Where each dependency's output goes: `chain`, or the single-image `chainFrom`. */
function slotsFor(req: GenerationRequest, n: number): ChainSlot[] {
// Dependencies beyond the listed slots are images (a chain shorter than dependsOn used to crash the launch).
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 29bbf1d6..5f519f04 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -20,8 +20,14 @@ import {
type RefuseCode,
type RunFacts,
} from "./billing";
-import { outputKind, previewGeneration } from "./generations";
-import { HOSTED_WORDS, inputCounts, poolAllows, poolReady, poolTakes, poolTakesFiles, queueFacts, runFacts, runOnPool } from "./hosted";
+import { getModel } from "@/lib/catalog";
+import { needsOf } from "@/lib/lanes";
+import { PLACE_ASK_HEADER } from "@/lib/guest-access";
+import { createGenerations, outputKind, plannedSteps, previewGeneration, type PlannedStep } from "./generations";
+import { loadIndex } from "./gpu/index-file";
+import { poolLane } from "./computer/pool";
+import { HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool } from "./hosted";
+import { withRunStamp } from "./run-stamp";
import { hostedRunsOn } from "./hosted-switch";
import { checkRun, moderationConfigured } from "./moderation";
import type { RunStamp } from "./run-stamp";
@@ -65,7 +71,85 @@ const billingRefusal = (code: RefuseCode | "price-changed", text: string, extra:
type Planned = ReturnType<typeof previewGeneration>;
/** The decision for an account's run: its own GPU or key as today, this install's GPUs, or a refusal. */
-export type PlaceDecision = { kind: "own" } | { kind: "pool"; planned: Planned; policy: Policy } | { kind: "refuse"; refusal: Refusal };
+export type PlaceDecision = { kind: "own" } | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"] } | { kind: "refuse"; refusal: Refusal };
+
+/** What an account whose own GPU didn't answer is asked, when its run named no place (never moved and charged unasked). */
+export const OWN_GPU_QUIET = "Your GPU isn't answering right now. Run this on this studio's GPUs instead, or try again when your GPU is back.";
+
+const askPlace = (): Refusal => ({ status: 409, body: { error: OWN_GPU_QUIET, code: "own-gpu-offline" }, headers: { [PLACE_ASK_HEADER]: "1" } });
+
+/** Does the policy put runs on this install's GPUs first, before the account's own GPU? */
+const prefersPool = (p: Policy | null | undefined): boolean => !!p?.hosted && p.prefer === "pool";
+
+/** May a run of this kind use this install's GPUs under the policy (`kinds` absent: every kind)? */
+export const kindAllowed = (p: Pick<Policy, "kinds">, kind: RunFacts["kind"]): boolean => p.kinds?.[kind] !== false;
+
+const stepEndpoint = (s: PlannedStep): string | undefined => {
+ const m = getModel(s.modelId);
+ return (m?.routes.find((r) => r.op === s.op && r.provider === s.provider) ?? m?.routes.find((r) => r.provider === s.provider))?.endpoint;
+};
+
+/**
+ * A step that needs no model and no graphics memory (a join, a trim, a mux): light work that costs nothing and that every
+ * policy allows. Text steps and steps made in the browser cost nothing either.
+ */
+function freeStep(s: PlannedStep): boolean {
+ if (s.provider === "llm" || s.provider === "local" || s.provider === "mock") return true;
+ if (s.provider !== "comfyui") return false;
+ const endpoint = stepEndpoint(s);
+ if (!endpoint) return false;
+ // A workflow that picks its graph at run time (`video-concat-{n}`): light when every graph it may pick is.
+ const index = loadIndex();
+ const [head, tail = ""] = endpoint.split("{n}");
+ const picks = endpoint.includes("{n}")
+ ? Object.keys(index.workflows).filter((id) => id.length > head.length + tail.length && id.startsWith(head) && id.endsWith(tail) && /^\d+$/.test(id.slice(head.length, id.length - tail.length)))
+ : [endpoint];
+ const needs = picks.map((id) => needsOf(index, id));
+ return needs.length > 0 && needs.every((x) => !!x && x.files.length === 0 && x.minVramBytes === 0);
+}
+
+/**
+ * Every row an account's run would make on this install's GPUs (a chain's later steps too), planned as the real run plans
+ * them and thrown away. Null when the request can't be made (the real run says why).
+ */
+export function poolSteps(accountId: string, req: GenerationRequest): PlannedStep[] | null {
+ try {
+ return runOnPool(accountId, () => withRunStamp({ place: "pool" }, () => plannedSteps(() => createGenerations(req))));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The first step of a run that this install's GPUs may not take under the policy (its model or app not offered, a kind
+ * the policy leaves out, a model no worker is allowed, a cloud model), in words; null when every step may run there.
+ */
+export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {
+ for (const s of steps) {
+ if (freeStep(s)) continue;
+ if (s.provider !== "comfyui" || s.kind === "model3d") return HOSTED_WORDS.notOffered;
+ if (!poolAllows(p, s.modelId, s.presetId) || !kindAllowed(p, s.kind as RunFacts["kind"])) return HOSTED_WORDS.notOffered;
+ if (!poolTakes(stepEndpoint(s))) return HOSTED_WORDS.notOffered;
+ }
+ return null;
+}
+
+/** The steps of a run that use this install's GPUs, for its one price: each model and operation once, with its rows. */
+export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]> {
+ const out = new Map<string, NonNullable<RunFacts["steps"]>[number]>();
+ for (const s of steps) {
+ if (freeStep(s)) continue;
+ const key = `${s.modelId} ${s.op}`;
+ const had = out.get(key);
+ if (had) {
+ had.jobs++;
+ continue;
+ }
+ const endpoint = stepEndpoint(s);
+ out.set(key, { model: s.modelId, op: s.op || null, kind: s.kind as RunFacts["kind"], jobs: 1, lane: poolOnWorkers() && endpoint && !endpoint.includes("{") ? poolLane(endpoint) : POOL_LANE });
+ }
+ return [...out.values()];
+}
/** Is the account's own GPU there to run now? */
async function ownGpuOnline(accountId: string): Promise<boolean> {
@@ -92,21 +176,31 @@ export async function decidePlace(account: Account, req: GenerationRequest, wish
}
if (planned.route.provider !== "comfyui") return { kind: "own" };
const hasGpu = !!accountGpu(account.id);
- if (hasGpu && wish !== "pool" && (await ownGpuOnline(account.id))) return { kind: "own" };
const p = await billingPolicy(account.id);
+ // Its own GPU first, unless the policy puts this install's first (a place the request names always wins).
+ if (hasGpu && wish !== "pool" && !prefersPool(p)) {
+ if (await ownGpuOnline(account.id)) return { kind: "own" };
+ // Its GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.
+ if (!wish) return { kind: "refuse", refusal: askPlace() };
+ }
if (!p) return { kind: "refuse", refusal: billingRefusal("paused", BILLING_PAUSED) };
if (!p.hosted) return { kind: "own" };
// From here on the run would be this install's: what it can't take there goes to the account's own GPU when it has one.
const notHere = (error: string): PlaceDecision => (hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });
if (outputKind(planned.op, planned.model) === "model3d") return hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, headers: {} } };
if (!poolAllows(p, planned.model.id, req.presetId)) return notHere(HOSTED_WORDS.notOffered);
+ if (!kindAllowed(p, outputKind(planned.op, planned.model))) return notHere(HOSTED_WORDS.notOffered);
// Nothing of this install's would ever run it (no worker is allowed its lane): never a run that waits for nothing.
if (!poolTakes(planned.route.endpoint)) return notHere(HOSTED_WORDS.notOffered);
if (req.loras?.length) return notHere(HOSTED_WORDS.loras);
const inputs = inputCounts(req);
const takes = (kind: "image" | "video" | "audio") => p.uploads[kind] && poolTakesFiles(kind);
if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return notHere(HOSTED_WORDS.inputs);
- return { kind: "pool", planned, policy: p };
+ // Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.
+ const steps = poolSteps(account.id, req);
+ const problem = steps && stepsProblem(p, steps);
+ if (problem) return notHere(problem);
+ return { kind: "pool", planned, policy: p, steps: steps ? pricedSteps(steps) : undefined };
}
/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */
@@ -173,14 +267,21 @@ 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).
*/
-export async function reservePool(account: Account, req: GenerationRequest, planned: Planned, shown: { amount: number; priceVersion: string } | null, checkOutputs: boolean): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {
+export async function reservePool(
+ account: Account,
+ req: GenerationRequest,
+ planned: Planned,
+ shown: { amount: number; priceVersion: string } | null,
+ checkOutputs: boolean,
+ steps?: RunFacts["steps"],
+): 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 a = await reserve({
requestId: nanoid(16),
account: accountFacts(account),
- run: runFacts(req, planned, kind),
+ run: { ...runFacts(req, planned, kind), ...(steps?.length && { steps }) },
queue: queueFacts(account.id, planned.route.endpoint),
shown: shown ?? { amount: 0, priceVersion: "" },
});
@@ -210,7 +311,8 @@ export async function reservePool(account: Account, req: GenerationRequest, plan
*/
export async function poolQuote(account: Account | null, asked: GenerationRequest, wish: PlaceWish): Promise<{ planned: Planned; quote: Quote } | null> {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return null;
- const p = account ? await billingPolicy(account.id) : null;
+ // A guest is priced under the billing service's policy for guests (none set: as an account would be, once signed up).
+ const p = account ? await billingPolicy(account.id) : billingConfigured() ? await billingPolicy(null) : null;
// Priced for the outputs it would make: the studio's cap per run, and the billing service's when lower.
const cap = Math.min(ACCOUNT_LIMITS.outputsPerRun, ...(billingConfigured() && p && p.limits.outputsPerRun > 0 ? [p.limits.outputsPerRun] : []));
const req = (asked.params?.numOutputs ?? 1) > cap ? { ...asked, params: { ...asked.params, numOutputs: cap } } : asked;
@@ -221,10 +323,14 @@ export async function poolQuote(account: Account | null, asked: GenerationReques
return null;
}
if (planned.route.provider !== "comfyui") return null;
- if (account && wish !== "pool" && accountGpu(account.id) && (await ownGpuOnline(account.id))) return null;
- if (p && (!p.hosted || !poolAllows(p, planned.model.id, req.presetId))) return null;
- if (!poolTakes(planned.route.endpoint)) return null;
+ if (account && wish !== "pool" && !prefersPool(p) && accountGpu(account.id) && (await ownGpuOnline(account.id))) return null;
const kind = outputKind(planned.op, planned.model);
- const q = await billingQuote(account ? accountFacts(account) : null, runFacts(req, planned, kind), queueFacts(account?.id ?? null, planned.route.endpoint));
+ if (p && (!p.hosted || !poolAllows(p, planned.model.id, req.presetId) || !kindAllowed(p, kind))) return null;
+ if (!poolTakes(planned.route.endpoint)) return null;
+ // Priced once for every step of a chain that uses this install's GPUs (a step it can't take there: not offered here).
+ const steps = account ? poolSteps(account.id, req) : null;
+ if (steps && p && stepsProblem(p, steps)) return null;
+ const facts = { ...runFacts(req, planned, kind), ...(steps && { steps: pricedSteps(steps) }) };
+ const q = await billingQuote(account ? accountFacts(account) : null, facts, queueFacts(account?.id ?? null, planned.route.endpoint));
return { planned, quote: q };
}
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
index 36683e2d..9307993e 100644
--- a/src/server/hosted.ts
+++ b/src/server/hosted.ts
@@ -1,5 +1,6 @@
import "server-only";
import { getModel } from "@/lib/catalog";
+import { computeDimensions } from "@/lib/comfy";
import type { GenerationRequest } from "@/lib/catalog/types";
import { billingConfigured, type Policy, type QueueFacts, type RunFacts } from "./billing";
import { lineFacts, poolLane, queueOfGeneration, workersAllowed } from "./computer/pool";
@@ -177,6 +178,23 @@ export function placeInLine(generationId: string): { place: number; etaSeconds:
return { place: before + 1, etaSeconds: typical === null ? null : Math.round(((before + 1) * typical) / 1000) };
}
+/**
+ * The megapixels of each picture or frame a request makes, about: the canvas it names (params.extra.width and height),
+ * else its aspect ratio and resolution (the model's defaults where it names none). Null for sound, text and 3D.
+ */
+export function requestMegapixels(req: GenerationRequest, kind: RunFacts["kind"], modelId: string): number | null {
+ if (kind !== "image" && kind !== "video") return null;
+ const extra = (req.params?.extra ?? {}) as Record<string, unknown>;
+ const w = Number(extra.width);
+ const h = Number(extra.height);
+ const model = getModel(modelId);
+ const size =
+ Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0
+ ? { width: w, height: h }
+ : computeDimensions(req.params?.aspectRatio ?? model?.defaults?.aspectRatio, req.params?.resolution ?? model?.defaults?.resolution, {});
+ return Math.round((size.width * size.height) / 10_000) / 100;
+}
+
/** The facts the billing service prices a run by (from a planned request: previewGeneration's answer). */
export function runFacts(
req: GenerationRequest,
@@ -197,7 +215,7 @@ export function runFacts(
provider: p.providerId,
jobs: p.jobs,
outputsPerJob: p.jobs > 0 ? Math.max(1, Math.round(p.outputs / p.jobs)) : 1,
- megapixels: null,
+ megapixels: requestMegapixels(req, kind, p.model.id),
seconds: req.params?.duration ?? (kind === "video" ? (model?.defaults?.duration ?? null) : null),
fps: req.params?.fps ?? null,
loras: p.loras.applied.length,
diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.ts
new file mode 100644
index 00000000..389817b9
--- /dev/null
+++ b/src/server/pool-limits.ts
@@ -0,0 +1,150 @@
+import "server-only";
+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 { db } from "./db";
+
+/**
+ * The limits on an account's runs, counted in SQLite so that requests that arrive together, in one process or in two
+ * (a deploy runs the old and the new server side by side for a moment), can never pass them together.
+ *
+ * - Every account run, wherever it goes: the studio's own limit of runs at once (ACCOUNT_LIMITS.activeRuns), as before.
+ * - A run on this install's GPUs (hosted runs): also the policy's limits, counted on runs there only, never on runs on
+ * the account's own GPU or its own key: runs at once (`activeRuns`), runs waiting in line (`waiting`), runs started in
+ * the last hour (`runsPerHour`), and runs started from one client address in the last hour (`addressRunsPerHour`).
+ * 0 or absent: no such limit.
+ *
+ * A run is one press of Run: its jobs and the steps its chains queue share a batch and count once.
+ *
+ * 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.
+ */
+
+const HOUR = 60 * 60_000;
+/** Started runs are kept this long for the hourly counts. */
+const KEEP_MS = 2 * HOUR;
+
+/** What a person reads when a limit on runs on this install's GPUs stops a run (plain words, no numbers of the studio's). */
+export const POOL_LIMIT_WORDS = {
+ active: (n: number) => `You have ${n} ${n === 1 ? "run" : "runs"} going. Start this one when one finishes.`,
+ 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.",
+};
+
+export interface LimitRefusal {
+ status: 429;
+ error: string;
+ code: string;
+ retryAfterS: number;
+}
+
+/** An account's runs going now (queued or running), wherever they run: a run's jobs and chain steps share a batch. */
+export function accountActiveRuns(accountId: string): number {
+ 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') = ?")
+ .get(accountId) as { n: number };
+ return r.n;
+}
+
+/** 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). */
+export function poolRunCounts(accountId: string): { active: number; waiting: number } {
+ const r = db()
+ .prepare(
+ `SELECT COUNT(*) AS active, COALESCE(SUM(CASE WHEN started = 0 THEN 1 ELSE 0 END), 0) AS waiting FROM (
+ SELECT COALESCE(g.batch_id, g.id) AS k, MAX(CASE WHEN r.started_at IS NOT NULL THEN 1 ELSE 0 END) AS started
+ FROM generations g LEFT JOIN generation_runs r ON r.id = g.id
+ WHERE g.status IN ('queued', 'running') AND json_extract(g.request_json, '$.account') = ? AND json_extract(g.request_json, '$.place') = 'pool'
+ GROUP BY k)`,
+ )
+ .get(accountId) as { active: number; waiting: number };
+ return { active: r.active, waiting: r.waiting };
+}
+
+/** The salt the client addresses are kept under: made once per install, never sent anywhere. */
+function salt(): string {
+ const d = db();
+ d.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('pool.addressSalt', ?)").run(crypto.randomBytes(32).toString("hex"));
+ return (d.prepare("SELECT value FROM settings WHERE key = 'pool.addressSalt'").get() as { value: string }).value;
+}
+
+/**
+ * The client's address as the hourly count keeps it (a salted hash, never the address), or null when clients can't be
+ * told apart (no trusted proxy: every request would count as one client).
+ */
+export function clientAddress(request: Request): string | null {
+ const key = LoginGuard.clientKey(request.headers);
+ if (key === LoginGuard.DIRECT) return null;
+ return crypto.createHmac("sha256", salt()).update(key).digest("hex").slice(0, 32);
+}
+
+const since = (column: "account" | "addr", value: string, from: number) =>
+ db().prepare(`SELECT COUNT(*) AS n, MIN(at) AS oldest FROM pool_admissions WHERE ${column} = ? AND at > ?`).get(value, from) as { n: number; oldest: number | null };
+
+/** Seconds until the oldest of an hour's runs leaves the hour. */
+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. */
+export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null, now = Date.now()): LimitRefusal | null {
+ 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 };
+ }
+ 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 (addrMax && addr) {
+ const h = since("addr", addr, now - HOUR);
+ if (h.n >= addrMax) return { status: 429, error: POOL_LIMIT_WORDS.address, code: "limit", retryAfterS: retryAfter(h.oldest, now) };
+ }
+ return null;
+}
+
+/** The studio's own limit of runs at once (every account run, wherever it goes), 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;
+}
+
+/** A refusal thrown inside admitRun's transaction, so nothing `make` wrote is kept. */
+export class AdmitRefused extends Error {
+ constructor(readonly refusal: LimitRefusal | { status: number; error: string; code: string; retryAfterS?: number }) {
+ super(refusal.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.
+ */
+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"] } {
+ const now = o.now ?? Date.now();
+ const d = db();
+ try {
+ return d
+ .transaction((): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } => {
+ 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();
+ if (o.pool) {
+ d.prepare("INSERT INTO pool_admissions (account, addr, at) VALUES (?, ?, ?)").run(o.accountId, o.pool.addr, now);
+ d.prepare("DELETE FROM pool_admissions WHERE at < ?").run(now - KEEP_MS);
+ }
+ return { ok: true, value };
+ })
+ .immediate();
+ } catch (e) {
+ if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };
+ throw e;
+ }
+}
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
new file mode 100644
index 00000000..8e817532
--- /dev/null
+++ b/tests/pool-limits.test.ts
@@ -0,0 +1,346 @@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Limits on runs on this install's GPUs: the policy's runs at once, runs waiting, runs an hour and runs from one address
+ * an hour count those runs only, together with making the run's rows (requests that arrive together never pass them
+ * together); runs on an account's own GPU keep the studio's own limits. Also where a run goes: the policy's default
+ * place, an own GPU that doesn't answer (asked, never moved), the kinds a policy allows, a guest's policy, every step of
+ * a chain checked and priced once, and the real size of a picture in its price facts.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-limits-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+delete process.env.FUOBE_TRUST_PROXY;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const hostedRun = await import("@/server/hosted-run");
+const limits = await import("@/server/pool-limits");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { PLACE_ASK_HEADER } = await import("@/lib/guest-access");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const IMAGE = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" };
+
+let fake: FakeBilling;
+let n = 0;
+
+/** A new account and its cookie (each test gets its own, so counts never carry over). */
+function account(o: { gpu?: "online" | "offline" } = {}) {
+ const a = auth.createAccount(`limits-${++n}@example.com`, "long enough");
+ if (o.gpu) {
+ auth.setAccountGpu(a.id, { mode: "computer" });
+ if (o.gpu === "online") tasks.beat(`acct:${a.id}`, { device: `device-${n}`, takeover: true, facts: { vramBytes: 24 * 2 ** 30 } });
+ }
+ return { id: a.id, cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` };
+}
+
+const post = async (body: Record<string, unknown>, cookie: string, headers: Record<string, string> = {}) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...headers }, body: text }),
+ );
+ return { status: r.status, headers: r.headers, body: (await r.json()) as { items?: { id: string; place?: string }[]; code?: string; error?: string } };
+};
+
+/** Runs on this install's GPUs an account has made. */
+const poolRuns = (id: string) =>
+ (db().prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') = 'pool'").get(id) as { n: number }).n;
+const ownRuns = (id: string) =>
+ (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') IS NULL").get(id) as { n: number }).n;
+
+function standInWorker() {
+ const w = pool.addWorker(`stand-in-${++n}`);
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);
+ return w;
+}
+
+const withBilling = (policy: Record<string, unknown> = {}) => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...FAKE_POLICY, ...policy, limits: { ...FAKE_POLICY.limits, outputsPerRun: 4, ...((policy.limits as object) ?? {}) }, ttlS: 0 };
+ billing.resetBillingCache();
+};
+
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ allowed = [fake.url];
+ auth.setPassword("install password");
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_TRUST_PROXY"]) delete process.env[k];
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ delete process.env.FUOBE_TRUST_PROXY;
+ fake.policy = { ...FAKE_POLICY };
+ fake.guestPolicy = null;
+ fake.price = { amount: 7, version: "v7" };
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ standInWorker();
+});
+
+const SHOWN = { shown: { amount: 7, priceVersion: "v7" } };
+
+describe("runs at once on this install's GPUs", () => {
+ it("10 requests sent together against a limit of 2 make exactly 2 runs, and every other hold goes back", async () => {
+ withBilling({ limits: { activeRuns: 2, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const before = fake.holds.size;
+ const answers = await Promise.all(Array.from({ length: 10 }, () => post({ ...IMAGE, ...SHOWN }, a.cookie)));
+ const made = answers.filter((r) => r.status === 201);
+ expect(made.length, JSON.stringify(answers.map((r) => [r.status, r.body.error]))).toBe(2);
+ expect(poolRuns(a.id)).toBe(2);
+ for (const r of answers.filter((x) => x.status !== 201)) {
+ expect(r.status).toBe(429);
+ expect(r.body.code).toBe("active-runs");
+ expect(r.body.error).toBe(limits.POOL_LIMIT_WORDS.active(2));
+ }
+ // Each request that got a hold and made nothing gives it back (an outbox release).
+ const holds = fake.holds.size - before;
+ const releases = (db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE kind = 'release'").get() as { n: number }).n;
+ expect(holds - 2).toBe(releases);
+ });
+
+ it("the count and the rows are one transaction: a second count inside it sees the first run", () => {
+ const a = account();
+ const p = { limits: { activeRuns: 1, waiting: 0, runsPerHour: 0, outputsPerRun: 0, maxMegapixels: 0, maxSeconds: 0, keepDays: 0, spaceBytes: 0 } };
+ const insert = () =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(`tx-${++n}`, JSON.stringify({ account: a.id, place: "pool" }), Date.now(), Date.now());
+ const first = limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null } }, insert);
+ expect(first.ok).toBe(true);
+ const second = limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null } }, insert);
+ expect(second.ok).toBe(false);
+ // A refusal thrown inside keeps nothing it wrote.
+ const p2 = { ...p, limits: { ...p.limits, activeRuns: 5 } };
+ const r = limits.admitRun({ accountId: a.id, pool: { policy: p2, addr: null } }, () => {
+ insert();
+ throw new limits.AdmitRefused({ status: 403, error: "no", code: "not-offered" });
+ });
+ expect(r.ok).toBe(false);
+ expect(poolRuns(a.id)).toBe(1);
+ });
+
+ it("runs on the account's own GPU never count against the policy, and keep the studio's own limit of 4", async () => {
+ withBilling({ limits: { activeRuns: 1, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ for (let i = 0; i < 3; i++) {
+ const r = await post(IMAGE, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBeUndefined();
+ }
+ expect(ownRuns(a.id)).toBe(3);
+ // One on this install's GPUs still fits its policy's 1.
+ const pooled = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(pooled.status, JSON.stringify(pooled.body)).toBe(201);
+ expect(poolRuns(a.id)).toBe(1);
+ // The studio's own 4 counts every run, as before.
+ const fifth = await post(IMAGE, a.cookie);
+ expect(fifth.status).toBe(429);
+ });
+
+ it("with a free install (no billing service) the policy's limits apply to runs there too", async () => {
+ const a = account();
+ const p = await billing.policy(a.id);
+ expect(p).toBe(billing.OPEN_POLICY);
+ for (let i = 0; i < 4; i++) expect((await post(IMAGE, a.cookie)).status).toBe(201);
+ const over = await post(IMAGE, a.cookie);
+ expect(over.status).toBe(429);
+ expect(poolRuns(a.id)).toBe(4);
+ });
+});
+
+describe("runs waiting, runs an hour, runs from one address", () => {
+ it("a run that hasn't started counts as waiting", async () => {
+ withBilling({ limits: { activeRuns: 5, waiting: 1, runsPerHour: 0 } });
+ const a = account();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ const second = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(second.status).toBe(429);
+ expect(second.body.error).toBe(limits.POOL_LIMIT_WORDS.waiting(1));
+ // Once it has started, the next one may wait.
+ const id = (db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') = ?").get(a.id) as { id: string }).id;
+ db().prepare("INSERT OR REPLACE INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, ?)").run(id, Date.now(), Date.now());
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ });
+
+ it("runs an hour are counted in the database, one per press of Run, with a time to try again", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 2 } });
+ const a = account();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);
+ const third = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(third.status).toBe(429);
+ expect(third.body.code).toBe("limit");
+ expect(Number(third.headers.get("retry-after"))).toBeGreaterThan(3000);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM pool_admissions WHERE account = ?").get(a.id) as { n: number }).n).toBe(2);
+ // A restart (new in-memory counts) changes nothing.
+ resetRates();
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(429);
+ });
+
+ it("runs from one client address an hour, across accounts, only behind a trusted proxy, kept as a hash", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, addressRunsPerHour: 2 } });
+ const from = { "x-forwarded-for": "203.0.113.9" };
+ const a = account();
+ const b = account();
+ // No trusted proxy: clients can't be told apart, so no address count.
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie, from)).status).toBe(201);
+ process.env.FUOBE_TRUST_PROXY = "1";
+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie, from)).status).toBe(201);
+ expect((await post({ ...IMAGE, ...SHOWN }, b.cookie, from)).status).toBe(201);
+ const third = await post({ ...IMAGE, ...SHOWN }, b.cookie, from);
+ expect(third.status).toBe(429);
+ expect(third.body.error).toBe(limits.POOL_LIMIT_WORDS.address);
+ expect((await post({ ...IMAGE, ...SHOWN }, b.cookie, { "x-forwarded-for": "198.51.100.4" })).status).toBe(201);
+ const kept = db().prepare("SELECT addr FROM pool_admissions WHERE addr IS NOT NULL").all() as { addr: string }[];
+ expect(kept.length).toBeGreaterThan(0);
+ expect(kept.every((r) => /^[0-9a-f]{32}$/.test(r.addr) && !r.addr.includes("203"))).toBe(true);
+ });
+});
+
+describe("where a run goes", () => {
+ it("the policy's default place: this install's GPUs first, even with the account's own GPU online; a named place wins", async () => {
+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBe("pool");
+ // The request a page gets back (and sends again on Retry) never says where it ran.
+ expect((r.body.items![0] as { request?: Record<string, unknown> }).request?.place).toBeUndefined();
+ const own = await post({ ...IMAGE, place: "own" }, a.cookie);
+ expect(own.status).toBe(201);
+ expect(own.body.items![0].place).toBeUndefined();
+ // Without it, the own GPU first as before.
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const again = await post(IMAGE, a.cookie);
+ expect(again.body.items![0].place).toBeUndefined();
+ // The status tells the pages.
+ const status = await visitorStatus(auth.accountById(a.id)!);
+ expect(status.viewer.prefer).toBeUndefined();
+ withBilling({ prefer: "pool" });
+ expect((await visitorStatus(auth.accountById(a.id)!)).viewer.prefer).toBe("pool");
+ });
+
+ it("an own GPU that doesn't answer: a run that named no place is asked about, never moved and charged", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "offline" });
+ const holds = fake.holds.size;
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe("own-gpu-offline");
+ expect(r.headers.get(PLACE_ASK_HEADER)).toBe("1");
+ expect(fake.holds.size).toBe(holds);
+ expect(poolRuns(a.id)).toBe(0);
+ // Asked for this install's GPUs, it runs there.
+ const yes = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);
+ expect(yes.status, JSON.stringify(yes.body)).toBe(201);
+ expect(poolRuns(a.id)).toBe(1);
+ });
+
+ it("a kind the policy leaves out is not offered here", async () => {
+ withBilling({ kinds: { image: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("not-offered");
+ expect(hostedRun.kindAllowed({ kinds: { image: false } }, "video")).toBe(true);
+ expect(hostedRun.kindAllowed({}, "model3d")).toBe(true);
+ });
+
+ it("a guest is told what the billing service's policy for guests says", async () => {
+ withBilling();
+ fake.guestPolicy = { ...FAKE_POLICY, hosted: false, ttlS: 0 };
+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();
+ expect(fake.calls_of("/v1/policy").at(-1)!.path).toBe("/v1/policy");
+ fake.guestPolicy = { ...FAKE_POLICY, hosted: true, ttlS: 0 };
+ billing.resetBillingCache();
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ // No billing service: as any account.
+ delete process.env.FUOBE_BILLING_URL;
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ });
+});
+
+describe("a run's price facts", () => {
+ it("send the real size of a picture, and every step of a chain once", async () => {
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account();
+ const r = await post({ ...IMAGE, params: { aspectRatio: "16:9", resolution: "1K" }, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const run = (fake.calls_of("/v1/reserve").at(-1)!.body as { run: { megapixels: number | null; steps?: { model: string; jobs: number }[] } }).run;
+ expect(run.megapixels).toBeGreaterThan(0.9);
+ expect(run.megapixels).toBeLessThan(1.2);
+ expect(run.steps).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 1 })]);
+ // A film of two shots: its two clips priced together with one hold; the join costs nothing.
+ const film = await post({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN }, a.cookie);
+ expect(film.status, JSON.stringify(film.body)).toBe(201);
+ const reserves = fake.calls_of("/v1/reserve");
+ const filmRun = (reserves.at(-1)!.body as { run: { steps?: { model: string; jobs: number }[] } }).run;
+ expect(filmRun.steps?.find((s) => s.model === "oss-wan22-14b-fast")?.jobs).toBe(2);
+ expect(filmRun.steps?.every((s) => s.model === "oss-wan22-14b-fast"), JSON.stringify(filmRun.steps)).toBe(true);
+ expect(poolRuns(a.id)).toBe(2);
+ });
+
+ it("every step must be one the policy allows: a later step's model it leaves out stops the run before anything is made", () => {
+ const steps = (models: [string, string][]) => models.map(([modelId, provider], i) => ({ id: `s${i}`, modelId, op: "t2i", provider, kind: "image", presetId: null, waits: i > 0 }));
+ const p = { ...billing.OPEN_POLICY, pool: { deny: ["oss-qwen-image-edit"] } };
+ expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"]]))).toBeNull();
+ expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"], ["oss-qwen-image-edit", "comfyui"]]))).not.toBeNull();
+ // A cloud step can't run here; a text step costs nothing and is always allowed.
+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps([["oss-z-image-turbo", "comfyui"], ["fal-flux", "fal"]]))).not.toBeNull();
+ expect(hostedRun.stepsProblem({ ...billing.OPEN_POLICY, pool: { allow: ["oss-z-image-turbo"] } }, steps([["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toBeNull();
+ expect(hostedRun.pricedSteps(steps([["oss-z-image-turbo", "comfyui"], ["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 2 })]);
+ });
+});
diff --git a/tests/run-place.test.ts b/tests/run-place.test.ts
index dd11e72e..2154b21a 100644
--- a/tests/run-place.test.ts
+++ b/tests/run-place.test.ts
@@ -106,6 +106,10 @@ describe("hosted runs (this studio's GPUs)", () => {
expect(at({ audience: "account", engine: "open", hosted: true, gpu: true }).where).toBe("gpu");
expect(at({ audience: "owner", engine: "open", hosted: true }).where).toBe("gpu");
});
+ it("with the studio's GPUs first, an account with its own GPU runs on the studio's; the owner still on its own", () => {
+ expect(at({ audience: "account", engine: "open", hosted: true, gpu: true, preferPool: true }).where).toBe("pool");
+ expect(at({ audience: "owner", engine: "open", hosted: true, preferPool: true }).where).toBe("gpu");
+ });
it("a guest signs up first", () => {
const p = at({ audience: "guest", engine: "open", hosted: true });
expect(p).toMatchObject({ where: "pool", needs: "signup", send: "this studio's GPUs, after sign-up" });