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: each attempt keeps its own clock, and a run back in line shows In line alone
Adarsh71a471ce9577
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 6d6aefa6..1bd76ee5 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -316,7 +316,7 @@ in that class came.| Setting | What it does | Default ||---|---|---|-| `runCeilingS` | `{ default, lanes }`: the longest one attempt at a job may run, in seconds, with a value per lane that overrides the default. It ends the run's own clock, and a worker's run limit is never longer | `{ "default": 2700, "lanes": {} }` (45 minutes) |+| `runCeilingS` | `{ default, lanes }`: the longest one attempt at a job may run, in seconds, with a value per lane that overrides the default. A worker's run limit is never longer, and the run's own clock is set from it (below) | `{ "default": 2700, "lanes": {} }` (45 minutes) || `ownerWaitLimitS` | How long the owner's own jobs may wait before a worker first takes them, in seconds. `null`: no limit | `null` || `fairShare` | Each class goes round its accounts (above). Off: strict order | `false` || `pickAllowanceMs` | How long a job in a worker's warm lane may go ahead of an older one (above). 0: strict order | `0` |@@ -328,9 +328,19 @@ If a worker stops answering for 2 minutes, its ComfyUI is down for 2 minutes, or15 minutes after the worker claimed it (or after its ComfyUI lost the job and the worker sent it again), its job goesback to the queue. The worker is added to the job's`tried_json` list, and the input reads start again. The old worker's late calls get 409, and it deletes that prompt.-After the third lost attempt, the job fails. A job that is put back because of a pause does not count as an attempt,-and neither does one lost while the worker's PC slept, once the worker says so (`slept` in its next beat).-The run's own clocks follow the queue's: each attempt gets its own running time.+If the worker's ComfyUI loses the job (it restarted), the worker sends it again once on the same claim. If ComfyUI loses+it a second time on that claim, the job goes back to the queue as a lost attempt. After the third lost attempt, the job+fails. A job that is put back because of a pause does not count as an attempt, and neither does one lost while the+worker's PC slept, once the worker says so (`slept` in its next beat).++The run's own clocks follow the queue's, even when a check of the run fails. No wait limit of the run's own ends a job+for the workers, and each attempt gets its own time from its claim: 15 minutes to send the files, the lane's run+ceiling twice (one more try after running out of memory) and 15 minutes to send the results. The worker's run limit+and stall limit, and the sending clock, end an attempt long before that. While a job is back in the queue, it shows no+progress from the attempt before.++A job of the owner's that no worker is allowed to run is refused when it is sent, as an account's run is. Allow its+lane for a worker first.**The place in line.** A waiting job's place counts every job that a worker able to run it would serve first, whateverits lane: one GPU serves every lane it has in this order. The wait adds the rest of the jobs those workers run now,diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 8989d562..4fa3a67e 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -63,6 +63,21 @@ const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class";/** A task a worker took that is still sending its files to its ComfyUI this long after the claim goes back in line. */export const SENDING_MS = 15 * 60_000;+/** The time a worker has to send a finished job's results up. */+export const SAVING_MS = 15 * 60_000;+/**+ * The longest one attempt of a worker's task may last, from its claim: SENDING_MS to send its files, its lane's run+ * ceiling twice (a worker sends a job once more after its ComfyUI ran out of memory, with its run limit counted again)+ * and SAVING_MS to send its results. The worker's own run limit and stall rule, and the sending clock, end an attempt+ * well before; this is only the run's backstop (generations.ts).+ */+export const attemptLimitMs = (lane?: string | null) => SENDING_MS + 2 * runCeilingMs(lane) + SAVING_MS;+/** When the attempt a worker holds now must have ended (none while the task waits in line). */+export function attemptDeadline(t: Pick<TaskRow, "state" | "claimed_at" | "lane">): { at: number; ms: number } | undefined {+ if (t.state === "waiting" || !t.claimed_at) return undefined;+ const ms = attemptLimitMs(t.lane);+ return { at: t.claimed_at + ms, ms };+}const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");@@ -653,9 +668,22 @@ function memo<A, R>(fn: (a: A) => R): (a: A) => R {// ---------------------------------------------------------------------------// Making tasks for workers+/** The catalog's lanes, worked out once for each requirements index (loadIndex keeps one until its file changes). */+const lanesByIndex = new WeakMap<ReturnType<typeof loadIndex>, { lanes: ReturnType<typeof allLanes>; byWorkflow: Map<string, string> }>();+function catalogLanes(): { lanes: ReturnType<typeof allLanes>; byWorkflow: Map<string, string> } {+ const index = loadIndex();+ let kept = lanesByIndex.get(index);+ if (!kept) {+ const lanes = allLanes(index, sha);+ kept = { lanes, byWorkflow: new Map(lanes.flatMap((l) => l.workflows.map((id) => [id, l.lane] as const))) };+ lanesByIndex.set(index, kept);+ }+ return kept;+}+/** The lane a workflow's tasks go in (a workflow the catalog doesn't know: the small lane). */export function poolLane(workflowId: string): string {- return allLanes(loadIndex(), sha).find((l) => l.workflows.includes(workflowId))?.lane ?? "small";+ return catalogLanes().byWorkflow.get(workflowId) ?? "small";}/**@@ -899,4 +927,4 @@ export function queueView(now = Date.now()) {}/** Every lane in this studio's catalog, for the owner to allow per worker. */-export const lanesCatalog = () => allLanes(loadIndex(), sha).map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length }));+export const lanesCatalog = () => catalogLanes().lanes.map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length }));diff --git a/src/server/generations.ts b/src/server/generations.tsindex e1d35446..8e0657d3 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -184,7 +184,8 @@ export function toGeneration(r: Row): Generation {op: r.op,kind: r.kind,status: r.status,- progress: r.progress,+ // In line on this install's GPUs (again, after an attempt): no progress.+ progress: pool && r.status === "queued" ? null : r.progress,message: pool ? poolMessage(r) : r.message,prompt: r.prompt,request,@@ -243,7 +244,8 @@ const PLAIN_POOL_ERRORS = (() => {let set: Set<string> | undefined;return () =>(set ??= new Set<string>([- ...Object.values(ACCOUNT_MESSAGES),+ // The account's own side only: its files, and a file it sent (never the server's own state, such as low disk).+ ...(["imageTooBig", "imageTooManyPixels", "audioTooBig", "videoTooBig", "fileTooBig", "wrongType", "uploadsFull", "filesFull"] as const).map((k) => ACCOUNT_MESSAGES[k]),RELAY_WORDS.stopped,POOL_WORDS.failed,BLOCKED_CARD_MESSAGE,@@ -2298,17 +2300,21 @@ async function pollOne(r: Row): Promise<void> {recordSubmission(r.id, res.sentAt);run = { submitted_at: res.sentAt, started_at: null };}- // A job for the workers keeps its task's own clocks (its wait limit until a worker first takes it): back in line- // after an attempt, its next attempt gets its own running time, and no wait limit of the runner's ends it.- const ownClocks = !!res && (res.state === "queued" || res.state === "running") && !!res.ownClocks;+ // A job for the workers keeps its task's own clocks (pool.ts): its wait limit until a worker first takes it, then+ // the deadline of the attempt a worker holds, from its claim (the worker's own run limit and stall rule end an+ // attempt first). No clock of the runner's ends it, even when a poll of it fails (the next tick asks again).+ const workerJob = typeof ctx.meta.relay === "string" && (ctx.meta.workers === true || onPool);+ const ownClocks = workerJob || (!!res && (res.state === "queued" || res.state === "running") && !!res.ownClocks);if (ownClocks && res?.state === "queued" && run.started_at) {db().prepare("UPDATE generation_runs SET started_at = NULL WHERE id = ?").run(r.id);run = { ...run, started_at: null };}// A job that has just left the queue gets its full running time from now.const startsNow = res?.state === "running" && !run.started_at;- const limitMs = runningLimitMs(r, ctx.meta, account, onPool);- const overdue = run.started_at ? now - run.started_at > limitMs : !ownClocks && !startsNow && now - run.submitted_at > queueMs;+ const deadline = ownClocks && (res?.state === "queued" || res?.state === "running") ? res.deadline : undefined;+ // (Worked out only for a started job: a queued one never reads it.)+ const limitMs = ownClocks ? (deadline?.ms ?? 0) : run.started_at ? runningLimitMs(r, ctx.meta, account, onPool) : 0;+ const overdue = ownClocks ? !!deadline && now > deadline.at : run.started_at ? now - run.started_at > limitMs : !startsNow && now - run.submitted_at > queueMs;if (overdue) {// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.await adapterFor(r.provider, account)@@ -2316,7 +2322,7 @@ async function pollOne(r: Row): Promise<void> {.catch(() => {});update(r.id, {status: "failed",- error: run.started_at+ error: run.started_at || deadline? `Timed out after ${Math.round(limitMs / 60_000)} minutes`: res?.state === "queued" && res.timeoutError? res.timeoutError@@ -2332,7 +2338,8 @@ async function pollOne(r: Row): Promise<void> {}if (!res) throw pollError;if (startsNow) db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now(), r.id);- update(r.id, { status: res.state, progress: res.progress ?? r.progress, message: res.message ?? null });+ // Back in line (a worker paused, went quiet or gave it back): no progress of the attempt before is kept.+ update(r.id, { status: res.state, progress: ownClocks && res.state === "queued" ? null : (res.progress ?? r.progress), message: res.message ?? null });return;}if (res.state === "failed") {diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex bd7cd2fa..9ed625be 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -113,7 +113,7 @@ import {type Principal,type TaskRow,} from "../computer/tasks";-import { poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords } from "../computer/pool";+import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, workersAllowed } from "../computer/pool";import { ownerWaitMs } from "../queue-settings";export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");@@ -270,6 +270,9 @@ 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.";+/** Said to the owner when no worker is allowed the lane of a job sent to the workers. */+export const NO_WORKER_FOR_LANE = "No worker is allowed to run this model yet. Allow its lane for a worker in Settings → Workers.";+/*** Every VideoHelperSuite save node of a graph for the workers saves no metadata: the prompt and the machine's own clock never* travel inside a result. Returns the graph changed in place.@@ -2431,14 +2434,16 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,if (!t.pools) return pollTask(principal, t, meta, manifest, made);// A run on the workers: while it waits, its place in line; once a worker has it, that worker's reports (a worker that// goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer"). It keeps its task's clocks- // (pool.ts): its wait limit until a worker first takes it, then each attempt's own running time. Back in line after an- // attempt (a worker paused, went quiet, gave it back), it shows its kept place as any waiting run does, and once a- // worker has it again, the usual words: never a restart.+ // (pool.ts): its wait limit until a worker first takes it, then the deadline of each attempt from its claim. Back in+ // line after an attempt (a worker paused, went quiet, gave it back), it shows its kept place as any waiting run does,+ // and once a worker has it again, the usual words: never a restart.const res: PollResult = t.state === "waiting" ? { state: "queued", message: poolWaitWords(t) } : await pollTask(principal, t, meta, manifest, made);if (res.state !== "queued" && res.state !== "running") return res;+ const deadline = attemptDeadline(t);+ const clocks = { ownClocks: true as const, ...(deadline && { deadline }) };// An account's run says only where it is: in line, or working on it (the owner's own runs keep the workers' words).- if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ownClocks: true };- return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ownClocks: true } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ownClocks: true };+ if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ...clocks };+ return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ...clocks } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ...clocks };}/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */@@ -2556,6 +2561,9 @@ export const comfyProvider: ProviderAdapter = {if (computer) {const metaBatch = !!meta.metaBatch;const forPool = onWorkers(computer);+ // The owner's job that no worker is allowed to run would wait with no end (the owner's jobs have no wait limit+ // unless the owner sets one): it is refused now, as an account's run is.+ if (forPool && computer === "owner" && !workersAllowed(poolLane(manifest.id))) throw new ProviderError(NO_WORKER_FOR_LANE);const task = createTask({principal: computer,generationId,@@ -2578,7 +2586,8 @@ export const comfyProvider: ProviderAdapter = {poolFields(manifest.id, { account: computer.slice(5), class: runStamp()?.class ?? "free", boostMs: runStamp()?.boostMs, waitMs: runStamp()?.waitMs || poolWaitMs() }),}),});- return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };+ // (`workers`: the run keeps its task's clocks, pool.ts, even when a poll of it fails.)+ return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id, ...(forPool && { workers: true }) }, payload: wf };}// A run on this install's workers with no account behind it is never sent anywhere.if (onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);diff --git a/src/server/providers/types.ts b/src/server/providers/types.tsindex 259b09ed..594bd173 100644--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@ -32,11 +32,12 @@ export interface RemoteOutput {* What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the* queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and* what was missing when it failed (`fix`: the tile's "Fix it"). A job for the workers keeps its task's own clocks- * (`ownClocks`): the runner then sets no wait limit of its own, and its running time counts from the attempt now running.+ * (`ownClocks`): the runner then sets no wait limit of its own, and ends it only past the deadline of the attempt a+ * worker holds now (`deadline`: when, and how long that attempt may last).*/export type PollResult =- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true }- | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true }+ | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true; deadline?: { at: number; ms: number } }+ | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true; deadline?: { at: number; ms: number } }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }| { state: "failed"; error: string; fix?: GenerationFix };diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex a9baa990..f5d986d3 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -57,6 +57,7 @@ const { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");const { ComputerRunner } = await import("@/lib/computer-runner");const { POOL_WORDS } = await import("@/lib/relay");+const { ACCOUNT_MESSAGES } = await import("@/server/account-files");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -379,6 +380,39 @@ describe("the line", () => {expect(g.message).toBe(POOL_WORDS.inLine);});+ it("back in line after an attempt, it shows In line with no progress from the attempt before", async () => {+ const w = standInWorker();+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" });+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const t = (await until(() => taskOf(id)))!;+ beatAs(w);+ const got = claimAs(w)!;+ expect(got.id).toBe(t.id);+ tasks.report(rowOf(t.id), { event: "sent", promptId: got.promptId }, () => ({ error: "unused" }));+ tasks.report(rowOf(t.id), { event: "running", value: 3, max: 4 }, () => ({ error: "unused" }));+ const working = await until(() => {+ const g = getGeneration(id);+ return g?.status === "running" && (g.progress ?? 0) > 0 ? g : null;+ });+ expect(working?.message).toBe(POOL_WORDS.working);+ // The worker pauses at once (its owner pressed the pause): the run goes back in line.+ pool.workerBeat(+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: true, why: "here-now", until: null }, gpu: {}, running: [{ task: t.id }], stopped: [] }),+ );+ const back = await until(() => {+ const g = getGeneration(id);+ return g?.status === "queued" ? g : null;+ });+ expect(back?.message).toBe(POOL_WORDS.inLine);+ expect(back?.progress).toBeNull();+ expect((db().prepare("SELECT progress FROM generations WHERE id = ?").get(id) as { progress: number | null }).progress).toBeNull();+ // A row in line never shows a progress it kept from before.+ db().prepare("UPDATE generations SET progress = 0.6 WHERE id = ?").run(id);+ expect(getGeneration(id)?.progress).toBeNull();+ });+it("place and wait count every task ahead in the order the workers serve them, whatever its lane", () => {const w = standInWorker();const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);@@ -417,6 +451,15 @@ describe("what an account reads about its run", () => {// Fuobe's own words about the account's side stay as they are.db().prepare("UPDATE generations SET error = ? WHERE id = ?").run("Your files have reached 3 GB. Delete some runs to make room.", id);expect(getGeneration(id)!.error).toBe("Your files have reached 3 GB. Delete some runs to make room.");+ for (const words of [ACCOUNT_MESSAGES.imageTooBig, ACCOUNT_MESSAGES.wrongType, ACCOUNT_MESSAGES.uploadsFull]) {+ db().prepare("UPDATE generations SET error = ? WHERE id = ?").run(words, id);+ expect(getGeneration(id)!.error).toBe(words);+ }+ // Words about the server's own state (its disk, how busy it is) are not the account's to act on: one plain sentence.+ for (const words of [ACCOUNT_MESSAGES.diskLow, ACCOUNT_MESSAGES.finishBusy, ACCOUNT_MESSAGES.finishRate, ACCOUNT_MESSAGES.uploadsBusy]) {+ db().prepare("UPDATE generations SET error = ? WHERE id = ?").run(words, id);+ expect(getGeneration(id)!.error, words).toBe(POOL_WORDS.failed);+ }});it("its output check is part of Working, and a stopped run says Not charged only when its hold set something aside", () => {diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex 983bfcbf..1d2177ee 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -45,9 +45,10 @@ const tasks = await import("@/server/computer/tasks");const pool = await import("@/server/computer/pool");const billing = await import("@/server/billing");const qs = await import("@/server/queue-settings");-const { loadManifest, comfyProvider, onComputer } = await import("@/server/providers/comfyui");+const { loadManifest, comfyProvider, onComputer, NO_WORKER_FOR_LANE } = await import("@/server/providers/comfyui");const { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");+const { POOL_WORDS } = await import("@/lib/relay");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -194,6 +195,23 @@ describe("classes", () => {expect(second.not_after! - second.created_at).toBeGreaterThanOrEqual(3600_000 - 1000);expect(second.not_after! - second.created_at).toBeLessThanOrEqual(3600_000 + 1000);});++ it("the owner's job that no worker is allowed to run is refused at once, never left waiting", async () => {+ const w = standInWorker();+ const workflow = loadManifest().workflows[0].id;+ const lane = pool.poolLane(workflow);+ const route = { provider: "comfyui", endpoint: workflow, op: "t2i" } as never;+ const submit = (gid: string) => onComputer("owner", () => comfyProvider.submit({ route, input: { prompt: "a lighthouse" } as never, generationId: gid } as never));+ const others = Object.fromEntries(allLanes(loadIndex(), sha).filter((l) => l.lane !== lane).map((l) => [l.lane, { delayMs: 0 }]));+ pool.patchWorker(w.id, { allow: others });+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;+ await expect(submit("owner-gen-refused")).rejects.toThrow(NO_WORKER_FOR_LANE);+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);+ // Allowed the lane again (paused or not), it goes in line.+ pool.patchWorker(w.id, { allow: { ...others, [lane]: { delayMs: 0 } }, paused: true });+ const t = rowOf(String(((await submit("owner-gen-allowed")).meta as { relay: string }).relay));+ expect(t.state).toBe("waiting");+ });});describe("the billing service's class and head start", () => {@@ -280,6 +298,17 @@ describe("the pick allowance", () => {});describe("the run ceiling", () => {+ it("a workflow's lane is worked out once for the catalog, so the runner reads it at no cost on every poll", () => {+ const lanes = allLanes(loadIndex(), sha);+ for (const l of lanes) for (const id of l.workflows) expect(pool.poolLane(id), id).toBe(l.lane);+ expect(pool.poolLane("no-such-workflow")).toBe("small");+ expect(pool.lanesCatalog().map((l) => l.lane)).toEqual(lanes.map((l) => l.lane));+ // Working the lanes out takes milliseconds each time; a thousand lookups take far less than that many times over.+ const t0 = performance.now();+ for (let i = 0; i < 1000; i++) pool.poolLane(lanes[i % lanes.length].workflows[0]);+ expect(performance.now() - t0).toBeLessThan(1000);+ });+it("a worker's run limit never passes its lane's ceiling, and with no measured run it is the ceiling", () => {const [a, b] = allLanes(loadIndex(), sha).map((l) => l.lane);expect(pool.runLimitMs(null, a)).toBe(45 * MIN);@@ -291,10 +320,10 @@ describe("the run ceiling", () => {expect(pool.runLimitMs(15 * MIN, b, 5 * MIN)).toBe(50 * MIN);});- it("a run longer than 45 minutes in a lane with a 60 minute ceiling goes on, and past 60 it stops", async () => {- const w = standInWorker();+ /** An account's run through the run route, and its task once the runner made it. */+ async function accountRun(prompt: string) {const r = await generationsRoute.POST(- new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a long one" }) }),+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt }) }),);const body = (await r.json()) as { items?: { id: string }[] };expect(r.status, JSON.stringify(body)).toBe(201);@@ -305,23 +334,101 @@ describe("the run ceiling", () => {await new Promise((res) => setTimeout(res, 20));t = taskOf(id);}- qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [t!.lane!]: 3600 } } });+ expect(t).toBeDefined();+ return { id, t: t! };+ }+ const tick = () => globalThis.__fuobeRunner?.tick();+ const claimedAgo = (taskId: string, ms: number) => tasks.setTask(taskId, { claimed_at: Date.now() - ms });+ const startedAgo = (id: string, ms: number) => db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);++ it("a run longer than 45 minutes in a lane with a 60 minute ceiling goes on; past 60 its worker gives it back, and the run's own clock only backs that up", async () => {+ const w = standInWorker();+ const { id, t } = await accountRun("a long one");+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [t.lane!]: 3600 } } });beatAs(w);const got = claimAs(w)!;- expect(got.id).toBe(t!.id);+ expect(got.id).toBe(t.id);expect(got.runLimitMs).toBe(60 * MIN);- tasks.setTask(t!.id, { state: "running", started_at: Date.now() });- await globalThis.__fuobeRunner?.tick();+ tasks.setTask(t.id, { state: "running", started_at: Date.now() });+ await tick();expect(getGeneration(id)?.status).toBe("running");- const startedAgo = (ms: number) => db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - ms, id);- startedAgo(50 * MIN);+ // 50 minutes, then 61, into the attempt: the worker's run limit decides, not the run's clock.+ for (const ago of [50 * MIN, 61 * MIN]) {+ claimedAgo(t.id, ago);+ startedAgo(id, ago);+ beatAs(w);+ await tick();+ expect(getGeneration(id)?.status).toBe("running");+ }+ // An attempt that outlasts every clock of the worker's (its files' sending time, the ceiling twice and the time to+ // send its results) is ended by the run's own clock.+ expect(pool.attemptLimitMs(t.lane)).toBe(pool.SENDING_MS + 2 * 60 * MIN + pool.SAVING_MS);+ claimedAgo(t.id, pool.attemptLimitMs(t.lane) + MIN);beatAs(w);- await globalThis.__fuobeRunner?.tick();+ await tick();+ expect(getGeneration(id)?.status).toBe("failed");+ expect(getGeneration(id)?.error).toBe(POOL_WORDS.failed);+ });++ it("a job a worker gives back and takes again between two polls gets its whole time again", async () => {+ const w = standInWorker();+ const { id, t } = await accountRun("given back and taken again");+ beatAs(w);+ const first = claimAs(w)!;+ expect(first.id).toBe(t.id);+ tasks.report(rowOf(t.id), { event: "sent", promptId: first.promptId }, () => ({ error: "unused" }));+ tasks.report(rowOf(t.id), { event: "running", value: 1, max: 4 }, () => ({ error: "unused" }));+ await tick();expect(getGeneration(id)?.status).toBe("running");- startedAgo(61 * MIN);+ // The first attempt began long ago, past the lane's ceiling (45 minutes).+ claimedAgo(t.id, 70 * MIN);+ startedAgo(id, 70 * MIN);+ // The worker gives it back (it stalled) and takes it again before the next poll.+ tasks.report(rowOf(t.id), { event: "give-back", why: "stalled" }, () => ({ error: "unused" }));+ expect(rowOf(t.id).state).toBe("waiting");beatAs(w);- await globalThis.__fuobeRunner?.tick();- expect(getGeneration(id)?.status).toBe("failed");+ expect(claimAs(w)?.id).toBe(t.id);+ await tick();+ const g = getGeneration(id)!;+ expect(g.status).toBe("running");+ expect(g.message).toBe(POOL_WORDS.working);+ });++ it("a poll that fails never ends a run in line by the runner's own wait, an account's or the owner's", async () => {+ standInWorker();+ const { id } = await accountRun("a poll that fails");+ // The owner's own job on the workers (no wait limit unless the owner sets one).+ const owner = await generationsRoute.POST(+ new Request(`http://${HOST}/api/generations`, {+ method: "POST",+ headers: { ...SITE_HEADERS, cookie: `${auth.SESSION_COOKIE}=${auth.createSession().value}`, "content-type": "application/json" },+ body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "the owner's own" }),+ }),+ );+ const ownerBody = (await owner.json()) as { items?: { id: string }[] };+ expect(owner.status, JSON.stringify(ownerBody)).toBe(201);+ const ownerId = ownerBody.items![0].id;+ for (let i = 0; i < 100 && !taskOf(ownerId); i++) {+ await tick();+ await new Promise((res) => setTimeout(res, 20));+ }+ expect(taskOf(ownerId)?.class).toBe("owner");+ await tick();+ // By the runner's own count, both waited past every wait limit it knows (their tasks keep the real ones), and each+ // poll fails (the database is busy).+ for (const g of [id, ownerId]) db().prepare("UPDATE generation_runs SET submitted_at = ?, started_at = NULL WHERE id = ?").run(Date.now() - 5 * 60 * MIN, g);+ const spy = vi.spyOn(comfyProvider, "poll").mockRejectedValue(new Error("database is locked"));+ try {+ await tick();+ await tick();+ expect(spy).toHaveBeenCalled();+ for (const g of [id, ownerId]) expect(getGeneration(g)?.status, g).toBe("queued");+ expect(getGeneration(id)?.message).toBe(POOL_WORDS.inLine);+ } finally {+ spy.mockRestore();+ }+ await tick();+ for (const g of [id, ownerId]) expect(getGeneration(g)?.status, g).toBe("queued");});});