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: the price check says the place in line and refuses before Run

Adarsh56aa32009250
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 43525a4f..f781c847 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -153,11 +153,11 @@ export async function POST(request: Request) {
try {
if (preview) {
// Hosted runs: a visitor's run that would go to this install's GPUs is priced there, with the billing service's
- // quote (its words for Run). Off, or a run on its own GPU or key: priced as before.
- const pool = viewer.kind !== "owner" ? await poolQuote(account, req, wish) : null;
+ // quote (its words for Run) and where it would stand in line. Off, or a run on its own GPU or key: priced as before.
+ const pool = viewer.kind !== "owner" ? await poolQuote(account, req, wish, { addr: account ? clientAddress(request) : null }) : null;
if (pool) {
const { model, ...p } = pool.planned;
- return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op, place: "pool", quote: pool.quote });
+ return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op, place: "pool", quote: pool.quote, line: pool.line });
}
const { model, ...p } = priced(() => previewGeneration(req));
return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op });
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 5f519f04..07ea2c8c 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -33,6 +33,7 @@ import { checkRun, moderationConfigured } from "./moderation";
import type { RunStamp } from "./run-stamp";
import { readRef } from "./storage";
import { ACCOUNT_LIMITS } from "./account-files";
+import { poolLimitRefusal } from "./pool-limits";
import { runAsTenant } from "./tenant";
/**
@@ -305,14 +306,34 @@ export async function reservePool(
};
}
+/** Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown). */
+export interface PoolLine {
+ place: number;
+ etaSeconds: number | null;
+}
+
+/** A price check's answer for a run this install's GPUs won't take, in the words the run itself would get. */
+const notOfferedQuote = (text: string): Quote => ({ allowed: false, amount: 0, priceVersion: "", text, code: "not-offered" });
+
/**
- * A price check on this install's GPUs (hosted runs on): the plan there and the billing service's quote (no service:
- * free, and Run keeps its own words). Null when the run wouldn't go there (its own GPU, its own key, today's answer).
+ * A price check on this install's GPUs (hosted runs on): the plan there, the billing service's quote (no service: free,
+ * and Run keeps its own words) and where the run would stand in line. Null when the run wouldn't go there (its own GPU,
+ * its own key, today's answer).
+ *
+ * The quote is refused before Run for what the run itself would be refused for (decidePlace and the route's limits), so
+ * Run is off and says why instead of failing once pressed: a model, a kind, LoRAs or files this install's GPUs don't
+ * take (for a viewer with no GPU of its own to send them to instead), and the policy's limits on runs at once, runs in
+ * line and runs an hour. `addr`: the client's address as the hourly count keeps it (pool-limits.ts clientAddress).
*/
-export async function poolQuote(account: Account | null, asked: GenerationRequest, wish: PlaceWish): Promise<{ planned: Planned; quote: Quote } | null> {
+export async function poolQuote(
+ account: Account | null,
+ asked: GenerationRequest,
+ wish: PlaceWish,
+ o: { addr?: string | null } = {},
+): Promise<{ planned: Planned; quote: Quote; line: PoolLine } | null> {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return 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;
+ const p = await billingPolicy(account?.id ?? 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;
@@ -323,14 +344,34 @@ export async function poolQuote(account: Account | null, asked: GenerationReques
return null;
}
if (planned.route.provider !== "comfyui") return null;
- if (account && wish !== "pool" && !prefersPool(p) && accountGpu(account.id) && (await ownGpuOnline(account.id))) return null;
+ const hasGpu = !!account && !!accountGpu(account.id);
+ if (account && hasGpu && wish !== "pool" && !prefersPool(p) && (await ownGpuOnline(account.id))) return null;
+ if (p && !p.hosted) return null;
+ const line = (facts: { ahead: number; etaS: number | null }, q?: Quote): PoolLine => ({ place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null });
+ // What this install's GPUs won't take goes to the viewer's own GPU when it has one (as the run would); otherwise the
+ // price check says so, and Run stays off.
+ const notHere = (text: string) => (hasGpu && wish !== "pool" ? null : { planned, quote: notOfferedQuote(text), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) });
const kind = outputKind(planned.op, planned.model);
- if (p && (!p.hosted || !poolAllows(p, planned.model.id, req.presetId) || !kindAllowed(p, kind))) return null;
- if (!poolTakes(planned.route.endpoint)) return null;
+ if (kind === "model3d") return notHere(OWN_GPU_TOOL_MESSAGE);
+ if (p && (!poolAllows(p, planned.model.id, req.presetId) || !kindAllowed(p, kind))) return notHere(HOSTED_WORDS.notOffered);
+ if (!poolTakes(planned.route.endpoint)) return notHere(HOSTED_WORDS.notOffered);
+ if (req.loras?.length) return notHere(HOSTED_WORDS.loras);
+ if (p) {
+ const inputs = inputCounts(req);
+ const takes = (k: "image" | "video" | "audio") => p.uploads[k] && poolTakesFiles(k);
+ if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return notHere(HOSTED_WORDS.inputs);
+ }
// 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 problem = steps && p ? stepsProblem(p, steps) : null;
+ if (problem) return notHere(problem);
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 };
+ const queue = queueFacts(account?.id ?? null, planned.route.endpoint);
+ let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);
+ // The policy's limits on this account's runs here, as the run would meet them (pool-limits.ts): said before Run.
+ if (q.allowed && account && p) {
+ const over = poolLimitRefusal(account.id, p, o.addr ?? null);
+ if (over) q = { ...q, allowed: false, code: "limit", text: over.error };
+ }
+ return { planned, quote: q, line: line(queue, q) };
}
diff --git a/tests/helpers/fake-billing.ts b/tests/helpers/fake-billing.ts
index c6ede6e8..859be8aa 100644
--- a/tests/helpers/fake-billing.ts
+++ b/tests/helpers/fake-billing.ts
@@ -60,6 +60,8 @@ export interface FakeBilling {
guestPolicy: Record<string, unknown> | null;
/** Extra fields of every reserve answer that sets a price aside (a class, say). */
reserveExtra: Record<string, unknown>;
+ /** The quote every price check gets instead of the allowed one (a refusal: busy, a limit…); null: allowed. */
+ quoteAnswer: Record<string, unknown> | null;
/** How many times each (hold, generation) pair was reported. */
reportCount: (holdId: string, generationId: string) => number;
calls_of: (path: string) => Recorded[];
@@ -86,6 +88,7 @@ export async function startFakeBilling(): Promise<FakeBilling> {
policy: { ...FAKE_POLICY },
guestPolicy: null,
reserveExtra: {},
+ quoteAnswer: null,
reportCount: (h, g) => reportCounts.get(`${h} ${g}`) ?? 0,
calls_of: (p) => f.calls.filter((c) => c.path.split("?")[0] === p),
};
@@ -109,7 +112,7 @@ export async function startFakeBilling(): Promise<FakeBilling> {
const b = (body ?? {}) as Record<string, unknown>;
if (p === "/v1/health") return json(200, { ok: true, version: "test" });
if (p === "/v1/policy") return json(200, !new URLSearchParams(path.split("?")[1] ?? "").get("account") && f.guestPolicy ? f.guestPolicy : f.policy);
- if (p === "/v1/quote") return json(200, quote());
+ if (p === "/v1/quote") return json(200, f.quoteAnswer ?? quote());
if (p === "/v1/reserve") {
const requestId = String(b.requestId);
const again = [...f.holds.entries()].find(([, h]) => h.requestId === requestId);
diff --git a/tests/hosted-price-check.test.ts b/tests/hosted-price-check.test.ts
new file mode 100644
index 00000000..9010cc01
--- /dev/null
+++ b/tests/hosted-price-check.test.ts
@@ -0,0 +1,186 @@
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { FAKE_POLICY, listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+// The price check before Run (`?preview=1`) on hosted runs: where a new run would stand in line and the wait, and a
+// refusal (busy, a limit, a model or files this install's GPUs don't take) said before Run is pressed, in the words the
+// run itself would get. With hosted runs off the answer is as before.
+const dir = tempDir("fuobe-hosted-price-check-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+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 billing = await import("@/server/billing");
+const { HOSTED_WORDS } = await import("@/server/hosted");
+const { POOL_LIMIT_WORDS } = await import("@/server/pool-limits");
+
+let fake: FakeBilling;
+let a = "";
+let cookie = "";
+let other = "";
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ other = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ delete process.env.FUOBE_HOSTED_RUNS;
+ delete process.env.FUOBE_HOSTED_FREE;
+ delete process.env.FUOBE_BILLING_URL;
+ fake.policy = { ...FAKE_POLICY };
+ fake.quoteAnswer = null;
+ fake.down = false;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ auth.setAccountGpu(a, null);
+});
+
+const check = async (body: Record<string, unknown>, c: string | null = cookie) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request("http://localhost:3000/api/generations?preview=1", {
+ method: "POST",
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(c && { cookie: c }) },
+ body: text,
+ }),
+ );
+ return { status: r.status, body: (await r.json()) as { place?: string; quote?: Record<string, unknown>; line?: { place: number; etaSeconds: number | null } } };
+};
+const fox = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox in the snow" };
+
+/** A run of `account`'s waiting in line on this install's GPUs (not started). */
+let n = 0;
+function waitingRun(account: string) {
+ const id = `waiting-${++n}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(id, JSON.stringify({ account, place: "pool" }), now, now);
+ return id;
+}
+
+describe("the price check with hosted runs off", () => {
+ it("is as before: no place, no quote and no line", async () => {
+ const r = await check(fox);
+ expect(r.status).toBe(200);
+ expect(r.body.place).toBeUndefined();
+ expect(r.body.quote).toBeUndefined();
+ expect(r.body.line).toBeUndefined();
+ });
+});
+
+describe("the price check with hosted runs on", () => {
+ beforeEach(() => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ });
+ const useService = () => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ };
+
+ it("says where a new run would stand in line: next with nobody ahead, behind every run that waits", async () => {
+ const first = await check(fox);
+ expect(first.body.place).toBe("pool");
+ expect(first.body.quote).toMatchObject({ allowed: true });
+ expect(first.body.line).toEqual({ place: 1, etaSeconds: null });
+ waitingRun(other);
+ waitingRun(other);
+ expect((await check(fox)).body.line?.place).toBe(3);
+ });
+
+ it("shows the service's words as they are, and its wait", async () => {
+ useService();
+ const r = await check(fox);
+ expect(r.body.quote).toMatchObject({ allowed: true, text: "7 units", sub: "from your test balance" });
+ expect(r.body.line).toEqual({ place: 1, etaSeconds: 7 });
+ });
+
+ it("passes a refusal of the service's on (busy), with its words, before Run", async () => {
+ useService();
+ fake.quoteAnswer = { allowed: false, amount: 0, priceVersion: "v7", text: "Busy right now. Try again in about 10 min.", code: "busy", etaS: 2400 };
+ const r = await check(fox);
+ expect(r.body.place).toBe("pool");
+ expect(r.body.quote).toMatchObject({ allowed: false, code: "busy", text: "Busy right now. Try again in about 10 min." });
+ });
+
+ it("the service not answering: refused as paused, in plain words", async () => {
+ useService();
+ fake.down = "error";
+ const r = await check(fox);
+ expect(r.body.quote).toMatchObject({ allowed: false, code: "paused", text: billing.BILLING_PAUSED });
+ });
+
+ it("the policy's limits on runs at once and in line are said before Run, with the run's own words", async () => {
+ useService();
+ fake.policy = { ...FAKE_POLICY, limits: { ...FAKE_POLICY.limits, activeRuns: 1 } };
+ waitingRun(other);
+ expect((await check(fox)).body.quote).toMatchObject({ allowed: true });
+ waitingRun(a);
+ const r = await check(fox);
+ expect(r.body.quote).toMatchObject({ allowed: false, code: "limit", text: POOL_LIMIT_WORDS.active(1) });
+ // Waiting runs have their own limit.
+ billing.resetBillingCache();
+ fake.policy = { ...FAKE_POLICY, limits: { ...FAKE_POLICY.limits, waiting: 1 } };
+ expect((await check(fox)).body.quote).toMatchObject({ allowed: false, code: "limit", text: POOL_LIMIT_WORDS.waiting(1) });
+ });
+
+ it("a model, LoRAs or files this install's GPUs don't take: refused before Run for an account with no GPU of its own", async () => {
+ useService();
+ fake.policy = { ...FAKE_POLICY, pool: { deny: ["oss-z-image-turbo"] } };
+ const denied = await check(fox);
+ expect(denied.body.place).toBe("pool");
+ expect(denied.body.quote).toMatchObject({ allowed: false, code: "not-offered", text: HOSTED_WORDS.notOffered });
+ billing.resetBillingCache();
+ fake.policy = { ...FAKE_POLICY };
+ const loras = await check({ ...fox, loras: [{ file: "x.safetensors", url: "https://huggingface.co/x/x.safetensors" }] });
+ expect(loras.body.quote).toMatchObject({ allowed: false, code: "not-offered", text: HOSTED_WORDS.loras });
+ billing.resetBillingCache();
+ fake.policy = { ...FAKE_POLICY, kinds: { image: false } };
+ expect((await check(fox)).body.quote).toMatchObject({ allowed: false, code: "not-offered" });
+ });
+
+ it("an account with a GPU of its own: what this install's GPUs don't take goes to its own GPU, as before", async () => {
+ useService();
+ auth.setAccountGpu(a, { mode: "computer" });
+ fake.policy = { ...FAKE_POLICY, pool: { deny: ["oss-z-image-turbo"] } };
+ const r = await check(fox);
+ expect(r.body.place).toBeUndefined();
+ expect(r.body.quote).toBeUndefined();
+ });
+
+ it("a guest is priced and placed in line as an account would be", async () => {
+ waitingRun(other);
+ const r = await check(fox, null);
+ expect(r.body.place).toBe("pool");
+ expect(r.body.quote).toMatchObject({ allowed: true });
+ expect(r.body.line?.place).toBe(2);
+ });
+});
+
diff --git a/tests/hosted-runs-voice-design.test.ts b/tests/hosted-runs-voice-design.test.ts
index c68d2701..572f940d 100644
--- a/tests/hosted-runs-voice-design.test.ts
+++ b/tests/hosted-runs-voice-design.test.ts
@@ -78,7 +78,8 @@ describe("Design a voice on this install's GPUs", () => {
it("the policy's deny list keeps a voice designer off; the hosted Qwen3-TTS on fal is never priced there", async () => {
fake.policy = { ...FAKE_POLICY, pool: { deny: ["oss-voxcpm2"] } };
billing.resetBillingCache();
- expect(await poolQuote(account, design("oss-voxcpm2"), undefined)).toBeNull();
+ // Refused by the price check, so Run is off before it is pressed (an account with no GPU of its own to run it on).
+ expect((await poolQuote(account, design("oss-voxcpm2"), undefined))?.quote).toMatchObject({ allowed: false, code: "not-offered" });
expect(await poolQuote(account, design("oss-qwen3-tts"), undefined)).not.toBeNull();
expect(await poolQuote(account, { ...design("qwen-3-tts"), engine: "cloud" }, undefined)).toBeNull();
expect((await decidePlace(account, { ...design("qwen-3-tts"), engine: "cloud" }, undefined)).kind).toBe("own");