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: a tool's run is priced as it asks, and its rows are checked against what was held
Adarsh60109bad3fd6
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 079632f8..d5371bbb 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -91,9 +91,16 @@ A tool's run (Shorts, Cinema Studio, Storyboard, the apps, the palette lock andthrough the same gate as a studio run: every step is checked, the run is priced once from every step, held once, andcounted once. Its price check answers `{ place: "pool", quote, line }` beside the tool's own answer when the run wouldgo to this install's GPUs, and the tool's own answer is then priced as a run there (so an account with no GPU of its-own is priced, not asked to connect one). A tool whose body has no field for the place or the price shown reads them from the request's-headers: `x-fuobe-place` (`own` or `pool`) and `x-fuobe-shown` (`{ amount, priceVersion }` as URI-encoded JSON). A-field in the body wins.+own is priced, not asked to connect one). A tool whose body has no field for the place or the price shown reads them+from the request's headers: `x-fuobe-place` (`own` or `pool`) and `x-fuobe-shown` (`{ amount, priceVersion }` as+URI-encoded JSON). A field in the body wins.++A tool makes its own requests, so each of its steps is priced as it asks. A step that asks for more outputs at once+than `outputsPerRun` allows (or Fuobe's own cap of 4) is refused before Run with words that say how many a run there+makes. It is never priced as a smaller run. The studios' own runs are cut to the cap instead, and say so. Before+anything of a tool's run is sent, Fuobe checks the rows its start made against what was priced and held: no more jobs+of any model, no more outputs at once than the cap, and only CPU work for a run held as CPU work. A run whose rows+don't match is stopped: its rows are canceled and its hold goes back (403, `code: "not-offered"`).Some models, modes and options run on a visitor's own setup only (`src/lib/own-setup.ts`), and so does a workflow thatnone of this install's GPUs can run right now (none holds its files, serves its kind of work, or has the memory itdiff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsindex 5b126f9a..6bf0d4be 100644--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@ -19,8 +19,8 @@ import { queueRelease } from "./billing-outbox";import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";import { gpuTargetFor } from "./gpu/target";import { runOnPool } from "./hosted";-import { decideToolPlace, GUEST_PLAN, moderateRun, poolMayTake, readWishes, reservePool, stepsProblem, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";-import { cancelGeneration, captureRun, stepsOf } from "./generations";+import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, poolMayTake, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";+import { cancelGeneration, captureRun } from "./generations";import { AdmitRefused, admitRun, clientAddress, poolLimitRefusal } from "./pool-limits";import { hit, unhit } from "./rate";import { withRunStamp, type RunStamp } from "./run-stamp";@@ -390,9 +390,10 @@ const isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v a* A tool run on this install's GPUs (placeOf said "pool"): the policy's limits on runs there (never for light work* only), the moderation service's check, one hold for the whole run priced from every step (none for light work: free),* then the run made as the account's run there (runOnPool, every row stamped with its place and hold) and counted in- * the same transaction (admitRun). Every row it makes is checked against the policy again before anything is sent- * (stepsProblem): a step the policy doesn't allow stops the whole run, its rows are stopped, and its hold goes back.- * Its own GPU's checks (the pre-flight, its LoRAs) don't apply here.+ * the same transaction (admitRun). Every row it makes is checked again before anything is sent (madeRunProblem): against+ * the policy, and against what the run was priced and held for (its jobs, its outputs at once, light work only). A row+ * that doesn't match stops the whole run: its rows are stopped, and its hold goes back. Its own GPU's checks (the+ * pre-flight, its LoRAs) don't apply here.*/async function startOnPool<T>(request: Request,@@ -430,7 +431,7 @@ async function startOnPool<T>(const made = captureRun(run.start);// A tool that makes its rows as it goes (after an await) is checked once they are all made, below.if (!isThenable(made.value)) {- const problem = stepsProblem(pool.policy, stepsOf(made.ids));+ const problem = madeRunProblem(pool, made.ids);if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });}return made;@@ -460,7 +461,7 @@ async function startOnPool<T>(return back(errorResponse(e));}if (isThenable(made.value)) {- const problem = stepsProblem(pool.policy, stepsOf(made.ids));+ const problem = madeRunProblem(pool, made.ids);if (problem) {undo();return back(notOffered(problem));diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex c16993df..31a51a13 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -25,10 +25,11 @@ import {} from "./billing";import { getModel } from "@/lib/catalog";import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER } from "@/lib/guest-access";-import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, type PlannedStep } from "./generations";+import { db } from "./db";+import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, stepsOf, type PlannedStep } from "./generations";import { loadIndex } from "./gpu/index-file";import { poolLane } from "./computer/pool";-import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";+import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, outputsWords, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";import { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";@@ -138,7 +139,7 @@ const ownSetupRefusal = (setup: OwnSetup): { kind: "refuse"; refusal: Refusal }/** A gate's refusal as the run's answer: its words, with the own setup that would run it. */function gateRefusal(gate: GateRefusal): { kind: "refuse"; refusal: Refusal } {if (gate.reason === "ownSetup") return ownSetupRefusal(gate.setup ?? needsGpu());- const error = gateWords(gate.reason, false);+ const error = gateText(gate, false);if (gate.reason === "model3d") return { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } };const r = notOffered(error);if (gate.setup) r.refusal.body.ownSetup = gate.setup;@@ -217,6 +218,39 @@ export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {return null;}+/** How many outputs each row asks for (its request's numOutputs: a run split into one job per output keeps it on each). */+function rowOutputs(ids: string[]): number[] {+ const q = db().prepare("SELECT request_json FROM generations WHERE id = ?");+ return ids.map((id) => {+ const r = q.get(id) as { request_json: string } | undefined;+ try {+ const n = r ? Number((JSON.parse(r.request_json) as GenerationRequest).params?.numOutputs ?? 1) : 1;+ return Number.isFinite(n) ? n : 1;+ } catch {+ return 1;+ }+ });+}++/**+ * The rows a tool's run made on this install's GPUs, checked against what it was priced and held for, before anything+ * of it is sent: every step one the policy allows there (stepsProblem); a run held as light work (free, never counted)+ * that made light work only; no row asking for more outputs at once than a run there makes (poolOutputsCap); and no more+ * jobs of any model and operation than were priced. Null when they match; otherwise its refusal's words. A tool whose+ * start makes more than its plan said is stopped here, never run on a hold for less.+ */+export function madeRunProblem(run: { policy: Policy; steps: RunFacts["steps"]; light: boolean }, ids: string[]): string | null {+ const made = stepsOf(ids);+ const problem = stepsProblem(run.policy, made);+ if (problem) return problem;+ if (run.light) return lightRun(made) ? null : HOSTED_WORDS.notOffered;+ const cap = poolOutputsCap(run.policy);+ if (rowOutputs(ids).some((n) => n > cap)) return outputsWords(cap, false);+ const held = new Map((run.steps ?? []).map((s) => [`${s.model} ${s.op ?? ""}`, s.jobs]));+ for (const s of pricedSteps(made)) if (s.jobs > (held.get(`${s.model} ${s.op ?? ""}`) ?? 0)) return HOSTED_WORDS.notOffered;+ return null;+}+/*** Is a run light work only: every step it makes a ComfyUI step that needs no model and no graphics memory (a filter, a* trim, a join, adding sound, a Ken Burns move)? Such a run is free and never counts against the policy's limits on runs@@ -243,25 +277,29 @@ export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]/*** Why this install's GPUs won't take a run: a 3D model, a model or kind not offered there, a model their card can't run,- * LoRAs, a kind of file, or one that runs on the visitor's own setup only (`ownSetup`: a static item of own-setup.ts, or- * a workflow none of this install's GPUs can run right now: none holds its files, serves its lane, or has the memory).+ * LoRAs, a kind of file, more outputs at once than a run there makes (`outputs`: a tool's run, which can't be cut down+ * the way the studios' own runs are), or one that runs on the visitor's own setup only (`ownSetup`: a static item of+ * own-setup.ts, or a workflow none of this install's GPUs can run right now: none holds its files, serves its lane, or+ * has the memory).*/-export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "ownSetup";+export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "outputs" | "ownSetup";/*** A gate's refusal: its reason, and the visitor's own setup that would run it (`setup`: always with "ownSetup"; with the- * others, a GPU of its own, which runs what this install's GPUs don't take).+ * others, a GPU of its own, which runs what this install's GPUs don't take). `cap`: with "outputs", the most a run there+ * makes at once.*/-export type GateRefusal = { ok: false; reason: GateReason; setup?: OwnSetup };+export type GateRefusal = { ok: false; reason: GateReason; setup?: OwnSetup; cap?: number };/** The words for a gate's reason: an account may connect its own GPU in Settings, a guest has nowhere to do that yet. */-export function gateWords(reason: Exclude<GateReason, "ownSetup">, guest: boolean): string {+export function gateWords(reason: Exclude<GateReason, "ownSetup" | "outputs">, guest: boolean): string {if (reason === "model3d") return OWN_GPU_TOOL_MESSAGE;return (guest ? HOSTED_GUEST_WORDS : HOSTED_WORDS)[reason];}/** A gate's refusal in words: the own setup's label (the same for a guest and an account), or the reason's words. */-export const gateText = (gate: GateRefusal, guest: boolean): string => (gate.reason === "ownSetup" ? ownSetupLabel(gate.setup ?? needsGpu()) : gateWords(gate.reason, guest));+export const gateText = (gate: GateRefusal, guest: boolean): string =>+ gate.reason === "ownSetup" ? ownSetupLabel(gate.setup ?? needsGpu()) : gate.reason === "outputs" ? outputsWords(gate.cap ?? 1, guest) : gateWords(gate.reason, guest);/*** The one check of whether this install's GPUs take a run, shared by the run itself (decidePlace) and the price check@@ -327,13 +365,18 @@ async function ownGpuOnline(accountId: string): Promise<boolean> {}}+/** The most outputs one request makes on this install's GPUs: the studio's cap per run, and the policy's when lower. */+export function poolOutputsCap(p: Pick<Policy, "limits"> | null): number {+ const policyCap = p && p.limits.outputsPerRun > 0 ? [Math.floor(p.limits.outputsPerRun)] : [];+ return Math.min(ACCOUNT_LIMITS.outputsPerRun, ...policyCap);+}+/**- * A request as it runs on this install's GPUs: no more outputs than the studio's cap per run, and the policy's when lower- * (`capped`: fewer than it asked). The price check and the run plan and price this same request.+ * A request as it runs on this install's GPUs: no more outputs than poolOutputsCap (`capped`: fewer than it asked). The+ * price check and the run plan and price this same request.*/export function poolRequest(req: GenerationRequest, p: Pick<Policy, "limits"> | null): { req: GenerationRequest; capped: boolean } {- const policyCap = p && p.limits.outputsPerRun > 0 ? [Math.floor(p.limits.outputsPerRun)] : [];- const cap = Math.min(ACCOUNT_LIMITS.outputsPerRun, ...policyCap);+ const cap = poolOutputsCap(p);if ((req.params?.numOutputs ?? 1) <= cap) return { req, capped: false };return { req: { ...req, params: { ...req.params, numOutputs: cap } }, capped: true };}@@ -626,6 +669,10 @@ const asPlannedStep = (req: GenerationRequest, p: Planned, waits: boolean): Plan* "unplanned" when a step can't be planned on this install's GPUs (a cloud model, a request with something wrong: the* run goes where it goes today, which says what), or the first step's refusal; passed, the step the run is priced as* (its first ComfyUI step) and every row the run would make.+ *+ * A tool makes its own requests when it starts, so each step is planned and priced as it asks: one that asks for more+ * outputs at once than a run there makes (poolOutputsCap) is refused ("outputs"), never priced as a smaller copy the run+ * wouldn't use.*/export function toolGate(p: Policy | null,@@ -634,9 +681,10 @@ export function toolGate(): "unplanned" | GateRefusal | { ok: true; main: ToolPoolRun["main"]; rows: PlannedStep[] } {let main: ToolPoolRun["main"] | null = null;const rows: PlannedStep[] = [];+ const cap = poolOutputsCap(p);for (const step of steps) {const deps = step.deps ?? 0;- const { req } = poolRequest(step.request, p);+ const req = step.request;let planned: Planned;try {planned = runOnPool(viewer, () => previewChained(req, deps));@@ -651,6 +699,7 @@ export function toolGate(const gate = poolGate(p, planned, req, () => (deps ? [asPlannedStep(req, planned, true)] : poolSteps(viewer ?? GUEST_PLAN, req)));// A tool adds its LoRAs itself (a person adds none to it): said as a step that runs on an own GPU, not as extra LoRAs.if (!gate.ok) return gate.reason === "loras" ? { ok: false, reason: "notOffered", setup: gate.setup } : gate;+ if ((req.params?.numOutputs ?? 1) > cap) return { ok: false, reason: "outputs", cap };rows.push(...(gate.steps ?? [asPlannedStep(req, planned, deps > 0)]));main ??= { req, planned };}diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex da1c3600..238556c0 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -135,6 +135,16 @@ export const HOSTED_GUEST_WORDS = {inputs: "This kind of file can't be used here. Use a picture instead.",};+/**+ * A tool's run that asks for more pictures or clips at once than a run on this install's GPUs makes (the policy's cap per+ * run): pick fewer. An account may also connect its own GPU, which has no such cap.+ */+export function outputsWords(cap: number, guest: boolean): string {+ const most = cap === 1 ? "one at a time" : `up to ${cap} at a time`;+ const pick = cap === 1 ? "Pick one" : `Pick ${cap} or fewer`;+ return guest ? `Runs here make ${most}. ${pick}.` : `This studio's GPUs make ${most}. ${pick}, or connect your own GPU in Settings.`;+}+/** May this model (and app) run on this install's GPUs under this policy? */export function poolAllows(p: Pick<Policy, "pool">, modelId: string, presetId?: string | null): boolean {const m = p.pool ?? {};diff --git a/tests/hosted-surface-runs.test.ts b/tests/hosted-surface-runs.test.tsindex e16e0044..9348c84e 100644--- a/tests/hosted-surface-runs.test.ts+++ b/tests/hosted-surface-runs.test.ts@@ -222,6 +222,31 @@ describe("Cinema Studio for an account with no GPU of its own", () => {expect(rows.every((q) => q.place === "pool" && !!q.hold)).toBe(true);});+ it("a batch of 4 when a run here makes one at a time: said in the price check and on Run, nothing held or made", async () => {+ hostedOn();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };+ const id = await project("none");+ const four = { ...STILL, batch: 4 };+ const words = hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, false);+ const check = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate?preview=1`, "POST", { input: four }, "none"), params({ id }));+ expect(check.status, await check.clone().text()).toBe(200);+ expect(((await check.json()) as { quote?: { allowed: boolean; text: string } }).quote).toMatchObject({ allowed: false, text: words });+ const before = reserves();+ const since = Date.now();+ const r = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", { input: four }, "none", shownHeaders()), params({ id }));+ expect(r.status, await r.clone().text()).toBe(403);+ expect(((await r.json()) as { error: string }).error).toBe(words);+ expect(reserves()).toBe(before);+ expect(runsSince("none", since)).toEqual([]);+ // One take at a time runs, priced and held for exactly what it makes.+ const one = await send(() => generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", { input: STILL }, "none", shownHeaders()), params({ id })));+ expect(one.status, await one.clone().text()).toBe(201);+ expect(reserves() - before).toBe(1);+ const held = fake.calls_of("/v1/reserve").at(-1)!.body as { run: { jobs: number; outputsPerJob: number } };+ expect(held.run).toMatchObject({ jobs: 1, outputsPerJob: 1 });+ expect(runsSince("none", since)).toHaveLength(1);+ });+it("an account whose own GPU answers is priced and run there, as before", async () => {hostedOn();const id = await project("gpu");diff --git a/tests/hosted-tool-runs.test.ts b/tests/hosted-tool-runs.test.tsindex ec5930d5..2c1392b9 100644--- a/tests/hosted-tool-runs.test.ts+++ b/tests/hosted-tool-runs.test.ts@@ -187,6 +187,86 @@ describe("hosted runs on", () => {expect(hold?.released).toBe(true);});+ it("a start that makes more jobs than its plan was priced and held for is stopped, and its hold goes back", async () => {+ useBilling();+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const rows = stored("none").length;+ const before = reserves();+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },+ plan: () => plan,+ // Priced as one picture; the start makes two of the same model.+ start: () => [...createGenerations(plan[0].request), ...createGenerations({ ...plan[0].request, prompt: "a fox at dusk" })],+ });+ expect(r.ok).toBe(false);+ if (!r.ok) {+ expect(r.response.status).toBe(403);+ expect(((await r.response.json()) as { code: string }).code).toBe("not-offered");+ }+ expect(reserves() - before).toBe(1);+ expect((fake.calls_of("/v1/reserve").at(-1)!.body as { run: { steps: { jobs: number }[] } }).run.steps).toEqual([expect.objectContaining({ jobs: 1 })]);+ expect(stored("none").length).toBe(rows);+ await drainOutbox();+ expect([...fake.holds.values()].at(-1)?.released).toBe(true);+ });++ it("a start whose row asks for more outputs at once than a run here makes is stopped, its hold given back", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const rows = stored("none").length;+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },+ plan: () => plan,+ start: () => createGenerations({ ...plan[0].request, params: { numOutputs: 2 } }),+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(((await r.response.json()) as { error: string }).error).toBe(hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, false));+ expect(stored("none").length).toBe(rows);+ await drainOutbox();+ expect([...fake.holds.values()].at(-1)?.released).toBe(true);+ });++ it("a run planned as light work (free, never counted) whose start makes GPU work is stopped before anything is sent", async () => {+ const light = [{ request: { feature: "video", modelId: "oss-ken-burns", op: "still-motion" as const, inputs: { images: ["/api/files/x.png"] }, params: { duration: 4 } } }];+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, light);+ expect(place.kind).toBe("pool");+ if (place.kind === "pool") expect(place.light).toBe(true);+ const rows = stored("none").length;+ const before = reserves();+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ plan: () => light,+ start: () => createGenerations({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" }),+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.response.status).toBe(403);+ expect(reserves()).toBe(before);+ expect(stored("none").length).toBe(rows);+ });++ it("a tool's step that asks for more outputs than a run here makes is refused before Run, never priced smaller", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", params: { numOutputs: 4 } } }];+ const words = hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, false);+ const quotes = fake.calls_of("/v1/quote").length;+ const check = await toolRun.toolPriceCheck(json("/api/x?preview=1", "POST", {}, "none"), () => steps);+ expect(check?.quote).toMatchObject({ allowed: false, code: "not-offered", text: words });+ expect(fake.calls_of("/v1/quote").length).toBe(quotes);+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);+ expect(place.kind).toBe("refuse");+ if (place.kind === "refuse") expect(place.refusal.body).toMatchObject({ error: words, code: "not-offered" });+ // A guest's words name nothing it can't do yet; an account whose own GPU answers runs it there.+ expect(hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, true)).not.toMatch(/Settings/);+ expect(await toolRun.placeOf(auth.accountById(ids.gpu)!, steps)).toEqual({ kind: "own" });+ });+it("a 3D model stays on an account's own GPU: refused here in the tools' words", async () => {const steps = [{ request: { feature: "3d", modelId: "oss-pixal3d", op: "image-to-3d" as const, prompt: "", inputs: { images: ["/api/files/x.png"] } } }];const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);