Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Workers: a newer app process is known from its start, and tickets are remade only for a known older catalog

Adarsh6b9d70d0e057
diff --git a/src/server/computer/ticket-refresh.ts b/src/server/computer/ticket-refresh.ts
index 252c9c66..abe76001 100644
--- a/src/server/computer/ticket-refresh.ts
+++ b/src/server/computer/ticket-refresh.ts
@@ -17,7 +17,10 @@ import { endTask, inputsOf, json, setTask, swapTaskInput, type TaskRow } from ".
* allowed) ends its run in one plain sentence. Only waiting tasks: one a worker holds finishes with the ticket it has.
*
* Only forward: while a deploy's two app processes share the database, only the one started last (the newest version)
- * makes tickets again, and only it ever ends a run for it. The other leaves every ticket as it is.
+ * makes tickets again, and only it ever ends a run for it. The other leaves every ticket as it is. Each app process says
+ * its version and start in the database from its start, and again with its beat (noteCatalogProcess), so the newer one
+ * is known before it serves any claim. And a process remakes only the tickets of a version it knows to be older: one whose
+ * processes started before it, or have all stopped. A ticket of a version it doesn't know is never touched.
*/
declare global {
@@ -27,29 +30,48 @@ declare global {
/** When this app process started. */
export const processStart = () => (globalThis.__fuobeProcessStart ??= Math.round(Date.now() - process.uptime() * 1000));
-/** An app process that said nothing for this long has stopped (each one says so at most a minute apart while workers claim). */
+/** An app process that said nothing for this long has stopped (each one says so with its beat, every few seconds). */
const GONE_MS = 5 * 60_000;
+/**
+ * Say that an app process of this catalog version runs (started at `startedAt`): at its start and with its beat
+ * (generations.ts keepBeating), and before it remakes tickets.
+ */
+export function noteCatalogProcess(version: string | null = catalogVersion(), startedAt = processStart(), now = Date.now()): void {
+ if (!version) return;
+ db()
+ .prepare("INSERT INTO catalog_processes (version, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(version) DO UPDATE SET started_at = MAX(started_at, excluded.started_at), seen_at = MAX(seen_at, excluded.seen_at)")
+ .run(version, startedAt, now);
+}
+
/**
* Say that a process of this catalog version runs (started at `startedAt`), and whether it is the newest: of the app
* processes on this database heard from lately, none started after it with another version. A deploy's new process is
* the newest from its start; so is a rollback's.
*/
export function newestCatalog(version: string, startedAt = processStart(), now = Date.now()): boolean {
- const d = db();
- d.prepare("INSERT INTO catalog_processes (version, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(version) DO UPDATE SET started_at = MAX(started_at, excluded.started_at), seen_at = MAX(seen_at, excluded.seen_at)").run(version, startedAt, now);
- const later = d.prepare("SELECT 1 FROM catalog_processes WHERE version != ? AND seen_at > ? AND started_at > ? LIMIT 1").get(version, now - GONE_MS, startedAt);
+ noteCatalogProcess(version, startedAt, now);
+ const later = db().prepare("SELECT 1 FROM catalog_processes WHERE version != ? AND seen_at > ? AND started_at > ? LIMIT 1").get(version, now - GONE_MS, startedAt);
return !later;
}
+/**
+ * SQL: the catalog versions a process of version @version started at @startedAt may remake tickets of. Only versions it
+ * knows (their processes said so) and that are older than it: started before it, or every process of it has stopped.
+ */
+const OLDER_VERSIONS = "SELECT version FROM catalog_processes WHERE version != @version AND (started_at < @startedAt OR seen_at <= @gone)";
+
export async function refreshTickets(o: { version?: string; startedAt?: number; now?: number } = {}): Promise<{ refreshed: number; ended: number }> {
const version = o.version ?? catalogVersion();
if (!version) return { refreshed: 0, ended: 0 };
+ const startedAt = o.startedAt ?? processStart();
+ const now = o.now ?? Date.now();
// A process of an older version (a deploy's overlap) leaves every ticket as it is.
- if (!newestCatalog(version, o.startedAt ?? processStart(), o.now ?? Date.now())) return { refreshed: 0, ended: 0 };
+ if (!newestCatalog(version, startedAt, now)) return { refreshed: 0, ended: 0 };
+ // Only tickets of a version known to be older: never one this process doesn't know (it may be newer).
const rows = db()
- .prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND ticket_json IS NOT NULL AND json_extract(ticket_json, '$.catalogVersion') IS NOT ?")
- .all(version) as TaskRow[];
+ .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND ticket_json IS NOT NULL AND json_extract(ticket_json, '$.catalogVersion') IN (${OLDER_VERSIONS})`)
+ .all({ version, startedAt, gone: now - GONE_MS }) as TaskRow[];
const catalog = { has: (id: string) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow };
let refreshed = 0;
let ended = 0;
diff --git a/src/server/generations.ts b/src/server/generations.ts
index ed7a5643..4782984a 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -128,7 +128,9 @@ import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";
import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";
import { hostedRunsOn } from "./hosted-switch";
+import { catalogVersion } from "./computer/catalog-version";
import { poolLane, queueOfGeneration } from "./computer/pool";
+import { noteCatalogProcess, processStart } from "./computer/ticket-refresh";
import { runPreviewAt } from "./computer/tasks";
import { runCeilingMs } from "./queue-settings";
import { sweepBilling } from "./billing-outbox";
@@ -3161,11 +3163,15 @@ declare global {
const runnerToken = () => (globalThis.__fuobeRunnerToken ??= `${process.pid}:${nanoid(12)}`);
-/** Say that this app process still runs. */
+/**
+ * Say that this app process still runs, and which catalog version it makes job tickets for (ticket-refresh.ts: a newer
+ * process is known from its start, before it serves any worker's claim).
+ */
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);
+ noteCatalogProcess(catalogVersion(), processStart(), now);
}
/**
diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.ts
index aad3f4de..7b9a184b 100644
--- a/tests/recovery-server.test.ts
+++ b/tests/recovery-server.test.ts
@@ -1564,6 +1564,18 @@ describe("two app processes on one database (a deploy's overlap)", () => {
return { app, token };
}
+ it("each app process says its catalog version from its start, before it serves any worker's claim", async () => {
+ const version = catalogVersion()!;
+ const t0 = Date.now();
+ db().prepare("DELETE FROM catalog_processes").run();
+ // The other process's beat (every 5 s, from its start) says it again.
+ for (let i = 0; i < 100 && !db().prepare("SELECT 1 FROM catalog_processes WHERE version = ?").get(version); i++) await sleep(100);
+ const r = db().prepare("SELECT started_at, seen_at FROM catalog_processes WHERE version = ?").get(version) as { started_at: number; seen_at: number } | undefined;
+ expect(r, "the catalog version of the app processes").toBeTruthy();
+ expect(r!.seen_at).toBeGreaterThanOrEqual(t0);
+ expect(r!.started_at).toBeLessThanOrEqual(r!.seen_at);
+ });
+
it("the other process serves the worker and a session: the same run, the same state", async () => {
const w = standInWorker();
const { id } = await pressRun();
diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.ts
index 44466084..90382533 100644
--- a/tests/worker-tickets.test.ts
+++ b/tests/worker-tickets.test.ts
@@ -352,7 +352,9 @@ describe("the line hands out tickets inside each PC's ceiling", () => {
});
it("a waiting task whose ticket was made for the catalog before an update gets its ticket made again, with its place kept", async () => {
- const { refreshTickets } = await import("@/server/computer/ticket-refresh");
+ const { noteCatalogProcess, processStart, refreshTickets } = await import("@/server/computer/ticket-refresh");
+ // The app process before the update said its catalog version when it ran.
+ noteCatalogProcess(OTHER, processStart() - 60_000, Date.now() - 60_000);
const w = addWorker();
beat(w);
const mine = await accountTask();
@@ -418,6 +420,30 @@ describe("the line hands out tickets inside each PC's ceiling", () => {
}
});
+ it("an older process that serves a claim before the newer one has served any changes nothing, and never touches a version it doesn't know", async () => {
+ const { noteCatalogProcess, refreshTickets } = await import("@/server/computer/ticket-refresh");
+ db().prepare("DELETE FROM catalog_processes").run();
+ try {
+ const w = addWorker();
+ beat(w);
+ // A run the newer process queued, whose ticket names a workflow only the newer catalog has.
+ const newer = await accountTask();
+ db().prepare("UPDATE relay_tasks SET ticket_json = ? WHERE id = ?").run(JSON.stringify({ ...JSON.parse(row(newer.id).ticket_json!), workflowId: "a-workflow-only-the-new-catalog-has" }), newer.id);
+ const was = row(newer.id);
+ const t0 = Date.now();
+ // The older process (another catalog, started a minute before) serves a worker's claim first: the newer version is
+ // one it doesn't know, so its ticket stays as it is and its run goes on.
+ expect(await refreshTickets({ version: OTHER, startedAt: t0 - 60_000, now: t0 })).toEqual({ refreshed: 0, ended: 0 });
+ expect(row(newer.id)).toMatchObject({ state: "waiting", ticket_json: was.ticket_json, needs_json: was.needs_json });
+ // Once the newer process has said it runs (at its start and with its beat), the older one isn't the newest either.
+ noteCatalogProcess(VERSION, t0, t0 + 1000);
+ expect(await refreshTickets({ version: OTHER, startedAt: t0 - 60_000, now: t0 + 2000 })).toEqual({ refreshed: 0, ended: 0 });
+ expect(row(newer.id)).toMatchObject({ state: "waiting", ticket_json: was.ticket_json });
+ } finally {
+ db().prepare("DELETE FROM catalog_processes").run();
+ }
+ });
+
it("a ticket made again for a new catalog gets the files its graph makes made again, and its lane and needs from the new catalog", async () => {
const { refreshTickets } = await import("@/server/computer/ticket-refresh");
db().prepare("DELETE FROM catalog_processes").run();
@@ -448,6 +474,9 @@ describe("the line hands out tickets inside each PC's ceiling", () => {
.prepare("UPDATE relay_tasks SET ticket_json = ?, needs_json = ?, lane = ? WHERE id = ?")
.run(JSON.stringify(before), JSON.stringify({ workflowId: "palette-transfer-image", files: [], packs: [], minVramBytes: 0, catalogVersion: OTHER }), "small", id);
expect(claim(w)).toBeNull();
+ // The app process before the update said its catalog version when it ran.
+ const { noteCatalogProcess, processStart } = await import("@/server/computer/ticket-refresh");
+ noteCatalogProcess(OTHER, processStart() - 60_000, Date.now() - 60_000);
expect(await refreshTickets()).toEqual({ refreshed: 1, ended: 0 });
const after = row(id);
const next = JSON.parse(after.ticket_json!) as import("@/lib/job-ticket").JobTicket;