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
Queue: a run's priority within its class, from the billing service
Adarsheaaf649b0de0
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex da59005a..7611f7d2 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1258,8 +1258,10 @@ export interface GenerationRequest {checkOutputs?: boolean;/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */waitMs?: number;- /** Server-only: the run's class in the line on this install's GPUs ("paid" goes before "free"), from the billing service. */+ /** Server-only: the run's class in the line on this install's GPUs ("paid" or "free"), from the billing service. */class?: "paid" | "free";+ /** Server-only: the run's priority within its class (0 to 9, higher first), from the billing service. */+ priority?: number;/** 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. */diff --git a/src/lib/run-priority.ts b/src/lib/run-priority.tsnew file mode 100644index 00000000..9191aad2--- /dev/null+++ b/src/lib/run-priority.ts@@ -0,0 +1,11 @@+/**+ * A run's priority within its class on this install's GPUs, from an external service (billing.ts ReserveAnswer): 0 is+ * none, a higher number goes earlier in each round of the line (src/server/computer/pool.ts smartLine).+ */+export const MAX_PRIORITY = 9;++/** A priority as it may be kept: a whole number from 0 to MAX_PRIORITY (anything else is 0). */+export function cleanPriority(v: unknown): number {+ const n = typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0;+ return Math.max(0, Math.min(MAX_PRIORITY, n));+}diff --git a/src/server/billing.ts b/src/server/billing.tsindex c09ae800..b02c0665 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -245,8 +245,13 @@ export type ReserveAnswer =/** The longest the run may wait before a worker first takes it (ms; 0: the install's own limit). */maxWaitMs: number;pools?: string[];- /** The run's class in the line: "paid" goes before "free" (absent: "free"). */+ /** The run's class in the line: "paid" or "free" (absent: "free"). */class?: "paid" | "free";+ /**+ * The run's priority within its class, from an external service: a whole number from 0 (none, the same as absent)+ * to 9, higher first in each round of the line (src/lib/run-priority.ts; anything else is read as 0).+ */+ priority?: number;text: string;/** The hold is made, and the run waits until then (epoch ms) before it enters the line (absent: at once). */startAt?: number;diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex 68b0e611..a19a720d 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -94,7 +94,7 @@ export function queueFinish(o: {settings: Record<string, unknown>;step?: number;/** Its class and place in the line, in place of the run's own (a preview made for an older result goes last). */- place?: { class: "paid" | "free" | "owner"; rankAt: number };+ place?: { class: "paid" | "free" | "owner"; rankAt: number; priority?: number };}): string {const principal: Principal = o.account ? `acct:${o.account}` : "owner";const queued = () => {@@ -139,6 +139,7 @@ export function queueFinish(o: {pools: ["pool"],account: o.account,class: run?.class ?? (o.account ? "free" : "owner"),+ ...(run?.priority && { priority: run.priority }),rankAt: run?.rankAt ?? now,lane: "small",needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex e2cc4b9e..017c7084 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -8,6 +8,7 @@ import { fileChoices, hasVariants, pickFiles, swapGraphFiles, type FileChoice }import type { FileKey } from "@/lib/gpu/types";import { POOL_WORDS, RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";import { runtimeFileKeys } from "@/lib/runtime-files";+import { cleanPriority } from "@/lib/run-priority";import { APPS, MODELS } from "@/lib/catalog";import { laneName, type LaneName } from "@/lib/lane-names";import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";@@ -2020,12 +2021,13 @@ export function lineFacts(accountId: string | null, asked: string | null, now =}/**- * What a task for workers stores: its lane, its needs, its class and its place in line. A person's run is "free" unless- * the billing service said "paid"; the owner's own jobs are the "owner" class, served after every person's.+ * What a task for workers stores: its lane, its needs, its class, its priority and its place in line. A person's run is+ * "free" unless the billing service said "paid", with the priority it gave (none: 0); the owner's own jobs are the+ * "owner" class, served after every person's.*/export function poolFields(workflowId: string,- o: { account?: string; class?: "paid" | "free" | "owner"; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string; graphSha?: boolean; runtime?: FileNeed[] } = {},+ o: { account?: string; class?: "paid" | "free" | "owner"; priority?: number; boostMs?: number; rankAt?: number; waitMs?: number; onlyWorker?: string; size?: Needs["size"]; catalogVersion?: string; graphSha?: boolean; runtime?: FileNeed[] } = {},now = Date.now(),) {const index = loadIndex();@@ -2042,6 +2044,8 @@ export function poolFields(...(cpuWorkflow(workflowId) && { slot: "cpu" as const }),account: o.account,class: cls,+ // Its priority within its class (the billing service's), for people's runs only.+ ...(cls !== "owner" && cleanPriority(o.priority) > 0 && { priority: cleanPriority(o.priority) }),// A head start is only for people's runs, only inside their class, and never more than a day: the owner's own jobs// stand in line in the order they came. A later step of a run keeps the run's place (rankAt).rankAt: o.rankAt ?? now - (cls === "owner" ? 0 : Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000))),@@ -2059,7 +2063,7 @@ const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_jso* 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").+ * - `class`: the run's ("paid" when the billing service said so, else "free"), and `priority`: the one it gave (0: none).* - `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 row with no such job yet keeps the time the run was made (less its head start):* a run's first job waits in the order it came, and so does one sent again after its first send was cut off before@@ -2074,14 +2078,14 @@ const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_jso* 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; placed: boolean; started: boolean; later: boolean } | null {+export function runPlaceOf(generationId: string): { class: "paid" | "free"; priority: number; rankAt: number | null; placed: boolean; started: boolean; later: 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 = ?`,+ json_extract(request_json, '$.boostMs') AS boost, json_extract(request_json, '$.priority') AS prio 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;+ .get(generationId) as { created_at: number; depends_on: string | null; batch_id: string | null; hold: unknown; cls: unknown; boost: unknown; prio: 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@@ -2110,6 +2114,7 @@ export function runPlaceOf(generationId: string): { class: "paid" | "free"; rank.get(press);return {class: g.cls === "paid" ? "paid" : "free",+ priority: cleanPriority(g.prio),rankAt: jobs[0]?.rank_at ?? g.created_at - boost,placed: jobs.length > 0,started: jobs.some((t) => t.claimed_at !== null),diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 3c8f0ca7..c3a12a03 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -28,6 +28,7 @@ import {cleanNodeTitle,} from "@/lib/relay";import { reasonText } from "@/lib/comfy-reason";+import { cleanPriority } from "@/lib/run-priority";import { cleanNodeTimes } from "@/lib/node-times";import { trackReport, type LiveProgress } from "@/lib/run-progress";import type { FinishTicket } from "@/lib/finish-ticket";@@ -198,6 +199,10 @@ export interface TaskRow {worker_id: string | null;/** Its class in the line: "paid", "free" (people's runs) or "owner" (the owner's own jobs, served last). NULL: from before classes, read as "owner" with no account and "free" with one. */class: string | null;+ /** The run's priority within its class, from an external service (0 or absent: none; higher first, at most 9). */+ priority?: number | null;+ /** 1: one attempt of it failed (it stalled, or ran past its run limit), and it waits at the back for its last try. */+ failed_once?: number | null;/** Its live progress as JSON (taskProgress), and when its latest preview picture came (null: none kept). */progress_json: string | null;preview_at: number | null;@@ -487,7 +492,7 @@ export interface NewTask {/** More to keep with it (a finishing job's step). */extra?: Record<string, unknown>;/** For workers (pool.ts): the pools that may take it, and what they need to. */- pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string; slot?: "cpu" };+ pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; priority?: number; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string; slot?: "cpu" };}/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */@@ -501,8 +506,8 @@ export function createTask(t: NewTask): { id: string; promptId: string } {const pool = t.pool;d.prepare(`INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,- account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json, finish_json, slot)- VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json, finish_json, slot, priority)+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,).run(id,t.principal,@@ -528,6 +533,7 @@ export function createTask(t: NewTask): { id: string; promptId: string } {t.ticket ? JSON.stringify(t.ticket) : null,t.finish ? JSON.stringify(t.finish) : null,pool?.slot ?? null,+ cleanPriority(pool?.priority),);const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];let n = 0;diff --git a/src/server/db.ts b/src/server/db.tsindex 3df784e5..1a3e12a1 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1160,6 +1160,8 @@ const RELAY_COLUMNS: [string, string, string][] = [["relay_workers", "asked_no_stream", "INTEGER NOT NULL DEFAULT 0"],// The last beat at which a worker was on (pool.ts capacityLimits).["relay_workers", "available_at", "INTEGER"],+ // A run's priority within its class, from an external service (0: none; higher first: pool.ts smartLine).+ ["relay_tasks", "priority", "INTEGER NOT NULL DEFAULT 0"],];declare global {diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 20d53022..ab90f3d5 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -63,6 +63,7 @@ import { runAsTenant } from "./tenant";import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";import { ADD_KEY_HEADER } from "@/lib/your-keys";import type { Place } from "@/lib/place-name";+import { cleanPriority } from "@/lib/run-priority";import { placeFor, placeOfAccount } from "./place-name";import { rememberedPlace } from "./run-on";import { siteFallbackOn } from "./site-fallback";@@ -813,8 +814,7 @@ export async function renewalAt(a: { code: string; quote?: Quote }, account: Acc/*** The stamp fields a reserve's answer gives a run: its hold, the words for its charge, whether anything was set aside,- * its wait limit (the policy's `giveUp` wins), and its class and head start in the line (a paid run goes before every- * free one).+ * its wait limit (the policy's `giveUp` wins), and its class, priority and head start in the line.*/export function heldStamp(a: Extract<ReserveAnswer, { ok: true }>, giveUp: number | undefined): RunStamp {const boost = Number(a.boostMs);@@ -825,6 +825,7 @@ export function heldStamp(a: Extract<ReserveAnswer, { ok: true }>, giveUp: numbe...(Number(a.amount) > 0 && { charged: true }),...(giveUp === undefined && a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),...(a.class === "paid" && { class: "paid" as const }),+ ...(cleanPriority(a.priority) > 0 && { priority: cleanPriority(a.priority) }),...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),};}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 192e949f..8373fcb7 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -320,6 +320,7 @@ function accountPoolFields(workflowId: string, account: string, generationId: streturn poolFields(workflowId, {account,class: stamp?.class ?? "free",+ priority: stamp?.priority,boostMs: stamp?.boostMs,...(run?.rankAt != null && { rankAt: run.rankAt }),...(pressed !== undefined && { rankAt: pressed }),diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex 34fdb0f3..a706dbde 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -1,6 +1,7 @@import "server-only";import { AsyncLocalStorage } from "node:async_hooks";import type { GenerationRequest } from "@/lib/catalog/types";+import { cleanPriority } from "@/lib/run-priority";/*** What the server decided about one run before it was created, stamped on every row the run makes (its jobs, and every@@ -13,7 +14,8 @@ import type { GenerationRequest } from "@/lib/catalog/types";* - `charged`: the hold set an amount aside (a free run's sets aside nothing), so a run that ends early says it wasn't* 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.+ * - `class`, `priority` and `boostMs`: its class in the line ("paid" or "free"), its priority within its class+ * (src/lib/run-priority.ts) 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).* - `standalone`: an account's run made on its own in a studio (POST /api/generations, Image to 3D's route), not by a@@ -32,6 +34,8 @@ export interface RunStamp {waitMs?: number;/** Its class in the line on this install's GPUs, from the billing service (none: "free"). */class?: "paid" | "free";+ /** Its priority within its class, from the billing service (none: 0). */+ priority?: number;/** 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. */@@ -58,7 +62,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", "light", "standalone"] as const;+export const STAMP_FIELDS = ["place", "hold", "charge", "charged", "checkOutputs", "waitMs", "class", "priority", "boostMs", "light", "standalone"] as const;/** A request with the current stamp's fields, and none of a stored request's own. */export function stamped(req: GenerationRequest): GenerationRequest {@@ -75,6 +79,7 @@ export function stamped(req: GenerationRequest): GenerationRequest {...(s.checkOutputs && { checkOutputs: true }),...(waitOf(s.waitMs) !== undefined && { waitMs: s.waitMs }),...(s.class === "paid" && { class: "paid" as const }),+ ...(cleanPriority(s.priority) > 0 && { priority: cleanPriority(s.priority) }),...(s.boostMs && s.boostMs > 0 && { boostMs: s.boostMs }),...(s.light && { light: true }),...(s.standalone && { standalone: true }),@@ -94,6 +99,7 @@ export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[numbe...(req.checkOutputs && { checkOutputs: true }),...(waitOf(req.waitMs) !== undefined && { waitMs: req.waitMs }),...(req.class === "paid" && { class: "paid" as const }),+ ...(cleanPriority(req.priority) > 0 && { priority: cleanPriority(req.priority) }),...(req.boostMs && req.boostMs > 0 && { boostMs: req.boostMs }),...(req.light && { light: true }),...(req.standalone && { standalone: true }),