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 run of CPU work only is free and never counted
Adarshacc1e0d13e9e
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 9c91c59d..4d5fdb86 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -174,8 +174,9 @@ export async function POST(request: Request) {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);+ // GPU or key, nor on a run of light work only, which is free): said now, before anything is checked or set aside, and+ // counted again as the run is made (admitRun).+ const over = onPool.light ? null : poolLimitRefusal(account.id, onPool.policy, addr);if (over) {unhit(`run:${account.id}`);return refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) });@@ -242,7 +243,10 @@ export async function POST(request: Request) {if (account) {const mod = await moderateRun(account, req, onPool?.planned ?? null, onPool ? "pool" : "own");if (!mod.ok) return refusedBy(mod.refusal);- if (onPool) {+ if (onPool?.light) {+ // Light work only (joins, trims): free, so nothing is set aside, and it counts against none of the policy's limits.+ stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };+ } else if (onPool) {const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps);if (!held.ok) return refusedBy(held.refusal);stamp = held.stamp;@@ -259,7 +263,7 @@ export async function POST(request: Request) {// sent until they are kept.const pool = onPool;const admitted = inScope(() => {- const r = admitRun({ accountId: account.id, pool: pool ? { policy: pool.policy, addr } : null }, () => {+ const r = admitRun({ accountId: account.id, pool: pool && !pool.light ? { policy: pool.policy, addr } : null }, () => {const run = captureRun(make);const problem = pool && stepsProblem(pool.policy, stepsOf(run.ids));if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex e657ea6f..c0d500b1 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1199,6 +1199,8 @@ export interface GenerationRequest {class?: "paid" | "free";/** Server-only: a head start in line within its class (ms), from the billing service. */boostMs?: number;+ /** Server-only: a run on this install's GPUs made of light work only (joins, trims), free and never counted. */+ light?: boolean;feature: string;presetId?: string;modelId: string;diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex d26e567c..f8a5228f 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -14,6 +14,7 @@ import {billingConfigured,cachedPolicy,forgetBalance,+ FREE_QUOTE,policy as billingPolicy,quote as billingQuote,refusalStatus,@@ -24,7 +25,6 @@ import {type RunFacts,} from "./billing";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";@@ -77,12 +77,13 @@ 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. On this install's- * GPUs: the request as it runs there (`req`, `capped` when the policy cut its outputs), its plan, its policy and the steps- * it is priced for.+ * GPUs: the request as it runs there (`req`, `capped` when the policy cut its outputs), its plan, its policy, the steps+ * it is priced for, and whether it is light work only (`light`: every step a join, a trim or the like, which is free and+ * never counted against the policy's limits).*/export type PlaceDecision =| { kind: "own" }- | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean }+ | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean; light: boolean }| { kind: "refuse"; refusal: Refusal };const OWN: PlaceDecision = { kind: "own" };@@ -107,8 +108,10 @@ const stepEndpoint = (s: PlannedStep): string | undefined => {};/**- * A ComfyUI 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.+ * A ComfyUI step of CPU work (the requirements index marks it `cpu`: no model file, no first-run download, no graphics+ * memory and no card its nodes need, such as a filter, a trim, a join, adding sound or a Ken Burns move): light work that+ * costs nothing, that every policy allows, and that is never counted. A step whose nodes run on the card (RTX Video) is+ * GPU work, model file or not.*/function freeStep(s: PlannedStep): boolean {if (s.provider !== "comfyui") return false;@@ -116,8 +119,8 @@ function freeStep(s: PlannedStep): boolean {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 needs = (endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint]).map((id) => needsOf(index, id));- return needs.length > 0 && needs.every((x) => !!x && x.files.length === 0 && x.minVramBytes === 0);+ const ids = endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint];+ return ids.length > 0 && ids.every((id) => index.workflows[id]?.cpu === true);}/**@@ -154,6 +157,13 @@ export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {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+ * at once, in line or an hour. Unknown steps (null: the plan couldn't be made) count as GPU work.+ */+export const lightRun = (steps: PlannedStep[] | null | undefined): boolean => !!steps?.length && steps.every(freeStep);+/** 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]>();@@ -319,7 +329,7 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi}// Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.if (ownOffline) return { kind: "refuse", refusal: askPlace() };- return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped };+ return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, light: lightRun(gate.steps) };}/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */@@ -479,6 +489,11 @@ export async function poolQuote(if (hasGpu && wish !== "pool") return null;return { planned, quote: notOfferedQuote(gateWords(gate.reason, !account)), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };}+ // Light work only (joins, trims): free, and never counted against the policy's limits, so the service isn't asked.+ if (lightRun(gate.steps)) {+ const queue = queueFacts(account?.id ?? null, planned.route.endpoint);+ return { planned, quote: FREE_QUOTE, line: line(queue) };+ }// Priced once for every step of a chain that uses this install's GPUs. Its facts are read as the viewer (an input's// size from its own files only: another's file reads as none, and says nothing of whether it exists).const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), ...(gate.steps && { steps: pricedSteps(gate.steps) }) };diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.tsindex f672b124..b8f30258 100644--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@ -12,8 +12,9 @@ import { db } from "./db";** - 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`).+ * the account's own GPU or its own key, nor on runs of light work only (joins, trims: free, never counted): runs at+ * once (`activeRuns`), runs waiting in line (`waiting`, no row started yet), runs made (Run pressed and admitted) in+ * the last hour (`runsPerHour`), and runs made 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.@@ -23,7 +24,7 @@ import { db } from "./db";*/const HOUR = 60 * 60_000;-/** Started runs are kept this long for the hourly counts. */+/** Runs made (let in) 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). */@@ -49,7 +50,10 @@ export function accountActiveRuns(accountId: string): 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). */+/**+ * An account's runs going now on this install's GPUs, and how many of them haven't started yet (no row of theirs has).+ * Runs of light work only (joins, trims) don't count.+ */export function poolRunCounts(accountId: string): { active: number; waiting: number } {const r = db().prepare(@@ -57,6 +61,7 @@ export function poolRunCounts(accountId: string): { active: number; waiting: numSELECT COALESCE(g.batch_id, g.id) AS k, MAX(CASE WHEN r.started_at IS NOT NULL THEN 1 ELSE 0 END) AS startedFROM generations g LEFT JOIN generation_runs r ON r.id = g.idWHERE g.status IN ('queued', 'running') AND json_extract(g.request_json, '$.account') = ? AND json_extract(g.request_json, '$.place') = 'pool'+ AND json_extract(g.request_json, '$.light') IS NOT 1GROUP BY k)`,).get(accountId) as { active: number; waiting: number };diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex dd538675..f8ee703a 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -14,6 +14,8 @@ import type { GenerationRequest } from "@/lib/catalog/types";* charged.* - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).* - `class` and `boostMs`: its class in the line ("paid" before "free") and its head start inside that class.+ * - `light`: a run on this install's GPUs made of light work only (joins, trims): free, and never counted against the+ * policy's limits on runs there (pool-limits.ts).*/export interface RunStamp {place?: "pool";@@ -27,6 +29,8 @@ export interface RunStamp {class?: "paid" | "free";/** A head start in line within its class (ms), from the billing service. */boostMs?: number;+ /** Light work only (hosted-run.ts lightRun): free, and not counted against the policy's limits. */+ light?: boolean;}declare global {@@ -42,7 +46,7 @@ export const withRunStamp = <T,>(stamp: RunStamp, fn: () => T): T => store().runexport const runStamp = (): RunStamp | undefined => store().getStore();/** The server-only fields of a request. */-export const STAMP_FIELDS = ["place", "hold", "charge", "charged", "checkOutputs", "waitMs", "class", "boostMs"] as const;+export const STAMP_FIELDS = ["place", "hold", "charge", "charged", "checkOutputs", "waitMs", "class", "boostMs", "light"] as const;/** A request with the current stamp's fields, and none of a stored request's own. */export function stamped(req: GenerationRequest): GenerationRequest {@@ -60,6 +64,7 @@ export function stamped(req: GenerationRequest): GenerationRequest {...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),...(s.class === "paid" && { class: "paid" as const }),...(s.boostMs && s.boostMs > 0 && { boostMs: s.boostMs }),+ ...(s.light && { light: true }),};}@@ -74,6 +79,7 @@ export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[numbe...(req.waitMs && { waitMs: req.waitMs }),...(req.class === "paid" && { class: "paid" as const }),...(req.boostMs && req.boostMs > 0 && { boostMs: req.boostMs }),+ ...(req.light && { light: true }),};}diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 941e2382..9f080d38 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -258,6 +258,60 @@ describe("runs at once on this install's GPUs", () => {});});+describe("light work on this install's GPUs (joins, trims, a Ken Burns move)", () => {+ /** An account's picture, uploaded as its own. */+ async function picture(cookie: string) {+ const { TINY_PNG } = await import("./helpers/fake-comfy-runner");+ const uploadsRoute = await import("@/app/api/uploads/route");+ const up = await uploadsRoute.POST(+ new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "image/png", "x-file-name": "still.png", "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }),+ );+ expect(up.status).toBe(201);+ return ((await up.json()) as { url: string }).url;+ }+ const kenBurns = (url: string) => ({ feature: "video", modelId: "oss-ken-burns", op: "still-motion", inputs: { images: [url] }, params: { duration: 4 } });++ it("is free and never counted: no price asked, nothing set aside, and the policy's limits count only GPU runs", async () => {+ withBilling({ limits: { activeRuns: 1, waiting: 0, runsPerHour: 1 } });+ const a = account();+ const url = await picture(a.cookie);+ expect(hostedRun.lightRun(hostedRun.poolSteps(a.id, kenBurns(url) as never))).toBe(true);+ expect(hostedRun.lightRun(hostedRun.poolSteps(a.id, IMAGE as never))).toBe(false);+ // RTX Video's nodes run on the card, model file or not: GPU work, priced and counted.+ const step = (modelId: string, op: string) => ({ id: "s0", modelId, op, provider: "comfyui", kind: "video", presetId: null, waits: false });+ const rtx = getModel("oss-rtx-video-upscale")!.routes.find((x) => x.provider === "comfyui")!;+ expect(hostedRun.lightRun([step("oss-rtx-video-upscale", rtx.op)])).toBe(false);+ expect(hostedRun.pricedSteps([step("oss-rtx-video-upscale", rtx.op)])).toHaveLength(1);+ expect(hostedRun.pricedSteps([step("oss-ken-burns", "still-motion")])).toEqual([]);+ // The price check before Run: free, with its place in line, and the billing service isn't asked.+ const quotes = fake.calls_of("/v1/quote").length;+ const check = (await preview(kenBurns(url), a.cookie)).body as { place?: string; quote?: { allowed: boolean; amount: number; text: string } };+ expect(check.place).toBe("pool");+ expect(check.quote).toMatchObject({ allowed: true, amount: 0, text: "" });+ expect(fake.calls_of("/v1/quote").length).toBe(quotes);+ // Two of them go in line together, with no hold, past a limit of one run at once and one an hour.+ const holds = fake.holds.size;+ const reserves = fake.calls_of("/v1/reserve").length;+ for (let i = 0; i < 2; i++) {+ const r = await post(kenBurns(url), a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.items![0].place).toBe("pool");+ // What the page gets back never says so.+ expect((r.body.items![0] as { request?: Record<string, unknown> }).request?.light).toBeUndefined();+ }+ expect(fake.calls_of("/v1/reserve").length).toBe(reserves);+ expect(fake.holds.size).toBe(holds);+ expect(limits.poolRunCounts(a.id)).toEqual({ active: 0, waiting: 0 });+ // A GPU run still has its place: they took none of its limits.+ const gpu = await post({ ...IMAGE, ...SHOWN }, a.cookie);+ expect(gpu.status, JSON.stringify(gpu.body)).toBe(201);+ expect(limits.poolRunCounts(a.id)).toEqual({ active: 1, waiting: 1 });+ // And the next GPU run meets them.+ const over = await post({ ...IMAGE, ...SHOWN }, a.cookie);+ expect(over.status).toBe(429);+ });+});+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 } });