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: an app restarted while it saved a result collects it at once
Adarsh682b8beda9e2
diff --git a/src/server/db.ts b/src/server/db.tsindex 8760d417..dcba1ab0 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1015,6 +1015,17 @@ const RUNNER_COLUMNS: [string, string, string][] = [["generation_runs", "finish_until", "INTEGER"],];+/**+ * Each app process on this database, by the name its turns carry, and when it last said it still runs (generations.ts+ * keepBeating). A turn whose process went quiet is free before it runs out. Made here rather than as a numbered+ * migration, so branches that add migrations never clash over its place.+ */+const RUNNER_TABLES = `CREATE TABLE IF NOT EXISTS app_processes (+ token TEXT PRIMARY KEY,+ started_at INTEGER NOT NULL,+ seen_at INTEGER NOT NULL+ );`;+/** Columns of the relay tables that came later: [table, column, type]. */const RELAY_COLUMNS: [string, string, string][] = [["relay_runners", "comfy", "TEXT NOT NULL DEFAULT 'ok'"],@@ -1138,6 +1149,7 @@ function open(): Database.Database {}// The optional billing and moderation services (billing.ts, moderation.ts): their tables and columns.db.exec(HOOK_TABLES);+ db.exec(RUNNER_TABLES);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 57e1da70..a653005b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -2328,6 +2328,7 @@ export function ensureRunner(): void {function startRunner(): void {watchGenerations(db());+ keepBeating();const cur = globalThis.__fuobeRunner;if (cur) {// After a dev hot-reload, point the existing timers at this module's (fresh) code.@@ -2717,9 +2718,9 @@ async function pollOne(r: Row): Promise<void> {/*** Change a run the runner looked at, only while it still goes (queued or running, and not held for its output check) and- * no other app process holds its turn to save its results. A look that took a while (a slow poll, a deploy's overlap) never takes a run another- * process saved, failed or canceled meanwhile back to an earlier state, and never fails a run another process is- * saving. Returns whether the change was made.+ * no other app process that still runs holds its turn to save its results. A look that took a while (a slow poll, a+ * deploy's overlap) never takes a run another process saved, failed or canceled meanwhile back to an earlier state, and+ * never fails a run another process is saving. Returns whether the change was made.*/export function updateLive(id: string, fields: Partial<Row>, now = Date.now()): boolean {const keys = Object.keys(fields);@@ -2728,28 +2729,90 @@ export function updateLive(id: string, fields: Partial<Row>, now = Date.now()):db().prepare(`UPDATE generations SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id AND status IN ('queued', 'running') AND stage IS NULL- AND NOT EXISTS (SELECT 1 FROM generation_runs WHERE id = @__id AND finish_by IS NOT NULL AND finish_by != @__me AND finish_until >= @__now)`,+ AND NOT EXISTS (SELECT 1 FROM generation_runs t WHERE t.id = @__id AND t.finish_by IS NOT NULL AND t.finish_by != @__me AND t.finish_until >= @__now+ AND NOT ${HOLDER_QUIET})`,)- .run({ ...fields, __now: now, __id: id, __me: runnerToken() }).changes > 0+ .run({ ...fields, __now: now, __id: id, __me: runnerToken(), __quiet: now - QUIET_MS }).changes > 0);}/** 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;+/** How often an app process says it still runs (keepBeating)… */+const BEAT_MS = 5_000;+/** …and how long after its last word it counts as stopped (killed, or crashed): its turns are free then, before they run out. */+export const QUIET_MS = 20_000;+/** A process quiet this long is forgotten. */+const FORGET_MS = 24 * 60 * 60_000;++/** SQL: the process holding turn `t` has been quiet since before @__quiet. A turn whose process has no row waits to run out. */+const HOLDER_QUIET = "EXISTS (SELECT 1 FROM app_processes p WHERE p.token = t.finish_by AND p.seen_at < @__quiet)";declare global {/** This app process, as the runs whose results it saves name it. */var __fuobeRunnerToken: string | undefined;+ /** This app process's beat (keepBeating). */+ var __fuobeBeat: ReturnType<typeof setInterval> | undefined;}const runnerToken = () => (globalThis.__fuobeRunnerToken ??= `${process.pid}:${nanoid(12)}`);+/** Say that this app process still runs. */+function beat(now = Date.now()): void {+ db()+ .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);+}++/**+ * From now on, this app process says every 5 s that it still runs (in the database, so every process on it reads that,+ * wherever it runs), and another process takes a turn this one holds only once this one has been quiet for 20 s. When it+ * exits, it gives its turns back at once, so the app that starts next saves those runs straight away. Once per process:+ * the runner starts it, and so does the first turn it takes.+ */+function keepBeating(): void {+ if (globalThis.__fuobeBeat) return;+ const now = Date.now();+ try {+ beat(now);+ db().prepare("DELETE FROM app_processes WHERE seen_at < ?").run(now - FORGET_MS);+ } catch (e) {+ console.warn(`[generations] app process: ${(e as Error).message}`);+ }+ const timer = setInterval(() => {+ try {+ beat();+ } catch {+ // A busy or closed database: the next beat says it.+ }+ }, BEAT_MS);+ timer.unref?.();+ globalThis.__fuobeBeat = timer;+ process.once("exit", giveTurnsBack);+}++/** This app process exits (it saves nothing more): its turns go back now, and its row with them. */+function giveTurnsBack(): void {+ try {+ const d = db();+ 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());+ d.prepare("DELETE FROM app_processes WHERE token = ?").run(me);+ })();+ } catch {+ // The database closed first: its turns are free once this process has been quiet for 20 s.+ }+}+/*** 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.+ * process holds the turn, or the one that holds it stopped part way (its turn ran out, or it has been quiet for 20 s:+ * killed, or crashed), 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 {+ keepBeating();const d = db();return d.transaction((): boolean => {@@ -2760,8 +2823,11 @@ export function claimFinish(id: string, now = Date.now()): boolean {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+ .prepare(+ `UPDATE generation_runs AS t SET finish_by = @__me, finish_until = @until WHERE t.id = @__id+ AND (t.finish_by IS NULL OR t.finish_by = @__me OR t.finish_until IS NULL OR t.finish_until < @__now OR ${HOLDER_QUIET})`,+ )+ .run({ __me: me, until: now + FINISH_TURN_MS, __id: id, __now: now, __quiet: now - QUIET_MS }).changes > 0);}).immediate();diff --git a/tests/helpers/app-process.ts b/tests/helpers/app-process.tsindex 8aad3368..80877dd9 100644--- a/tests/helpers/app-process.ts+++ b/tests/helpers/app-process.ts@@ -31,7 +31,10 @@ export interface AppProcess {pauseNextSave: () => Promise<{ paused: Promise<void>; release: () => void }>;/** What it wrote to its error output. */errors: () => string;+ /** It exits as `next start` does when it is told to stop (its exit handlers run). */stop: () => Promise<void>;+ /** It is killed: it ends at once, with no word and none of its exit handlers. */+ kill: () => Promise<void>;}const realFetch = globalThis.fetch;@@ -100,6 +103,12 @@ export async function startAppProcess(o: { dataDir: string; env?: Record<string,await Promise.race([ended, new Promise((r) => setTimeout(r, 5000))]);if (child.exitCode === null) child.kill();},+ kill: async () => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const ended = new Promise((r) => child.once("exit", r));+ child.kill("SIGKILL");+ await ended;+ },};}diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 87b9e48b..b5d60735 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -58,7 +58,7 @@ const { NextRequest } = await import("next/server");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");const { setSetting } = await import("@/server/settings");-const { getGeneration, ensureRunner, updateLive } = await import("@/server/generations");+const { getGeneration, ensureRunner, QUIET_MS, updateLive } = await import("@/server/generations");const pool = await import("@/server/computer/pool");const tasks = await import("@/server/computer/tasks");const billing = await import("@/server/billing");@@ -1549,12 +1549,9 @@ describe("a deploy while results are being sent", () => {describe("two app processes on one database (a deploy's overlap)", () => {let app2: AppProcess;+ const appEnv = () => ({ FUOBE_HOSTED_RUNS: "1", FUOBE_BILLING_URL: svc.address, FUOBE_BILLING_TOKEN: svc.token, COMFYUI_URL: DEAD, FUOBE_PUBLIC_SIGNUP: "1" });beforeAll(async () => {- app2 = await startAppProcess({- dataDir: dir,- env: { FUOBE_HOSTED_RUNS: "1", FUOBE_BILLING_URL: svc.address, FUOBE_BILLING_TOKEN: svc.token, COMFYUI_URL: DEAD, FUOBE_PUBLIC_SIGNUP: "1" },- allow: [comfy.url],- });+ app2 = await startAppProcess({ dataDir: dir, env: appEnv(), allow: [comfy.url] });});afterAll(async () => {await app2?.stop();@@ -1563,6 +1560,26 @@ describe("two app processes on one database (a deploy's overlap)", () => {/** The run as the account's session reads it from the other process. */const there = (id: string) => async () => (await app2.generation(id, a1)) as unknown as RunLike;+ /** When the app process that names its turns `token` last said it still runs (none: it exited, or never ran). */+ const seenAt = (token: string) => (db().prepare("SELECT seen_at FROM app_processes WHERE token = ?").get(token) as { seen_at: number } | undefined)?.seen_at;+ /** The app process that holds the turn to save the run's result. */+ const turnOf = (id: string) => (db().prepare("SELECT finish_by FROM generation_runs WHERE id = ?").get(id) as { finish_by: string | null } | undefined)?.finish_by ?? null;+ /** That process is in the middle of saving the run's result: it took the turn, minutes before its turn runs out. */+ const holdTurn = (id: string, token: string) => db().prepare("UPDATE generation_runs SET finish_by = ?, finish_until = ? WHERE id = ?").run(token, Date.now() + 4 * MIN, id);++ /** One more app process on this database, and the name its turns carry. */+ async function anotherApp(): Promise<{ app: AppProcess; token: string }> {+ const tokens = () => (db().prepare("SELECT token FROM app_processes").all() as { token: string }[]).map((r) => r.token);+ const known = new Set(tokens());+ const app = await startAppProcess({ dataDir: dir, env: appEnv(), allow: [comfy.url] });+ const token = tokens().find((t) => !known.has(t));+ if (!token) {+ await app.stop();+ throw new Error("The new app process never said it runs");+ }+ return { app, token };+ }+it("the other process serves the worker and a session: the same run, the same state", async () => {const w = standInWorker();const { id } = await pressRun();@@ -1659,6 +1676,73 @@ describe("two app processes on one database (a deploy's overlap)", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});+ it("an app restarted while it saved a result collects it at once: the app that stopped gave its turn back as it exited", 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");+ // The app before the restart was saving the result (it holds the turn, for minutes yet) when it was told to stop.+ const { app, token } = await anotherApp();+ try {+ holdTurn(id, token);+ for (let i = 0; i < 3; i++) await tick();+ expect(getGeneration(id)?.status, "a turn whose app still runs is left to it").toBe("running");+ expect(updateLive(id, { message: POOL_WORDS.inLine })).toBe(false);+ // While it runs, it says so every few seconds: a turn it has held longer than its quiet limit stays its own.+ const quietSince = seenAt(token)! - QUIET_MS - 1000;+ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = ?").run(quietSince, token);+ for (let i = 0; i < 150 && seenAt(token)! <= quietSince; i++) await sleep(100);+ expect(seenAt(token), "its next word").toBeGreaterThan(quietSince);+ await tick();+ expect(getGeneration(id)?.status).toBe("running");+ expect(turnOf(id)).toBe(token);+ } finally {+ await app.stop();+ }+ // It exited as an app does when it is told to stop: its turn went with it, and this app saves the result now.+ expect(seenAt(token)).toBeUndefined();+ expect(turnOf(id)).toBeNull();+ await tick();+ expect(getGeneration(id)?.status).toBe("succeeded");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("an app killed while it saved a result leaves it to this one once it has been quiet for 20 s, minutes before 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);+ const { app, token } = await anotherApp();+ holdTurn(id, token);+ await app.kill();+ // Killed: nothing of it ran as it ended, so its turn and its last word are still there.+ expect(turnOf(id)).toBe(token);+ await tick();+ expect(getGeneration(id)?.status, "its last word is a moment old: it may only be slow").toBe("running");+ // 20 s with no word from it: it stopped, and this app saves the result, long before its turn would run out.+ clock();+ vi.setSystemTime(Date.now() + QUIET_MS + 1000);+ await tick();+ expect(getGeneration(id)?.status).toBe("succeeded");+ expect(turnOf(id)).not.toBe(token);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });+it("a run stopped while its result is saved stays stopped, and the file saved for it goes (none is left filling the account's space)", async () => {const w = standInWorker();const { id } = await pressRun();diff --git a/tests/runtime-runner.test.ts b/tests/runtime-runner.test.tsindex 193376b8..60083358 100644--- a/tests/runtime-runner.test.ts+++ b/tests/runtime-runner.test.ts@@ -152,6 +152,34 @@ describe("restarts (S7)", () => {globalThis.__fuobeSubmitting!.delete("uploading-1");}});++ it("collects a result whose save the app before a restart left part way at once, not when that app's turn would run out", async () => {+ const g = image("saved by the app before a restart");+ await until(() => row(g.id).external_id);+ // That app took the turn to save the result, minutes before its turn runs out, and still said it ran a moment ago.+ const now = Date.now();+ db().prepare("INSERT OR IGNORE INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, NULL)").run(g.id, now);+ db().prepare("INSERT INTO app_processes (token, started_at, seen_at) VALUES ('app-before', ?, ?)").run(now - 60_000, now);+ db().prepare("UPDATE generation_runs SET finish_by = 'app-before', finish_until = ? WHERE id = ?").run(now + 4 * 60_000, g.id);+ const poll = mockProvider.poll;+ let finished = false;+ mockProvider.poll = async (ctx) => {+ const r = await poll(ctx);+ if (ctx.externalId === row(g.id).external_id && r.state === "succeeded") finished = true;+ return r;+ };+ try {+ // The result is ready at the provider. While that app may still be saving it, it is left to that app.+ await until(() => finished, 10_000);+ await sleep(2_000);+ expect(["queued", "running"]).toContain(row(g.id).status);+ // 20 s with no word from it (it was killed, or crashed): this app saves the result at its next turn.+ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = 'app-before'").run(Date.now() - gens.QUIET_MS - 1000);+ expect((await settle(g.id, 5_000)).status).toBe("succeeded");+ } finally {+ mockProvider.poll = poll;+ }+ });});describe("cancel while submitting (S13)", () => {