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: one app process saves a finished run, and each report is sent once
Adarsh9997b071297e
diff --git a/src/server/billing-outbox.ts b/src/server/billing-outbox.tsindex ba943fa6..6c8f4e6d 100644--- a/src/server/billing-outbox.ts+++ b/src/server/billing-outbox.ts@@ -1,4 +1,5 @@import "server-only";+import crypto from "node:crypto";import { db } from "./db";import { billingConfigured, forgetBalance, sendReport, type RefundReport, type SettleReport } from "./billing";@@ -6,7 +7,8 @@ import { billingConfigured, forgetBalance, sendReport, type RefundReport, type S* The billing outbox: every report the billing service must get (settle, refund, release) is written here first, then* sent, and sent again with backoff until the service takes it (for 7 days). A report is known by its key (the run* row's id, or "release:<hold>"), so a row is reported once however often the sweep runs, and a restart in between- * loses nothing: the sweep finds every finished row with a hold and no report from what is stored.+ * loses nothing: the sweep finds every finished row with a hold and no report from what is stored. An app process+ * takes a report before it sends it, so two processes on one database (a deploy's overlap) never send the same one.** A hold's rows are reported once none of them is still queued or running, each with `rows` (how many rows share the* hold), so the service closes the hold when the last report arrives.@@ -140,15 +142,42 @@ interface OutboxRow {created_at: number;}+/** How long an app process holds a report it is sending (a send takes 5 s at most: billing.ts BILLING_TIMEOUTS.report). */+const SEND_TURN_MS = 60_000;++declare global {+ /** This app process, as the reports it is sending name it. */+ var __fuobeOutboxToken: string | undefined;+}++const outboxToken = () => (globalThis.__fuobeOutboxToken ??= `${process.pid}:${crypto.randomUUID()}`);++/**+ * Take a report to send it: only one not sent yet, that no other app process is sending now (two processes on one+ * database during a deploy's overlap never send the same report, so the service gets each one once).+ */+function claimReport(key: string): boolean {+ const now = Date.now();+ const me = outboxToken();+ return (+ db()+ .prepare("UPDATE billing_outbox SET sending_by = ?, sending_until = ? WHERE key = ? AND done_at IS NULL AND (sending_until IS NULL OR sending_until < ? OR sending_by = ?)")+ .run(me, now + SEND_TURN_MS, key, now, me).changes > 0+ );+}+/** Send the reports that are due. Returns how many the service took. */export async function drainOutbox(now = Date.now(), limit = 50): Promise<number> {const d = db();- const due = d.prepare("SELECT key, kind, hold_id, payload_json, tries, created_at FROM billing_outbox WHERE done_at IS NULL AND next_at <= ? ORDER BY next_at LIMIT ?").all(now, limit) as OutboxRow[];+ const due = d+ .prepare("SELECT key, kind, hold_id, payload_json, tries, created_at FROM billing_outbox WHERE done_at IS NULL AND next_at <= ? AND (sending_until IS NULL OR sending_until < ?) ORDER BY next_at LIMIT ?")+ .all(now, Date.now(), limit) as OutboxRow[];let sent = 0;for (const r of due) {+ if (!claimReport(r.key)) continue;try {await sendReport(r.kind, JSON.parse(r.payload_json));- d.prepare("UPDATE billing_outbox SET done_at = ?, tries = tries + 1, last_error = NULL WHERE key = ?").run(Date.now(), r.key);+ d.prepare("UPDATE billing_outbox SET done_at = ?, tries = tries + 1, last_error = NULL, sending_until = NULL, sending_by = NULL WHERE key = ?").run(Date.now(), r.key);sent++;const account = accountOfHold(r.hold_id);if (account) forgetBalance(account);@@ -158,11 +187,11 @@ export async function drainOutbox(now = Date.now(), limit = 50): Promise<number>const age = now - r.created_at;if (age >= GIVE_UP_MS) {// Kept, marked as given up: the service's own hold sweep releases what it held.- d.prepare("UPDATE billing_outbox SET done_at = ?, tries = ?, last_error = ?, gave_up = 1 WHERE key = ?").run(now, tries, (e as Error).message.slice(0, 500), r.key);+ d.prepare("UPDATE billing_outbox SET done_at = ?, tries = ?, last_error = ?, gave_up = 1, sending_until = NULL, sending_by = NULL WHERE key = ?").run(now, tries, (e as Error).message.slice(0, 500), r.key);console.warn(`[fuobe] billing: gave up sending ${r.kind} ${r.key} after 7 days`);continue;}- d.prepare("UPDATE billing_outbox SET tries = ?, next_at = ?, last_error = ? WHERE key = ?").run(tries, now + wait, (e as Error).message.slice(0, 500), r.key);+ d.prepare("UPDATE billing_outbox SET tries = ?, next_at = ?, last_error = ?, sending_until = NULL, sending_by = NULL WHERE key = ?").run(tries, now + wait, (e as Error).message.slice(0, 500), r.key);if (age >= ALERT_AFTER_MS) console.warn(`[fuobe] billing: ${r.kind} ${r.key} still not sent after ${Math.round(age / 60_000)} min: ${(e as Error).message}`);}}diff --git a/src/server/db.ts b/src/server/db.tsindex abb0714e..78602626 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -987,6 +987,18 @@ const HOOK_COLUMNS: [string, string, string][] = [["assets", "held", "INTEGER NOT NULL DEFAULT 0"],// NULL, or "checking" (the tile says "Checking").["generations", "stage", "TEXT"],+ // A report one app process is sending now, until when: no other process sends it meanwhile (billing-outbox.ts).+ ["billing_outbox", "sending_until", "INTEGER"],+ ["billing_outbox", "sending_by", "TEXT"],+];++/**+ * Columns the runner added to generation_runs: the app process that saves a finished run's results, and until when it+ * holds that turn (generations.ts claimFinish). Two processes on one database (a deploy's overlap) never both save it.+ */+const RUNNER_COLUMNS: [string, string, string][] = [+ ["generation_runs", "finish_by", "TEXT"],+ ["generation_runs", "finish_until", "INTEGER"],];/** Columns of the relay tables that came later: [table, column, type]. */@@ -1112,7 +1124,7 @@ function open(): Database.Database {}// The optional billing and moderation services (billing.ts, moderation.ts): their tables and columns.db.exec(HOOK_TABLES);- for (const [table, column, type] of HOOK_COLUMNS) {+ for (const [table, column, type] of [...HOOK_COLUMNS, ...RUNNER_COLUMNS]) {const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);if (!has) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 036f9062..d833d602 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -2489,7 +2489,11 @@ async function pollOne(r: Row): Promise<void> {}const ctx = pollContext(r, model);// Its outputs are saved and the 3D finish runs (or ran until a restart): nothing more to ask the provider.- if (ctx.meta.finishing) return resumeFinish(r);+ // (Only the app process whose turn it is: two processes on one database never run its finish twice.)+ if (ctx.meta.finishing) {+ if (claimFinish(r.id)) resumeFinish(r);+ return;+ }// Poll first: a job that finished while the server was asleep or down is collected, not timed out.let res: PollResult | undefined;let pollError: unknown;@@ -2583,6 +2587,9 @@ async function pollOne(r: Row): Promise<void> {}res = { ...res, outputs: (res.outputs as RichOutput[]).map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, watermark: { mode, ...(marks && { marks }) } } } : o)) };}+ // One app process saves a finished run's results: the one that takes the turn (two processes on one database during a+ // deploy's overlap never both save them, and the second never ends a saved run as failed).+ if (!claimFinish(r.id)) return;// Mark first so a slow download isn't polled twice.update(r.id, { status: "running", progress: 0.99, message: "Saving results" });const outputs: OutputFile[] = [];@@ -2604,6 +2611,8 @@ async function pollOne(r: Row): Promise<void> {for (const o of keepMatte(res.outputs as RichOutput[], matte)) {try {outputs.push(await persistOutput(o, r.id));+ // Still saving: the turn is still this process's.+ claimFinish(r.id);} catch (e) {if (account) {for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);@@ -2679,6 +2688,38 @@ async function pollOne(r: Row): Promise<void> {});}+/** How long an app process holds the turn to save a finished run's results (it renews it as it goes). */+const FINISH_TURN_MS = 5 * 60_000;++declare global {+ /** This app process, as the runs whose results it saves name it. */+ var __fuobeRunnerToken: string | undefined;+}++const runnerToken = () => (globalThis.__fuobeRunnerToken ??= `${process.pid}:${nanoid(12)}`);++/**+ * Take (or renew) this app process's turn to save a run's results: only while the run still goes, and only when no other+ * process holds the turn (or its turn ran out: that process stopped part way, so this one takes over). Two processes on+ * one database (a deploy's overlap) never both save a run, so a run is finished once.+ */+export function claimFinish(id: string, now = Date.now()): boolean {+ const d = db();+ return d+ .transaction((): boolean => {+ const g = d.prepare("SELECT status FROM generations WHERE id = ?").get(id) as Pick<Row, "status"> | undefined;+ if (!g || (g.status !== "queued" && g.status !== "running")) return false;+ const me = runnerToken();+ d.prepare("INSERT OR IGNORE INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, NULL)").run(id, now);+ return (+ d+ .prepare("UPDATE generation_runs SET finish_by = ?, finish_until = ? WHERE id = ? AND (finish_by IS NULL OR finish_by = ? OR finish_until IS NULL OR finish_until < ?)")+ .run(me, now + FINISH_TURN_MS, id, me, now).changes > 0+ );+ })+ .immediate();+}+/** Start (or keep running) the 3D finish of a job whose outputs are stored; it marks the job done when it ends. */function resumeFinish(r: Row): void {const outputs = JSON.parse(r.outputs_json || "[]") as OutputFile[];diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 2cfc7573..b23535be 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -1059,13 +1059,16 @@ describe("two app processes on one database (a deploy's overlap)", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});- it("while one process saves a finished run's result, the other saves it too today, and the run ends failed: no runner lease or one-time finalize", async () => {+ it("while one process saves a finished run's result, the other leaves it to that process: the result is saved once, and the run settles once", async () => {const w = standInWorker();const { id } = await pressRun();+ const watch = watchOf(id, { "other process": there(id) });const d = driver(w);// This process's runner turns at every step but the result's parts: the result is saved below.d.onStep(async (step) => {- if (step !== "part") await tick();+ if (step === "part") return;+ await tick();+ await watch.look();});await d.beat();expect(await d.runOne()).toBe(true);@@ -1076,12 +1079,37 @@ describe("two app processes on one database (a deploy's overlap)", () => {const theirs = app2.tick();await pause.paused;await tick();+ // (Only this process is looked at now: the other one waits in the middle of its move until it is released.)+ expect(getGeneration(id)?.status, "this process leaves the run to the one saving it").toBe("running");+ expect(getGeneration(id)?.message).toBe(POOL_WORDS.working);pause.release();await theirs;- await expectFreeFailure(id);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a process that stopped while it saved a result leaves it to the other once its turn runs out", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ expect(getGeneration(id)?.status).toBe("running");+ // Another process took the turn and stopped (a deploy ended it) before it saved anything.+ db().prepare("UPDATE generation_runs SET finish_by = 'another-process', finish_until = ? WHERE id = ?").run(Date.now() + 60_000, id);+ await tick();+ expect(getGeneration(id)?.status).toBe("running");+ // Its turn runs out: this process saves the result.+ db().prepare("UPDATE generation_runs SET finish_until = ? WHERE id = ?").run(Date.now() - 1, id);+ await expectOnce(id, watch, { prompts: 1, place: 1 });});- it("both processes send a finished run's report today when their sweeps meet, so the service gets it twice", async () => {+ it("both processes' sweeps meet over a finished run's report: one sends it, so the service gets it once", async () => {const w = standInWorker();const { id } = await pressRun();const watch = watchOf(id);@@ -1105,6 +1133,7 @@ describe("two app processes on one database (a deploy's overlap)", () => {expect(watch.problems({ place: 1 })).toEqual([]);expect(g?.status).toBe("succeeded");const settle = { holdId: holdOf(id), kind: "settle", status: "succeeded" };- expect(svc.reportsFor(id)).toEqual([settle, settle]);+ expect(svc.reportsFor(id)).toEqual([settle]);+ expect(svc.callsOf("/v1/settle").filter((c) => (c.body as { generationId?: string }).generationId === id)).toHaveLength(1);});});