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
Runs across a deploy: one send per run with the release before, a cut-off step on the install's ComfyUI never sent twice, a stopping server starts no new step
Adarsh5ee8b03a6ccf
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex c47b72ec..2d3b46f5 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -319,6 +319,7 @@ Only cut a PR when the owner asks for one. The steps that worked for PRs #12 to- **The pre-flight index:** PR #15 put its graphs into `workflows/comfyui/requirements.json` (with ComfyUI-DBS in `packs.json`) and gave Split soundtrack, Fly path and Turnaround rows in `STUDIO_ROWS` (`src/server/gpu/tools.ts`). A package that adds a graph or a studio does the same. After PR #15, check that they reached main: `git grep -c '/audio/split' origin/main -- src/server/gpu/tools.ts` (Split soundtrack's row in `STUDIO_ROWS`) and `git grep -c separate-soundtrack-dbs origin/main -- workflows/comfyui/requirements.json` must each print a count. If not, add them (`node scripts/comfy/build-requirements.mjs` rewrites the index).- **Data folders that ran the old integration branch:** migrations are known by their place in `MIGRATIONS`, and on `claude/fuobe-parity-4` up to `f7c6d8e` places 23 and 24 were acc-1's identity tables and acc-2's audit-log trigger. On main they are the GPU pre-flight's tables and `assets.account_id`. PR #15's `open()` in `src/server/db.ts` forgets either place when main's work is missing and the dropped package's is there, so main's migration runs (`tests/dropped-branch-migrations.test.ts`). The dropped tables stay, unused. Never reuse a place in that list: only append.- **Public sign-up** is off by default, and verify.sh's servers run without it. `tests/public-signup.test.ts`, `tests/public-signup-tools.test.ts` and `tests/account-*.test.ts` pin the guest and account answers.+- **Who sends a run, across a deploy from the release before:** this release decides which app process sends a run, or waits on it, with a turn (`submit_turns`, freed when its process has been quiet for 20 s). The release before used a lease in the run's `external_meta_json` (`lease`: `{by, until}`, 60 s, renewed every 15 s). A deploy that starts the new instance before it stops the old one runs both releases on one database for a moment, so for one release both marks count (`OLD_LEASE` in `src/server/generations.ts`): a live lease of a process that isn't in `app_processes` holds a run as a turn does, and a run whose turn this release holds carries its lease too (renewed by the beat, removed with the turn). Once every instance runs this release, the next release can drop `OLD_LEASE`, `oldLeaseHolds` and the lease writes. A deploy that stops the old instance first (a plain restart) needs none of it. `tests/own-run-turns.test.ts` covers both directions.- **Small free disk and Vitest:** accounts can't upload or run while the data disk has less free space than it keeps (`FUOBE_ACCOUNT_DISK_FREE_GB`, else 20 GB or a tenth of the disk, at least 2 GB). In a container with a few GB free, `POST /api/generations` then answers 503 where `tests/gpu-api.test.ts` expects 409, so run Vitest with `FUOBE_ACCOUNT_DISK_FREE_GB=1` (verify.sh and the build prompts do).- **What none of the checks cover:** no GPU and no paid key have been used. Every Original is checked in demo mode, on the CPU ComfyUI (graphs accepted, no weights run) and by unit tests, but not for image quality or real bills.- **The owner's workflow JSONs and downloaded repos:** never commit them, never run them.diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 18fa23fe..f86ec318 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -667,7 +667,9 @@ gives a new step neither that run's place nor its start. When two app processesoverlap), only the one that takes a step's turn sends it, so each step is sent once. A step is marked just before itsjob is made; when the process that was sending it stopped part way, the next one looks for the step's job: nonemade, and the step is sent now (in its run's place); one made, and the step ends in the one plain sentence and that-job stops, so it is never run twice. When the run is canceled or deleted, its finishing jobs end too: one in line at once,+job stops, so it is never run twice. That look is for steps on the workers, whose jobs are tasks in the studio's+database. A step sent to the install's own ComfyUI (on the studio's machine) may be in its queue already, so when its+send was cut off it ends in the plain sentence instead of being sent again. When the run is canceled or deleted, its finishing jobs end too: one in line at once,with its files, and one that a CPU slot runs at its next progress report (the worker sends one at least every 10seconds). A 3D model finished this way waits for the output check when the run asked for one, as any run's outputs do.The time a CPU task runs is never counted as GPU time.diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 10fa5b9f..8fcc66b1 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -707,7 +707,8 @@ owner's own runs, and runs on this studio's GPUs (hosted runs), keep their wordswith what is left of its wait (its tries and its time), on one instance only; so does a step of alonger run. Another instance never fails, takes or sends a run whose turn a running instanceholds. A server that is stopping sends no more tries and gives its waiting runs' turns back at- once, for the next instance. A run that+ once, for the next instance; it launches no new step of a longer run and takes over no wait,+ and a step whose first send it had begun is left unsent, for the next instance to launch. A run thatwaited, and a step of a longer run on any try (its first too), is marked just before the try sendsthe job itself: a server cut off in the middle of that send leaves a job the GPU or provider mayalready have, so the next instance doesn't send it again, and the run fails with "This run wasdiff --git a/src/server/generations.ts b/src/server/generations.tsindex 356fc407..5ec71863 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -73,7 +73,7 @@ import { kandinskyPrompt } from "@/lib/kandinsky-prompt";import { carriesLayout } from "@/lib/layout-prompt";import { setResolver, watchGenerations, type LiveEvent } from "./live";import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";-import { comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, ownLink, probeComfy, relayFile, troubleError, type OwnGpu } from "./providers/comfyui";+import { comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, onPoolWorkers, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, ownLink, probeComfy, relayFile, troubleError, type OwnGpu } from "./providers/comfyui";import { accountById, accountGpu, gpuLink, type AccountGpu } from "./auth";import { accountEngineMode, accountKey, markKeyGood, paidAllowed, usableProviders } from "./account-keys";import { addKeyMessage, CLOUD_KEY, CLOUD_PROVIDERS, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";@@ -443,6 +443,13 @@ interface PendingMeta {* Cleared when the try fails and the step waits; gone once it is handed over (markSending).*/sending?: number;+ /**+ * With `sending`: that send's job is a task of this database (a step of a run on this install's workers), so whether+ * the send made it is known (hasJobFor). Without it the job went to a ComfyUI or a provider that may have it.+ */+ sendingTask?: boolean;+ /** Who holds the run as the release before this one marked it (OLD_LEASE), and until when. */+ lease?: { by?: unknown; until?: unknown };}/** A run's wait for its own GPU or key, kept with it (survives a restart). */@@ -486,10 +493,50 @@ const readMeta = (json: string | null | undefined): PendingMeta & Record<string,* this install's GPUs.*/-/** Another app process took this run's turn (this one went quiet meanwhile): it is that process's to send now. */+/**+ * The release before this one marked the runs an instance held with a lease in external_meta_json (`lease`: {by, until},+ * renewed every 15 s, good for 60 s), not with a turn. For the first deploy of this release its old instance still runs+ * next to the new one for a moment, on the same database, so both marks count: a live lease whose holder isn't an app+ * process of this release (none in app_processes) holds a run as a turn of another process does, and while this process+ * holds a run's turn, the run carries a lease of this process too (takeSubmitTurn, renewed by the beat, gone with the+ * turn), which the release before reads as held. Neither then sends, fails or takes over a run the other holds.+ */+export const OLD_LEASE = { ms: 60_000, renewMs: 15_000 };++/** A lease field of a row's external_meta_json, in SQL (NULL when the column isn't JSON). */+const leaseField = (table: string, field: "by" | "until") =>+ `(CASE WHEN json_valid(${table}.external_meta_json) THEN json_extract(${table}.external_meta_json, '$.lease.${field}') END)`;++/**+ * SQL: a live lease of the release before (OLD_LEASE) holds the run in `table` (1, else 0: never NULL); this process's+ * own lease never does. Named parameters: @__now and @__me.+ */+const OLD_LEASE_HELD = (table: string) =>+ `(COALESCE(${leaseField(table, "until")} > @__now, 0) AND ${leaseField(table, "by")} IS NOT @__me+ AND NOT EXISTS (SELECT 1 FROM app_processes lp WHERE lp.token = ${leaseField(table, "by")}))`;++/** A live lease of the release before (OLD_LEASE) holds this run: an instance of that release is sending it or waiting on it. */+function oldLeaseHolds(json: string | null | undefined, now = Date.now()): boolean {+ const lease = readMeta(json).lease;+ if (!lease || typeof lease !== "object" || typeof lease.until !== "number" || lease.until <= now) return false;+ if (lease.by === runnerToken()) return false;+ return !(typeof lease.by === "string" && db().prepare("SELECT 1 FROM app_processes WHERE token = ?").get(lease.by));+}++/** This process's lease on a run whose turn it holds (OLD_LEASE), as SQL sets it (@lease: leaseOf). */+const LEASE_SET = `json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))`;+const leaseOf = (now: number) => JSON.stringify({ by: runnerToken(), until: now + OLD_LEASE.ms });++/**+ * Another app process took this run's turn (this one went quiet meanwhile), or an instance of the release before holds it+ * (OLD_LEASE): it is that process's to send now.+ */function turnTaken(id: string): boolean {- const held = db().prepare("SELECT held_by FROM submit_turns WHERE id = ?").pluck().get(id) as string | undefined;- return held !== undefined && held !== runnerToken();+ const r = db().prepare("SELECT s.held_by, g.external_meta_json FROM generations g LEFT JOIN submit_turns s ON s.id = g.id WHERE g.id = ?").get(id) as+ | { held_by: string | null; external_meta_json: string | null }+ | undefined;+ if (!r) return false;+ return (r.held_by !== null && r.held_by !== runnerToken()) || oldLeaseHolds(r.external_meta_json);}/** A row still waiting for its hand-over (queued or running, no job yet): only then is it changed. */@@ -1699,11 +1746,12 @@ const DEP_IDS = "json_each(CASE WHEN substr(g.depends_on, 1, 1) = '[' AND json_v/*** SQL: an app process that still runs holds the turn to hand the run in `table` to its provider (takeSubmitTurn: it is- * sending it, or waiting on its own GPU or key for it); `others`: a process other than this one. Named parameters:- * @__me (this process's name) and @__quiet (since when a process that still runs has said so).+ * sending it, or waiting on its own GPU or key for it); `others`: a process other than this one. An instance of the+ * release before that holds it with a live lease (OLD_LEASE) holds it too. Named parameters: @__me (this process's+ * name), @__quiet (since when a process that still runs has said so) and @__now.*/const TURN_HELD = (table: string, others: boolean) =>- `EXISTS (SELECT 1 FROM submit_turns s JOIN app_processes p ON p.token = s.held_by WHERE s.id = ${table}.id${others ? " AND s.held_by != @__me" : ""} AND p.seen_at >= @__quiet)`;+ `(EXISTS (SELECT 1 FROM submit_turns s JOIN app_processes p ON p.token = s.held_by WHERE s.id = ${table}.id${others ? " AND s.held_by != @__me" : ""} AND p.seen_at >= @__quiet) OR ${OLD_LEASE_HELD(table)})`;/*** Waiting steps that can move: none of their dependencies is still queued or running (so they launch), or one@@ -1788,9 +1836,12 @@ export const COMFY_WAIT = { ms: 60_000 };/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */async function advanceDependents(): Promise<void> {+ // A server that is stopping launches no step (the app process that goes on does), and leaves the steps it looked at.+ if (draining()) return;+ const now = Date.now();const rows = db().prepare(READY_DEPENDENTS)- .all({ limit: 50 + submitting().size, __me: runnerToken(), __quiet: Date.now() - QUIET_MS }) as Row[];+ .all({ limit: 50 + submitting().size, __me: runnerToken(), __quiet: now - QUIET_MS, __now: now }) as Row[];// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.let lookedAgain: Promise<boolean> | undefined;for (const r of rows) {@@ -1838,17 +1889,19 @@ async function advanceDependents(): Promise<void> {continue;}// Every app process looks at the same waiting steps (a deploy runs two for a moment): only the one that takes the- // step's turn sends it, so it is sent once.+ // step's turn sends it, so it is sent once. A server that began to stop meanwhile leaves it to the one that goes on.+ if (draining()) return;if (!takeSubmitTurn(r.id, { waiting: true })) continue;// A step that waited for its own GPU or key, taken over after a restart or a deploy (its wait is kept with it, as a// run's is: takeOver). One cut off in the middle of its send, on a later try or its first (markSending), may have- // reached its GPU or provider: never sent twice. On this install's GPUs its job is a row of this database, so that is- // known: with none made, nothing was sent and the step is sent now (in its run's place); with one made, it stops- // with the step instead of running for nothing.+ // reached its GPU or provider: never sent twice. A step of a run on this install's workers whose send was to make a+ // task here (`sendingTask`) is known: with no task made, nothing was sent and the step is sent now (in its run's+ // place); with one made, it stops with the step instead of running for nothing. One sent to this install's own+ // ComfyUI (no task: its job may be there) stops as an account's own does.const pending = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null);const heal = pending.heal;if ((heal && typeof heal.sending === "number") || typeof pending.sending === "number") {- if (stored.place === "pool" && !hasJobFor(r.id)) notSending(r.id);+ if (stored.place === "pool" && pending.sendingTask === true && !hasJobFor(r.id)) notSending(r.id);else {fail(CUT_OFF_SENDING, "interrupted-sending");if (stored.place === "pool") stopJobsOf(r.id);@@ -2361,26 +2414,44 @@ class LetGo extends Error {}* takes the wait over later (this one cut off in the middle of the send, by a restart or a deploy) then doesn't send it* a second time. So is a step of an account's longer run on its first try (`step`: on its own GPU or key, or on this* install's GPUs): the process that launches it after this one was cut off never sends it again (advanceDependents).- * Throws LetGo when another app process took the run's turn, or when this server is stopping and the run waited (the- * next process goes on with its wait, and sends it).+ * `task`: the job this send makes is a task of this database (a run on this install's workers), noted with the mark.+ *+ * The look at the turn and the mark are one step (an immediate transaction): a process that stalled past its turn (20 s+ * with no beat) and another took it meanwhile never marks or sends the run, and one that takes the turn after the mark+ * sees it (takeOver, advanceDependents). Throws LetGo when this process doesn't hold the run's turn (another took it, or+ * an instance of the release before holds it: OLD_LEASE), when this server is stopping and the run waited (the next+ * process goes on with its wait, and sends it), and for a step's first try while this server is stopping (the next+ * process launches it, instead of finding it cut off in the middle of its send; the owner's steps too).*/-function markSending(id: string, step: boolean): void {- const r = db().prepare(`SELECT external_meta_json, depends_on FROM generations WHERE id = ? AND ${PENDING}`).get(id) as Pick<Row, "external_meta_json" | "depends_on"> | undefined;- if (!r) throw new Error("Stopped");- if (turnTaken(id)) throw new LetGo("Taken by another app process");- if (!readMeta(r.external_meta_json).heal) {- // A first try (nothing waited): a run's send cut off here fails at the next process's look (sweepInterrupted).- if (step && r.depends_on) {- db()- .prepare(`UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending', @now) WHERE id = @id AND ${PENDING}`)- .run({ id, now: Date.now() });- }- return;- }- if (draining()) throw new LetGo("Stopping");- db()- .prepare(`UPDATE generations SET external_meta_json = json_set(external_meta_json, '$.heal.sending', @now) WHERE id = @id AND ${PENDING} AND json_type(external_meta_json, '$.heal') = 'object'`)- .run({ id, now: Date.now() });+function markSending(id: string, step: boolean, task = false): void {+ const d = db();+ const out = d+ .transaction((): "gone" | "taken" | "stopping" | "marked" => {+ const r = d+ .prepare(`SELECT g.external_meta_json, g.depends_on, s.held_by FROM generations g LEFT JOIN submit_turns s ON s.id = g.id WHERE g.id = ? AND g.status IN ('queued', 'running') AND g.external_id IS NULL`)+ .get(id) as (Pick<Row, "external_meta_json" | "depends_on"> & { held_by: string | null }) | undefined;+ if (!r) return "gone";+ if (r.held_by !== runnerToken() || oldLeaseHolds(r.external_meta_json)) return "taken";+ const now = Date.now();+ if (!readMeta(r.external_meta_json).heal) {+ // A first try (nothing waited): a run's send cut off here fails at the next process's look (sweepInterrupted).+ if (!r.depends_on) return "marked";+ if (draining()) return "stopping";+ if (!step) return "marked";+ d.prepare(+ `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending', @now${task ? ", '$.sendingTask', json('true')" : ""})+ WHERE id = @id AND ${PENDING}`,+ ).run({ id, now });+ return "marked";+ }+ if (draining()) return "stopping";+ d.prepare(`UPDATE generations SET external_meta_json = json_set(external_meta_json, '$.heal.sending', @now) WHERE id = @id AND ${PENDING} AND json_type(external_meta_json, '$.heal') = 'object'`).run({ id, now });+ return "marked";+ })+ .immediate();+ if (out === "gone") throw new Error("Stopped");+ if (out === "taken") throw new LetGo("Taken by another app process");+ if (out === "stopping") throw new LetGo("Stopping");}/** A send its provider answered with a refusal (a 4xx): the job was never taken. */@@ -2392,7 +2463,7 @@ function refusedAtSend(e: unknown): boolean {/** A send that is over without a job: the run's mark of being sent goes (it was never handed over). */function notSending(id: string): void {db()- .prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.heal.sending', '$.sending') WHERE id = ? AND ${PENDING} AND json_valid(external_meta_json)`)+ .prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.heal.sending', '$.sending', '$.sendingTask') WHERE id = ? AND ${PENDING} AND json_valid(external_meta_json)`).run(id);}@@ -2404,7 +2475,11 @@ export const OWN_QUEUE = { scale: 1 };/** The longest an account's job waits in its own GPU's (or provider's) queue, however it moves. */const OWN_QUEUE_CAP_MS = 2 * 60 * 60_000;-/** The words a waiting run's tile shows, its wait kept with it (external_meta_json `heal`). False: it isn't waiting any more. */+/**+ * The words a waiting run's tile shows, its wait kept with it (external_meta_json `heal`). False: it isn't waiting any more,+ * or this process no longer holds its turn (it stalled, and another took the wait over: that one's wait, and its mark of+ * a send, stay as they are).+ */function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: number, message: string): boolean {heal.next = next;heal.words = trouble.words;@@ -2415,10 +2490,10 @@ function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: numbdb().prepare(`UPDATE generations SET status = 'queued', message = @message, updated_at = @now,- external_meta_json = json_set(json_remove(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending'), '$.heal', json(@heal))- WHERE id = @id AND ${PENDING}`,+ external_meta_json = json_set(json_remove(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending', '$.sendingTask'), '$.heal', json(@heal))+ WHERE id = @id AND ${PENDING} AND EXISTS (SELECT 1 FROM submit_turns s WHERE s.id = @id AND s.held_by = @me)`,)- .run({ id, message, now: Date.now(), heal: JSON.stringify(heal) }).changes > 0+ .run({ id, message, now: Date.now(), heal: JSON.stringify(heal), me: runnerToken() }).changes > 0);}@@ -3135,8 +3210,9 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pif (cloned && route.map?.cloneFirst && !input.voiceEmbedding) input.voiceEmbedding = cloned;// Nothing is sent once the run stopped being this one's to send (cancelled, failed, or taken by another instance).if (!going()) throw new Error("Stopped");- // (Every account's step on its first try: on its own GPU or key, and on this install's GPUs.)- markSending(id, !!req.account);+ // (Every account's step on its first try: on its own GPU or key, and on this install's GPUs. On the workers its job is+ // a task of this database, made by this send: the mark says so.)+ markSending(id, !!req.account, providerId === "comfyui" && onPoolWorkers());const res = await adapter.submit({ generationId: id, model: plan.model, route, input });// A saved voice the cloud just cloned keeps the embedding (the owner's runs only), so its next line skips the clone.if (typeof res.meta?.voiceEmbedding === "string" && !req.account) void keepVoiceEmbedding(req.inputs?.voiceAudio, res.meta.voiceEmbedding).catch(() => {});@@ -3271,21 +3347,26 @@ function startRunner(): void {* restart, or a deploy's old instance gone). One waiting for its own GPU or key goes on here, with what is left of its* wait (one process takes it); one cut off in the middle of its hand-over can't be recovered, and fails. A run a process* that still runs is sending or waiting on (this one, or another in a deploy's overlap) is left to it. Runs at start and- * every tick.+ * every tick; not while this server stops (the app process that goes on looks).*/function sweepInterrupted(): void {+ if (draining()) return;const now = Date.now();const rows = db().prepare(`SELECT g.id, g.provider, g.model_id, g.op, g.request_json, g.external_meta_json FROM generations gWHERE g.status IN ('queued','running') AND g.external_id IS NULL AND g.depends_on IS NULL AND g.created_at < @before AND NOT ${TURN_HELD("g", false)}`,)- .all({ before: now - STALE_SUBMIT.ms, __me: runnerToken(), __quiet: now - QUIET_MS }) as Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json" | "external_meta_json">[];+ .all({ before: now - STALE_SUBMIT.ms, __me: runnerToken(), __quiet: now - QUIET_MS, __now: now }) as Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json" | "external_meta_json">[];const busy = submitting();for (const r of rows) {if (busy.has(r.id)) continue;- const meta = readMeta(r.external_meta_json);- if (meta.heal && takeOver(r, meta.heal)) continue;+ let meta = readMeta(r.external_meta_json);+ if (meta.heal) {+ if (takeOver(r, meta.heal)) continue;+ // (As it is now: the process it was taken from may have marked it as being sent since this look.)+ meta = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null);+ }// A run that waited and was cut off in the middle of its send may have reached its GPU or provider: never sent twice.const cutOff = !!meta.heal && typeof meta.heal.sending === "number";const words = cutOff ? CUT_OFF_SENDING : "This run stopped before it started. Press Retry.";@@ -3318,6 +3399,14 @@ function takeOver(r: Pick<Row, "id" | "provider" | "model_id" | "op" | "request_if (!account || stored.place === "pool") return false;// Another app process took it first.if (!takeSubmitTurn(r.id)) return true;+ // Read again under the turn: the process that held it may have marked it as being sent after the sweep's look, before+ // it went quiet (markSending marks only under its turn). Then it may have reached its GPU or provider: never sent twice.+ const now = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null).heal;+ if (!now || typeof now.sending === "number") {+ handOverEnds(r.id);+ return false;+ }+ h = now;let p: ReturnType<typeof prepare>;try {p = asAccount(account, () => prepare(stored));@@ -3876,6 +3965,23 @@ function beat(now = Date.now()): void {.prepare("INSERT INTO app_processes (token, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(token) DO UPDATE SET seen_at = excluded.seen_at").run(runnerToken(), now, now);noteCatalogProcess(catalogVersion(), processStart(), now);+ renewLeases(now);+}++/**+ * The leases of the runs whose turn this process holds (OLD_LEASE), renewed once less than OLD_LEASE.ms - renewMs is left+ * (each renewal is a change of the run that its live updates send). Never over a live lease of the release before.+ */+function renewLeases(now: number): void {+ const by = leaseField("generations", "by");+ const until = leaseField("generations", "until");+ db()+ .prepare(+ `UPDATE generations SET external_meta_json = ${LEASE_SET}+ WHERE id IN (SELECT id FROM submit_turns WHERE held_by = @me) AND ${PENDING}+ AND (${until} IS NULL OR ${until} <= @now OR ${by} = @me) AND (${by} IS NOT @me OR ${until} IS NULL OR ${until} < @fresh)`,+ )+ .run({ me: runnerToken(), now, fresh: now + OLD_LEASE.ms - OLD_LEASE.renewMs, lease: leaseOf(now) });}/**@@ -3895,6 +4001,16 @@ function keepBeating(): void {} catch (e) {console.warn(`[generations] app process: ${(e as Error).message}`);}+ // Started inside a caller's transaction (the runner, first started by a run being made): that first word goes if the+ // transaction is rolled back, so it is said again as soon as the transaction is over, not 5 s later.+ if (db().inTransaction)+ setImmediate(() => {+ try {+ beat();+ } catch {+ // The next beat says it.+ }+ });const timer = setInterval(() => {try {beat();@@ -3914,6 +4030,8 @@ function giveTurnsBack(): void {const me = runnerToken();d.transaction(() => {d.prepare("UPDATE generation_runs SET finish_by = NULL, finish_until = NULL WHERE finish_by = ? AND finish_until >= ?").run(me, Date.now());+ // (Its leases first, while its turns still name the runs: OLD_LEASE.)+ d.prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.lease') WHERE id IN (SELECT id FROM submit_turns WHERE held_by = @me) AND ${leaseField("generations", "by")} = @me`).run({ me });d.prepare("DELETE FROM submit_turns WHERE held_by = ?").run(me);d.prepare("DELETE FROM app_processes WHERE token = ?").run(me);})();@@ -3964,17 +4082,21 @@ function takeSubmitTurn(id: string, o: { waiting?: boolean } = {}, now = Date.noconst d = db();return d.transaction((): boolean => {- const g = d.prepare("SELECT status, external_id FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id"> | undefined;+ const g = d.prepare("SELECT status, external_id, external_meta_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id" | "external_meta_json"> | undefined;if (!g || g.external_id || (g.status !== "queued" && (o.waiting || g.status !== "running"))) return false;- return (+ // An instance of the release before holds it (its lease: OLD_LEASE).+ if (oldLeaseHolds(g.external_meta_json, now)) return false;+ const took =d.prepare(`INSERT INTO submit_turns (id, held_by, held_at) VALUES (@id, @me, @now)ON CONFLICT(id) DO UPDATE SET held_by = excluded.held_by, held_at = excluded.held_atWHERE submit_turns.held_by = @me OR NOT EXISTS (SELECT 1 FROM app_processes p WHERE p.token = submit_turns.held_by AND p.seen_at >= @quiet)`,)- .run({ id, me: runnerToken(), now, quiet: now - QUIET_MS }).changes > 0- );+ .run({ id, me: runnerToken(), now, quiet: now - QUIET_MS }).changes > 0;+ // The lease the release before reads as held, while this process holds the turn (renewed by the beat).+ if (took) d.prepare(`UPDATE generations SET external_meta_json = ${LEASE_SET} WHERE id = @id AND ${PENDING}`).run({ id, lease: leaseOf(now) });+ return took;}).immediate();}@@ -3991,7 +4113,13 @@ function noteSubmitTurn(id: string): void {function handOverEnds(id: string): void {submitting().delete(id);try {- db().prepare("DELETE FROM submit_turns WHERE id = ? AND held_by = ?").run(id, runnerToken());+ const d = db();+ const me = runnerToken();+ d.transaction(() => {+ d.prepare("DELETE FROM submit_turns WHERE id = ? AND held_by = ?").run(id, me);+ // Its lease goes with the turn (OLD_LEASE): an instance of the release before may take a run left waiting at once.+ d.prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.lease') WHERE id = ? AND ${leaseField("generations", "by")} = ?`).run(id, me);+ })();} catch {// A closed database: the turn is free once this process has been quiet for 20 s.}diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.tsindex 847e0f2c..e138dc3d 100644--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@ -61,6 +61,8 @@ export interface FakeComfyOptions {* it is cut off before the answer comes. Its connection stays open until `dropHeld()` or `close()`.*/hold?: (method: string, path: string) => boolean;+ /** How long to wait before handling a request as usual (0 or undefined: at once): a slow network or GPU. */+ slow?: (method: string, path: string) => number;}/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */@@ -205,6 +207,12 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fconst chunks: Buffer[] = [];req.on("data", (c: Buffer) => chunks.push(c));req.on("end", () => {+ // (A slow answer: the request is handled as usual after that wait.)+ const wait = opts.slow?.(req.method ?? "GET", new URL(req.url ?? "/", "http://fake").pathname) ?? 0;+ if (wait > 0) setTimeout(handle, wait);+ else handle();+ });+ const handle = () => {const body = Buffer.concat(chunks);const url = new URL(req.url ?? "/", "http://fake");const entry: FakeLogEntry = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now() };@@ -343,7 +351,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Freturn res.end(png ? TINY_PNG : TINY_MP4);}json(404, { error: "not found" });- });+ };});return new Promise((resolve) => {server.listen(port, "127.0.0.1", () => {diff --git a/tests/own-run-turns.test.ts b/tests/own-run-turns.test.tsindex e268a39e..82a88c17 100644--- a/tests/own-run-turns.test.ts+++ b/tests/own-run-turns.test.ts@@ -79,7 +79,7 @@ beforeEach(() => {resetRates();SELF_HEAL.scale = SCALE;STALE_SUBMIT.ms = 0;- Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined, hold: undefined, output: undefined });+ Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined, hold: undefined, slow: undefined, output: undefined });fake.dropHeld();fake.log.length = 0;globalThis.__fuobeAccountGpus?.clear();@@ -172,6 +172,9 @@ describe("two app processes and a run waiting for its account's own GPU", () =>expect(turnOf(id)).toBeNull();expect(row(id)).toMatchObject({ status: "queued", external_id: null });expect(healOf(id)?.since).toBe(before.since);+ // A server that is stopping takes no wait over, its own included: the other process does.+ await tick();+ expect(turnOf(id)).toBeNull();// The other process takes the wait over: its turn, the wait's start kept, its tries going on from where they were.expect(await until(() => turnOf(id) === theirs && (healOf(id)?.tries ?? 0) > before.tries, () => app2.tick())).toBe(true);expect(healOf(id)?.since).toBe(before.since);@@ -216,6 +219,157 @@ describe("a step of a longer run that waits for its account's own GPU", () => {});});+/** The account's first run, done on the GPU with a picture, and the next step of its longer run (not launched yet). */+async function doneRunAndStep(): Promise<{ first: string; step: string }> {+ fake.opts.output = "both";+ const first = await startRun();+ expect(await until(() => ended(first))).toBe(true);+ expect(row(first).status, row(first).error ?? "").toBe("succeeded");+ const pic = await uploadPng();+ fake.log.length = 0;+ const [step] = asAccount(a, () =>+ createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } } as Parameters<typeof createGenerations>[0], { dependsOn: first }),+ );+ return { first, step: step.id };+}+const metaOf = (id: string) => JSON.parse(row(id).external_meta_json || "{}") as { sending?: number; lease?: { by: string; until: number }; heal?: Heal };+const both = () => Promise.all([tick(), app2.tick()]).then(() => {});++describe("a server that is stopping", () => {+ it("launches no new step of a longer run: the other process launches it, and it is sent once", async () => {+ const { step } = await doneRunAndStep();+ shutdown().draining = true;+ for (let i = 0; i < 3; i++) await tick();+ expect(turnOf(step), "not taken here").toBeNull();+ expect(row(step)).toMatchObject({ status: "queued", external_id: null });+ expect(prompts()).toBe(0);+ expect(await until(() => ended(step), () => app2.tick())).toBe(true);+ expect(row(step).status, row(step).error ?? "").toBe("succeeded");+ expect(prompts(), "sent once, by the process that goes on").toBe(1);+ });++ it("leaves a step whose first send it had begun unsent and unmarked: the other process launches it, and it is sent once", async () => {+ const { step } = await doneRunAndStep();+ // The server starts to stop while the step's picture goes to the GPU (after the step was taken here).+ fake.opts.answer = (m, p) => {+ if (m === "POST" && p === "/upload/image") shutdown().draining = true;+ return undefined;+ };+ await tick();+ expect(await until(() => shutdown().draining && !globalThis.__fuobeSubmitting?.has(step), async () => {})).toBe(true);+ fake.opts.answer = undefined;+ expect(turnOf(step), "its turn went back").toBeNull();+ expect(row(step)).toMatchObject({ status: "queued", external_id: null });+ expect(metaOf(step).sending, "never marked as being sent").toBeUndefined();+ expect(prompts()).toBe(0);+ expect(await until(() => ended(step), () => app2.tick())).toBe(true);+ expect(row(step).status, row(step).error ?? "").toBe("succeeded");+ expect(prompts(), "sent once").toBe(1);+ });+});++describe("a process that stalls while it sends a run", () => {+ it("once another process took the run's turn, it never marks or sends it: the run is sent once, by the one that took it", async () => {+ gpuStarting();+ const id = await startRun();+ expect(await until(() => waiting(id))).toBe(true);+ // Its GPU is back; the picture this process sends it is slow to land.+ let slowed = 0;+ fake.opts.slow = (m, p) => (m === "POST" && p === "/upload/image" && !slowed++ ? 8000 : 0);+ gpuBack();+ expect(await until(() => slowed > 0)).toBe(true);+ // Meanwhile this process stalls (no beat for 20 s), and the other takes the wait over.+ clearInterval(globalThis.__fuobeBeat);+ globalThis.__fuobeBeat = undefined;+ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = ?").run(Date.now() - QUIET_MS - 1000, mine());+ expect(await until(() => ended(id), () => app2.tick())).toBe(true);+ expect(row(id).status, row(id).error ?? "").toBe("succeeded");+ // This process's slow send lands after that: it sends nothing.+ for (let i = 0; i < 600 && globalThis.__fuobeSubmitting?.has(id); i++) await sleep(20);+ expect(globalThis.__fuobeSubmitting?.has(id)).toBe(false);+ const sends = fake.log.map((e) => `${e.method} ${e.path}`);+ expect(sends.lastIndexOf("POST /upload/image"), "its picture landed after the run was sent (by the other process)").toBeGreaterThan(sends.indexOf("POST /prompt"));+ expect(row(id).status).toBe("succeeded");+ expect(prompts(), "sent once, by the process that took it").toBe(1);+ // (This process says it runs again: its beat starts with the runner.)+ ensureRunner();+ expect(globalThis.__fuobeBeat).toBeDefined();+ });+});++/** The release before marked a run it held with a lease (OLD_LEASE), held by `by` until `until`. */+const leaseBy = (id: string, by: string, until: number) =>+ db().prepare("UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json_object('by', ?, 'until', ?)) WHERE id = ?").run(by, until, id);+/** That release's claim of a run (its code, as it is): true when it took the run. */+const oldClaim = (id: string, me: string) => {+ const now = Date.now();+ return (+ db()+ .prepare(+ `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))+ WHERE id = @id AND external_id IS NULL AND status IN ('queued', 'running')+ AND (NOT json_valid(external_meta_json) OR json_extract(external_meta_json, '$.lease.until') IS NULL+ OR json_extract(external_meta_json, '$.lease.until') < @now OR json_extract(external_meta_json, '$.lease.by') = @me)`,+ )+ .run({ id, now, me, lease: JSON.stringify({ by: me, until: now + 60_000 }) }).changes > 0+ );+};++describe("an instance of the release before on the same database (the first deploy of this release)", () => {+ it("a run it waits on (its live lease) is left to it by both processes; once its lease runs out, one of them goes on with the wait and sends it once", async () => {+ gpuStarting();+ const id = await startRun();+ expect(await until(() => waiting(id))).toBe(true);+ await drainHere(id);+ shutdown().draining = false;+ const before = healOf(id)!;+ leaseBy(id, "old-instance", Date.now() + 60_000);+ for (let i = 0; i < 3; i++) await both();+ expect(turnOf(id), "neither takes it").toBeNull();+ expect(row(id)).toMatchObject({ status: "queued", external_id: null });+ expect(healOf(id)?.tries).toBe(before.tries);+ expect(prompts()).toBe(0);+ gpuBack();+ leaseBy(id, "old-instance", Date.now() - 1);+ expect(await until(() => ended(id), both)).toBe(true);+ expect(row(id).status, row(id).error ?? "").toBe("succeeded");+ expect(prompts(), "sent once").toBe(1);+ });++ it("a step of a longer run it is launching (its live lease) is left to it; once its lease runs out, one of them launches it, sent once", async () => {+ const { step } = await doneRunAndStep();+ leaseBy(step, "old-instance", Date.now() + 60_000);+ for (let i = 0; i < 3; i++) await both();+ expect(turnOf(step)).toBeNull();+ expect(row(step)).toMatchObject({ status: "queued", external_id: null });+ expect(prompts()).toBe(0);+ leaseBy(step, "old-instance", Date.now() - 1);+ expect(await until(() => ended(step), both)).toBe(true);+ expect(row(step).status, row(step).error ?? "").toBe("succeeded");+ expect(prompts(), "sent once").toBe(1);+ });++ it("a run whose turn this process holds carries its lease, which that release reads as held; the beat renews it, and it goes with the turn", async () => {+ gpuStarting();+ const id = await startRun();+ expect(await until(() => waiting(id))).toBe(true);+ expect(turnOf(id)).toBe(mine());+ expect(metaOf(id).lease?.by).toBe(mine());+ expect(metaOf(id).lease!.until).toBeGreaterThan(Date.now() + 30_000);+ expect(oldClaim(id, "old-instance"), "that release can't take it").toBe(false);+ // About to run out: the beat (every 5 s) renews it.+ leaseBy(id, mine(), Date.now() + 2000);+ expect(await until(() => metaOf(id).lease!.until > Date.now() + 30_000, async () => {}, 8000)).toBe(true);+ expect(oldClaim(id, "old-instance")).toBe(false);+ // This process stops: the turn goes, and the lease with it, so that release may go on with the run at once.+ await drainHere(id);+ expect(turnOf(id)).toBeNull();+ expect(metaOf(id).lease).toBeUndefined();+ expect(oldClaim(id, "old-instance")).toBe(true);+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(id);+ });+});+// Last: the other process is killed here.describe("a process cut off in the middle of a send", () => {it("the run it was sending is never sent a second time: it ends in plain words once that process has gone quiet", async () => {diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex f5cf1f27..f551cf17 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -1662,8 +1662,8 @@ describe("two app processes on one database (a deploy's overlap)", () => {it("a chain's next step whose send was cut off: with no job made yet it is sent once, at its run's place, with no error", async () => {const { id, step, d } = await runAndNextStep();- // Marked as being sent by a process that was killed before it made the step's job.- db().prepare("UPDATE generations SET external_meta_json = json_object('sending', ?) WHERE id = ?").run(Date.now() - 1000, step);+ // Marked as being sent to the workers (a task here) by a process that was killed before it made the step's job.+ db().prepare("UPDATE generations SET external_meta_json = json_object('sending', ?, 'sendingTask', json('true')) WHERE id = ?").run(Date.now() - 1000, step);sendingIn("app-cut-off", step, QUIET_MS + 1000);await Promise.all([tick(), app2.tick()]);for (let i = 0; i < 200 && !jobsOf(step).length; i++) await sleep(25);@@ -1698,6 +1698,62 @@ describe("two app processes on one database (a deploy's overlap)", () => {expect(jobsOf(step)[0].state, "the job it made stops with it").toBe("canceled");});+ /** Hosted runs on the install's own ComfyUI, on this machine (the stand-in), instead of the workers. */+ const onInstallServer = () => {+ setSetting("comfyWhere", "server");+ setSetting("comfyUrl", comfy.url);+ };+ /** Every mark of a send this process leaves on a run (a temporary trigger on its own connection): the run's meta then. */+ const watchMarks = () => {+ db().exec(`CREATE TEMP TABLE IF NOT EXISTS send_marks (id TEXT, meta TEXT);+ CREATE TEMP TRIGGER IF NOT EXISTS send_mark AFTER UPDATE OF external_meta_json ON main.generations+ WHEN (CASE WHEN json_valid(NEW.external_meta_json) THEN json_type(NEW.external_meta_json, '$.sending') END) IS NOT NULL+ BEGIN INSERT INTO send_marks VALUES (NEW.id, NEW.external_meta_json); END;`);+ return (id: string) => (db().prepare("SELECT meta FROM send_marks WHERE id = ?").pluck().all(id) as string[]).map((m) => JSON.parse(m) as { sending?: number; sendingTask?: boolean });+ };++ it("a step's mark of its send says whether its job is a task here: on the workers it is, on the install's own ComfyUI it isn't", async () => {+ const marks = watchMarks();+ try {+ const { id, step, d } = await runAndNextStep();+ await tick();+ for (let i = 0; i < 200 && !jobsOf(step).length; i++) await sleep(25);+ expect(marks(step), "marked once, as a task here").toEqual([expect.objectContaining({ sending: expect.any(Number), sendingTask: true })]);+ await workAll(d);+ expect((await ended(step))?.status).toBe("succeeded");+ // The same on the install's own ComfyUI: its job may be in that ComfyUI's queue, and no task here says so.+ const first = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json);+ const [next] = runOnPool(A, () => withRunStamp(stampOf(first), () => createGenerations({ feature: "image", modelId: "oss-selftest-image", op: "edit", prompt: "invert it", chainFrom: "first" }, { dependsOn: id })));+ onInstallServer();+ const posts = comfy.posts();+ await tick();+ expect(await until(() => marks(next.id).length > 0 && comfy.posts() > posts)).toBe(true);+ expect(marks(next.id)).toEqual([expect.objectContaining({ sending: expect.any(Number) })]);+ expect(marks(next.id)[0].sendingTask).toBeUndefined();+ expect(jobsOf(next.id), "no task here").toHaveLength(0);+ } finally {+ db().exec("DROP TRIGGER IF EXISTS send_mark; DROP TABLE IF EXISTS send_marks;");+ }+ });++ it("a chain's next step on the install's own ComfyUI whose send was cut off is never sent again: it ends in the plain sentence, with no job here", async () => {+ const { step } = await runAndNextStep();+ onInstallServer();+ const posts = comfy.posts();+ // Marked as being sent by a process that was killed while it posted the step to that ComfyUI (no task here: its job+ // may be in that ComfyUI's queue).+ db().prepare("UPDATE generations SET external_meta_json = json_object('sending', ?) WHERE id = ?").run(Date.now() - 1000, step);+ sendingIn("app-cut-off-server", step, QUIET_MS + 1000);+ await Promise.all([tick(), app2.tick()]);+ const g = await ended(step);+ expect(plainFailure(g!, { charged: false }), JSON.stringify(g)).toEqual([]);+ expect(db().prepare("SELECT error FROM generations WHERE id = ?").get(step)).toEqual({ error: "This run was interrupted while it was being sent. Press Retry." });+ await Promise.all([tick(), app2.tick()]);+ await sleep(500);+ expect(comfy.posts(), "nothing more was posted to that ComfyUI").toBe(posts);+ expect(jobsOf(step)).toHaveLength(0);+ });+it("a step and a preview picture the worker reports to the other process are seen here too: a refresh, both sessions, the list and the other process show the same step", async () => {const w = standInWorker();const { id } = await pressRun();