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
Security: one account can't start extra runs or hold up other accounts' jobs
Adarsh278af60a4c14
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex cbc6767d..97c23b9a 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -139,6 +139,12 @@ export async function POST(request: Request) {return refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix });}}+ // 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}`);+ return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });+ }const items = onOwn(() => createGenerations(req));// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).const all = [...new Set([...notes, ...items.flatMap((g) => g.notes ?? [])])];diff --git a/src/server/generations.ts b/src/server/generations.tsindex 7cdd3b91..f104eab4 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -1564,17 +1564,30 @@ async function pollGuarded(r: Row): Promise<void> {}}+/**+ * The jobs one tick polls (100 at most): the owner's first, then every account's in turn (each account's oldest job,+ * then each one's second, and so on), so one account's long queue never hides another account's jobs.+ */+export function rowsToPoll(limit = 100): Row[] {+ return db()+ .prepare(+ `SELECT g.* FROM generations g+ JOIN (SELECT id, ROW_NUMBER() OVER (PARTITION BY json_extract(request_json, '$.account') ORDER BY created_at) AS turn+ FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL) t ON t.id = g.id+ ORDER BY ${ACCOUNT_LAST.replace("request_json", "g.request_json")}, t.turn, g.created_at ASC LIMIT ?`,+ )+ .all(limit) as Row[];+}+async function tick(): Promise<void> {const state = globalThis.__fuobeRunner;if (!state || state.busy) return;state.busy = true;try {sweepInterrupted();- // The owner's jobs first. An account's ComfyUI may be slow to answer: its polls run on their own, so they never hold- // up the owner's (pollGuarded never polls one row twice at once).- const active = db()- .prepare(`SELECT * FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL ORDER BY ${ACCOUNT_LAST}, created_at ASC LIMIT 100`)- .all() as Row[];+ // The owner's jobs first, then the accounts' in turn. An account's ComfyUI may be slow to answer: its polls run on+ // their own, so they never hold up the owner's (pollGuarded never polls one row twice at once).+ const active = rowsToPoll();for (const r of active) if (accountOf(r)) void pollGuarded(r);await Promise.all([...active.filter((r) => !accountOf(r)).map(pollGuarded), pollTrainings().catch(() => {}), advanceDependents().catch(() => {})]);} finally {diff --git a/tests/account-run-fairness.test.ts b/tests/account-run-fairness.test.tsnew file mode 100644index 00000000..c9e46ed1--- /dev/null+++ b/tests/account-run-fairness.test.ts@@ -0,0 +1,90 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-run-fairness-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+globalThis.__fuobeTestDiskFree = 1e13;++const realFetch = globalThis.fetch;+globalThis.fetch = (async () => new Response("not stubbed", { status: 599 })) as typeof fetch;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const { ACCOUNT_LIMITS } = await import("@/server/account-files");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");++let fake: FakeComfy;+let a = "";+let cookie = "";+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0 });+ globalThis.__fuobeTestGpuPort = fake.port;+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ auth.setAccountGpu(a, { url: fake.url });+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+});+beforeEach(() => resetRates());+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const run = (image: string) => {+ const text = JSON.stringify({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [image] } });+ return generationsRoute.POST(+ new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),+ );+};+const activeRuns = () =>+ (+ 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(a) as { n: number }+ ).n;++describe("M-8: one account can't crowd out the others' runs", () => {+ it("starts at most 4 runs at once, however many requests arrive together", async () => {+ const image = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a }).url;+ const answers = await Promise.all(Array.from({ length: 8 }, () => run(image)));+ expect(answers.filter((r) => r.status === 201).length).toBeLessThanOrEqual(ACCOUNT_LIMITS.activeRuns);+ expect(answers.filter((r) => r.status === 429).length).toBeGreaterThanOrEqual(8 - ACCOUNT_LIMITS.activeRuns);+ expect(activeRuns()).toBeLessThanOrEqual(ACCOUNT_LIMITS.activeRuns);+ });++ it("polls every account in turn: a long queue of one account's jobs never hides another's", () => {+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ const [template] = gens.createGenerations({ feature: "image", modelId: "fuobe-soul", prompt: "a fox", engine: "open" });+ const row = db().prepare("SELECT * FROM generations WHERE id = ?").get(template.id) as Record<string, unknown>;+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(template.id);+ const cols = Object.keys(row);+ const insert = db().prepare(`INSERT INTO generations (${cols.join(", ")}) VALUES (${cols.map((c) => `@${c}`).join(", ")})`);+ const add = (id: string, account: string | null, createdAt: number) =>+ insert.run({ ...row, id, batch_id: null, status: "running", external_id: `ext-${id}`, created_at: createdAt, request_json: JSON.stringify({ ...JSON.parse(row.request_json as string), account: account ?? undefined }) });+ const t = Date.now() - 60_000;+ for (let i = 0; i < 150; i++) add(`busy${i}`, "account-busy", t + i);+ add("other1", "account-other", t + 1000);+ add("owner1", null, t + 2000);+ const ids = gens.rowsToPoll().map((r) => r.id);+ expect(ids.length).toBeLessThanOrEqual(100);+ expect(ids).toContain("other1");+ // The owner's first, then each account's jobs in turn.+ expect(ids[0]).toBe("owner1");+ expect(ids.indexOf("other1")).toBeLessThan(ids.indexOf("busy1"));+ });+});