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
Workers: a chain's later step keeps its run's place in line
Adarsheab3422e6eed
diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex 94bbe66a..3f9e8208 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -11,7 +11,7 @@ import { ACCOUNT_TURNTABLE, accountFinishProblem, FINISHED_3D_OPS, MODEL_FINISH_import { getSetting } from "../settings";import { absolutePath, deleteAsset, getAsset, readRef, saveFile, type Asset } from "../storage";import { tenantAccount } from "../tenant";-import { cpuSlotOf, poolWaitMs, RETRY_WINDOW_MS, ticketReady } from "./pool";+import { cpuSlotOf, poolWaitMs, RETRY_WINDOW_MS, runPlaceOf, ticketReady } from "./pool";import { createTask, endTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type TaskRow } from "./tasks";import type { WorkerRow } from "./workers";@@ -61,10 +61,6 @@ export function finishTask(generationId: string, kind: FinishKind, step = 0): Tareturn rows.find((t) => ticketOf(t)?.kind === kind && (json<{ step?: number }>(t.extra_json, {}).step ?? 0) === step) ?? null;}-/** The run's own task on the workers (its class and its place in line), when it had one. */-const runTask = (generationId: string) =>- db().prepare("SELECT class, rank_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND finish_json IS NULL ORDER BY created_at DESC LIMIT 1").get(generationId) as Pick<TaskRow, "class" | "rank_at"> | undefined;-/** The wait the run was stamped with (the billing service's limit), else this install's (FUOBE_POOL_WAIT_MIN). */function runWaitMs(generationId: string): number {const r = db().prepare("SELECT json_extract(request_json, '$.waitMs') AS w FROM generations WHERE id = ?").get(generationId) as { w: unknown } | undefined;@@ -116,7 +112,9 @@ export function queueFinish(o: {.transaction((): string => {const again = queued();if (again) return again;- const run = runTask(o.generationId);+ // The run's class and place in line (pool.ts runPlaceOf): a chain's camera path is queued for a step that has no+ // job of its own yet, and keeps the place of the steps of its run before it.+ const run = runPlaceOf(o.generationId);const now = Date.now();const t = createTask({principal,@@ -129,8 +127,8 @@ export function queueFinish(o: {pool: {pools: ["pool"],account: o.account,- class: run?.class === "paid" ? "paid" : "free",- rankAt: run?.rank_at ?? now,+ class: run?.class ?? "free",+ rankAt: run?.rankAt ?? now,lane: "small",needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },notAfter: now + runWaitMs(o.generationId),diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex ef6c5ec4..b6ac5be9 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -995,7 +995,7 @@ export function lineFacts(accountId: string | null, asked: string | null, now =*/export function poolFields(workflowId: string,- o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string } = {},+ o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string } = {},now = Date.now(),) {const index = loadIndex();@@ -1010,8 +1010,8 @@ export function poolFields(...(cpuWorkflow(workflowId) && { slot: "cpu" as const }),account: o.account,class: o.class ?? (o.account ? ("free" as const) : ("owner" as const)),- // A head start is only inside a class, and never more than a day.- rankAt: now - Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000)),+ // A head start is only inside a class, and never more than a day. A later step of a run keeps the run's place (rankAt).+ rankAt: o.rankAt ?? now - Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000)),lane,needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0, ...extra },notAfter: o.waitMs ? now + o.waitMs : undefined,@@ -1019,6 +1019,55 @@ export function poolFields(};}+/** SQL: row `g` was made by the same press of Run as the row asked about (@hold: its billing hold; with none, @batch). */+const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_json, '$.hold') IS @hold ELSE @batch IS NOT NULL AND g.batch_id IS @batch END)";++/**+ * Where a row's job waits in line on the workers as part of its run (one press of Run, which made the row and every step+ * of its chain at once):+ *+ * - `class`: the run's ("paid" when the billing service said so, else "free").+ * - `rankAt`: the run's place in line. The first job any of its rows had on the workers sets it (the row itself, or a+ * step of the same run that fed it). A later step with no such job yet keeps the time the run was made (less its head+ * start). Null for a run's first job: it waits from now.+ * - `started`: a worker took one of those jobs. The run's wait limit no longer applies then (it applies only before the+ * run's first start).+ *+ * A chain's later step and a finishing job keep the run's place this way, instead of going behind every run sent after+ * the run started. Only steps the same press made count (the same billing hold; with none, the same batch): a result+ * kept from an earlier run that a step uses gives it neither that run's place nor its start. Null: no such row.+ */+export function runPlaceOf(generationId: string): { class: "paid" | "free"; rankAt: number | null; started: boolean } | null {+ const d = db();+ const g = d+ .prepare(+ `SELECT created_at, depends_on, batch_id, json_extract(request_json, '$.hold') AS hold, json_extract(request_json, '$.class') AS cls,+ json_extract(request_json, '$.boostMs') AS boost FROM generations WHERE id = ?`,+ )+ .get(generationId) as { created_at: number; depends_on: string | null; batch_id: string | null; hold: unknown; cls: unknown; boost: unknown } | undefined;+ if (!g) return null;+ const press = { id: generationId, hold: typeof g.hold === "string" && g.hold ? g.hold : null, batch: g.batch_id };+ const jobs = d+ .prepare(+ `WITH RECURSIVE fed(id) AS (+ SELECT @id+ UNION+ SELECT d.value FROM fed JOIN generations g ON g.id = fed.id,+ json_each(CASE WHEN substr(g.depends_on, 1, 1) = '[' AND json_valid(g.depends_on) THEN g.depends_on ELSE json_array(g.depends_on) END) d+ WHERE g.depends_on IS NOT NULL AND (g.id = @id OR ${SAME_PRESS})+ )+ SELECT t.rank_at, t.claimed_at FROM fed JOIN generations g ON g.id = fed.id JOIN relay_tasks t ON t.generation_id = g.id+ WHERE (g.id = @id OR ${SAME_PRESS}) AND t.pools IS NOT NULL AND t.rank_at IS NOT NULL ORDER BY t.rank_at ASC`,+ )+ .all(press) as Pick<TaskRow, "rank_at" | "claimed_at">[];+ const boost = Math.max(0, Math.min(Number(g.boost) || 0, 24 * 60 * 60_000));+ return {+ class: g.cls === "paid" ? "paid" : "free",+ rankAt: jobs[0]?.rank_at ?? (g.depends_on ? g.created_at - boost : null),+ started: jobs.some((t) => t.claimed_at !== null),+ };+}+/*** Is a workflow light CPU work: the requirements index marks it `cpu` (no model file, no graphics memory, no card its* nodes need: a join, a trim, adding sound, a Ken Burns move, a filter).diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex ebfb8fe4..ea963c4f 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -83,7 +83,7 @@ import {type Principal,type TaskRow,} from "../computer/tasks";-import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, workersCanRun } from "../computer/pool";+import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun } from "../computer/pool";import { catalogVersion } from "../computer/catalog-version";import { ticketProblem, type JobTicket } from "@/lib/job-ticket";import { catalogKnows, ticketFor } from "@/lib/ticket-compose";@@ -279,6 +279,26 @@ export function installComfyLocal(worker: ComfyWorker = "main"): boolean {/** Said when a run on this install's GPUs can't go where it was planned (its row's own words then say it plainly). */export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this machine, so runs of accounts don't go to it.";+/**+ * Where an account's job waits in line on the workers, in its run's class (paid before free). Its run's first job: at+ * the time it came (with the billing service's head start), with the run's wait limit. A later job of the same run (a+ * chain's next step, sent once the steps before it are done): at the run's place (pool.ts runPlaceOf), and with no wait+ * limit once a worker took any of the run's jobs (the wait limit applies only before the run's first start).+ */+function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string }) {+ const stamp = runStamp();+ const run = generationId ? runPlaceOf(generationId) : null;+ return poolFields(workflowId, {+ account,+ class: stamp?.class ?? "free",+ boostMs: stamp?.boostMs,+ ...(run?.rankAt != null && { rankAt: run.rankAt }),+ waitMs: run?.started ? undefined : stamp?.waitMs || poolWaitMs(),+ size: o.size,+ catalogVersion: o.catalogVersion,+ });+}+/** Said to the owner when a job is larger than every worker's PC may ever run (its ceiling: `fuobe worker setup`). */export const NO_WORKER_FOR_SIZE = "No worker may run a job this large: each PC's limits, set with fuobe worker setup, are lower. Pick a smaller size, a shorter clip or fewer results.";@@ -1805,7 +1825,7 @@ export const comfyProvider: ProviderAdapter = {: // An account's: the lane and files they need, in its class (paid before free), in the order they came// (with the billing service's head start inside the class), with the wait set for the run.// A ticket's task goes only to a worker built for its catalog, and inside that PC's ceiling.- poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs(), size: prepared.size, catalogVersion: ticket?.catalogVersion }),+ accountPoolFields(manifest.id, computer.slice(5), generationId, { size: prepared.size, catalogVersion: ticket?.catalogVersion }),}),});// (`workers`: the run keeps its task's clocks, pool.ts, even when a poll of it fails.)diff --git a/tests/cpu-slot.test.ts b/tests/cpu-slot.test.tsindex ec9cc043..e962ed36 100644--- a/tests/cpu-slot.test.ts+++ b/tests/cpu-slot.test.ts@@ -513,6 +513,35 @@ function pathFinish(photo = smallPng()) {}describe("finishing jobs and their run", () => {+ it("a chain step's camera path waits at its run's place and in its class, from the run's first job", () => {+ const first = generation(accountId, "image-to-video");+ const rankAt = Date.now() - 20 * 60_000;+ tasks.createTask({+ principal: `acct:${accountId}`,+ generationId: first,+ graph: {},+ workflowId: GPU_WORKFLOW,+ pool: { pools: ["pool"], account: accountId, class: "paid", rankAt, lane: pool.poolLane(GPU_WORKFLOW), needs: { workflowId: GPU_WORKFLOW, files: [], packs: [], minVramBytes: 0 } },+ });+ // The step its path is drawn for waits on the first step, and has no job of its own yet. One press of Run made both:+ // they share its batch and its class.+ const step = generation(accountId, "image-to-video");+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(first, step);+ db().prepare("UPDATE generations SET batch_id = 'path-run', request_json = json_set(request_json, '$.class', 'paid') WHERE id IN (?, ?)").run(first, step);+ const id = finish.queueFinish({+ kind: "path",+ generationId: step,+ account: accountId,+ step: 0,+ inputs: [+ { slot: "photo", data: smallPng(), contentType: "image/png", name: "photo.png" },+ { slot: "depth", data: smallPng(), contentType: "image/png", name: "depth.png" },+ ],+ settings: { keys: finish.pathKeys([{ t: 0, azimuth: 0, elevation: 0, distance: 1 }, { t: 1, azimuth: 20, elevation: 4, distance: 0.8 }]), frames: 9, fps: 16 },+ });+ expect(row(id)).toMatchObject({ class: "paid", rank_at: rankAt, slot: "cpu" });+ });+it("are queued once for a run (and step), however often they are asked", () => {const gid = generation(accountId, "image-to-3d");const queue = () => finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: Buffer.from("glTF fake model bytes"), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex 6c151f3f..a86c73aa 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -50,6 +50,10 @@ const { loadManifest, comfyProvider, onComputer, NO_WORKER_FOR_LANE } = await imconst { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");const { POOL_WORDS } = await import("@/lib/relay");+const hosted = await import("@/server/hosted");+const { withRunStamp } = await import("@/server/run-stamp");+const { getModel } = await import("@/lib/catalog");+const { encodePng } = await import("@/lib/png-encode");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -262,6 +266,114 @@ describe("the billing service's class and head start", () => {});});+describe("a run's later steps keep the run's place", () => {+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const PICTURE = encodePng({ width: 64, height: 48, data: Buffer.alloc(64 * 48 * 4, 128) });+ /**+ * A row of an account's run on the workers. The rows one press of Run made share its batch (and its billing hold, when+ * a billing service set one); a later step names the step it waits for.+ */+ function runRow(o: { batch: string; hold?: string; dependsOn?: string }) {+ const gid = `run-step-${++gens}`;+ const now = Date.now();+ db()+ .prepare("INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, depends_on) VALUES (?, ?, 'image', 'oss-selftest-image', 'open', 'comfyui', 'edit', 'image', 'queued', ?, '[]', ?, ?, ?)")+ .run(gid, o.batch, JSON.stringify({ account: accountId, place: "pool", ...(o.hold && { hold: o.hold }) }), now, now, o.dependsOn ?? null);+ return gid;+ }+ /** Its job sent to the workers as a step of the run is: inside the run's stamp (its class and its wait). */+ async function sendStep(gid: string, stamp: { class?: "paid" | "free"; waitMs: number }) {+ const sent = await hosted.runOnPool(accountId, () =>+ withRunStamp({ place: "pool", ...stamp }, async () => {+ const name = (await comfyProvider.prepareFile!(PICTURE, "image/png", "me.png", route))!;+ return comfyProvider.submit({ route, input: { images: [name], seed: 5 }, generationId: gid, model: getModel("oss-selftest-image") } as never);+ }),+ );+ return rowOf(String((sent.meta as { relay: string }).relay));+ }++ it("a chain's next step keeps the run's class and place, waits past the run's wait limit behind a long line, and still runs first", async () => {+ const w = standInWorker();+ const wait = 5 * MIN;+ const first = runRow({ batch: "chain-a" });+ const one = await sendStep(first, { class: "paid", waitMs: wait });+ expect(one.not_after).not.toBeNull();+ // A worker takes step 1 (the run has started) and finishes it.+ beatAs(w);+ expect(claimAs(w)?.id).toBe(one.id);+ done(one.id);+ // Meanwhile, runs sent after this run started fill the line.+ const line = [lineTask({ account: other, class: "paid" }), lineTask({ account: other, class: "paid" }), lineTask({ account: other })];+ // Step 2, sent once step 1 is done: at the run's place, in its class, with no wait limit (the run has started).+ const two = await sendStep(runRow({ batch: "chain-a", dependsOn: first }), { class: "paid", waitMs: wait });+ expect(two.rank_at).toBe(one.rank_at);+ expect(two.class).toBe("paid");+ expect(two.not_after).toBeNull();+ expect(pool.placeInLine(two).place).toBe(1);+ // Long past the run's wait limit, it is still in line, and it is served before every run sent after the run started.+ pool.sweepPool(Date.now() + 3 * wait);+ expect(rowOf(two.id).state).toBe("waiting");+ expect(served(w)).toEqual([two.id, ...line]);+ });++ it("a step sent before any job of its run was taken keeps the run's place and still has the run's wait limit", async () => {+ standInWorker();+ const wait = 5 * MIN;+ const first = runRow({ batch: "chain-b" });+ const one = await sendStep(first, { waitMs: wait });+ const two = await sendStep(runRow({ batch: "chain-b", dependsOn: first }), { waitMs: wait });+ expect(two.rank_at).toBe(one.rank_at);+ expect(two.class).toBe("free");+ expect(two.not_after).not.toBeNull();+ pool.sweepPool(Date.now() + 2 * wait);+ expect(rowOf(two.id).state).toBe("failed");+ });++ it("a later step with no job of its run on the workers yet waits from the time its run was made", async () => {+ standInWorker();+ const wait = 5 * MIN;+ const first = runRow({ batch: "chain-c" });+ const step = runRow({ batch: "chain-c", dependsOn: first });+ // The run was made 20 minutes ago (its first step ran elsewhere, or was light work).+ db().prepare("UPDATE generations SET created_at = ? WHERE id IN (?, ?)").run(Date.now() - 20 * MIN, first, step);+ const two = await sendStep(step, { waitMs: wait });+ const made = (db().prepare("SELECT created_at FROM generations WHERE id = ?").get(step) as { created_at: number }).created_at;+ expect(two.rank_at).toBe(made);+ expect(two.not_after).not.toBeNull();+ });++ it("a step that uses a result kept from an earlier run waits as a new run: its own place, and the wait limit", async () => {+ const w = standInWorker();+ const wait = 5 * MIN;+ // An earlier run, long done: a worker took it.+ const kept = runRow({ batch: "earlier", hold: "hold-earlier" });+ const old = await sendStep(kept, { class: "paid", waitMs: wait });+ db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(Date.now() - 60 * MIN, old.id);+ beatAs(w);+ expect(claimAs(w)?.id).toBe(old.id);+ done(old.id);+ const line = [lineTask({ account: other, class: "paid", agoMs: MIN })];+ // A new run (another batch) whose step uses that result, and a rerun in the same batch under a hold of its own.+ const two = await sendStep(runRow({ batch: "later", dependsOn: kept }), { class: "paid", waitMs: wait });+ const three = await sendStep(runRow({ batch: "earlier", hold: "hold-again", dependsOn: kept }), { class: "paid", waitMs: wait });+ for (const t of [two, three]) {+ expect(t.rank_at!).toBeGreaterThan(Date.now() - MIN);+ expect(t.not_after).not.toBeNull();+ }+ expect(served(w)).toEqual([...line, two.id, three.id]);+ });++ it("a run's first job waits in the order it came, with the run's wait limit, as before", async () => {+ standInWorker();+ const wait = 5 * MIN;+ const before = Date.now();+ const t = await sendStep(runRow({ batch: "chain-d" }), { waitMs: wait });+ expect(t.rank_at!).toBeGreaterThanOrEqual(before);+ expect(t.not_after! - t.created_at).toBeGreaterThanOrEqual(wait - 1000);+ expect(t.not_after! - t.created_at).toBeLessThanOrEqual(wait + 1000);+ });+});+describe("fair share", () => {it("off: strict order; on: each account's first run goes before anyone's second, counting runs it has going", () => {const w = standInWorker();