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.

Runner: waiting steps move past an older backlog; a step only feeding a failed one is dropped unpaid

Claude68ae296ead29
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index e6fb9649..56be6b3b 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -698,6 +698,12 @@ export interface GenerationRequest {
chain?: ChainSlot[];
/** Server-set when the runner filled the chain slots from the earlier steps' outputs (a retry takes them out again: unfilledRequest). */
chainFilled?: boolean;
+ /**
+ * A step only worth making for the steps after it (a per-frame render's frame edits and clips): while it still
+ * waits for its inputs (nothing spent yet), the runner cancels it once every step that would use it has failed
+ * or been canceled, so one failed frame doesn't leave the other lanes running up the bill.
+ */
+ dropWhenUnused?: boolean;
/** Storyboard frame this request makes (shown under the frame). */
frame?: { scene: string; index: number; of: number };
/** Part of a multi-step job (a shot of a multi-shot film, a step of an extend): shown on its tile. */
@@ -737,13 +743,22 @@ export interface ChainSlot {
/**
* Fan-out from a step that makes a list (extract-frames: one image per frame): take the dependency's
* output number `index` of the slot's kind (0-based, by `meta.index` when the outputs carry it). Past
- * the end it takes the last one, so a provider that returns a frame fewer than planned holds the last
- * frame instead of failing the whole render. One step per index fans a list out; a step with one slot
+ * the end it takes the last one, so a provider that returns a frame or two fewer than planned holds the
+ * last frame instead of failing the whole render (`of` bounds how many). One step per index fans a list out; a step with one slot
* per index gathers it back in order.
*/
index?: number;
+ /**
+ * With `index`: how many outputs the list was planned to have. A list more than CHAIN_LIST_SLACK short of it
+ * fails the step before it runs (a frame or two lost at the clip's end is held; half a clip of frozen, paid
+ * frames is not).
+ */
+ of?: number;
}
+/** How many outputs a planned list (ChainSlot.of) may be short of before the steps reading it fail. */
+export const CHAIN_LIST_SLACK = 2;
+
/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */
export interface GenInput extends GenParams {
prompt?: string;
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 7b423261..300dd911 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -298,6 +298,11 @@ export interface PipelineStep {
export interface PipelineOptions {
/** Group the steps (defaults to a new batch id). */
batchId?: string;
+ /**
+ * Steps made before, by key → generation id (a retry's steps that finished or are still running): steps
+ * may wait for them like for any other step, and they aren't made again.
+ */
+ existing?: Record<string, string>;
}
export interface Pipeline {
@@ -313,11 +318,16 @@ const asList = (a: string | string[] | undefined) => (a === undefined ? [] : Arr
/** Chain slots that take an audio output (and so may pick a stem). */
const AUDIO_SLOTS = new Set<ChainSlot["slot"]>(["audio", "voiceAudio", "audio2"]);
-/** Kahn's algorithm: steps in an order where every `after` comes first; throws on a cycle. Linear in steps + edges (a per-frame render has hundreds). */
+/**
+ * Kahn's algorithm: steps in an order where every `after` comes first; throws on a cycle. Linear in steps + edges
+ * (a per-frame render has hundreds). Keys that aren't steps (generations made before) are already done.
+ */
function topoOrder(steps: PipelineStep[]): PipelineStep[] {
- const indegree = new Map(steps.map((s) => [s.key, new Set(asList(s.after)).size]));
+ const keys = new Set(steps.map((s) => s.key));
+ const waits = (s: PipelineStep) => new Set(asList(s.after).filter((a) => keys.has(a)));
+ const indegree = new Map(steps.map((s) => [s.key, waits(s).size]));
const next = new Map<string, PipelineStep[]>();
- for (const t of steps) for (const a of new Set(asList(t.after))) next.set(a, [...(next.get(a) ?? []), t]);
+ for (const t of steps) for (const a of waits(t)) next.set(a, [...(next.get(a) ?? []), t]);
const ready = steps.filter((s) => indegree.get(s.key) === 0);
const out: PipelineStep[] = [];
for (let i = 0; i < ready.length; i++) {
@@ -370,17 +380,18 @@ function topoOrder(steps: PipelineStep[]): PipelineStep[] {
*/
export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}): Pipeline {
if (!steps.length) throw new Error("A pipeline needs at least one step");
+ const existing = opts.existing ?? {};
const keys = new Set<string>();
for (const s of steps) {
if (!s.key?.trim()) throw new Error("Every step needs a key");
- if (keys.has(s.key)) throw new Error(`Two steps are called “${s.key}”`);
+ if (keys.has(s.key) || Object.hasOwn(existing, s.key)) throw new Error(`Two steps are called “${s.key}”`);
keys.add(s.key);
}
for (const s of steps) {
const after = asList(s.after);
for (const a of after) {
if (a === s.key) throw new Error(`Step “${s.key}” can't wait for itself`);
- if (!keys.has(a)) throw new Error(`Step “${s.key}” waits for “${a}”, which isn't in the pipeline`);
+ if (!keys.has(a) && !Object.hasOwn(existing, a)) throw new Error(`Step “${s.key}” waits for “${a}”, which isn't in the pipeline`);
}
if (new Set(after).size !== after.length) throw new Error(`Step “${s.key}” lists the same step twice`);
const chain = s.chain ?? s.request.chain;
@@ -389,6 +400,8 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}
if (stray) throw new Error(`Step “${s.key}”: a stem (“${stray.stem}”) only goes into an audio slot, not “${stray.slot}”`);
const badIndex = chain?.find((c) => c.index !== undefined && !(Number.isInteger(c.index) && c.index >= 0));
if (badIndex) throw new Error(`Step “${s.key}”: an output number must be a whole number from 0 (got ${badIndex.index})`);
+ const badCount = chain?.find((c) => c.of !== undefined && (c.index === undefined || !Number.isInteger(c.of) || c.of <= c.index));
+ if (badCount) throw new Error(`Step “${s.key}”: a list of ${badCount.of} has no output number ${badCount.index ?? "(none given)"}`);
}
const ordered = topoOrder(steps);
const n = steps.length;
@@ -417,7 +430,12 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}
return { key: s.key, ...p };
});
const demo = previews.find((p) => p.demo);
- if (demo && previews.some((p) => !p.demo)) {
+ // Steps made before count too: a demo step can't continue what ran for real.
+ const madeForReal = Object.values(existing).some((id) => {
+ const g = getGeneration(id, { includeDeleted: true });
+ return g && g.provider !== "mock";
+ });
+ if (demo && (madeForReal || previews.some((p) => !p.demo))) {
throw new Error(`Step “${demo.key}” would run as a demo (${demo.model.name} needs ${providerNames(demo.model, demo.op)}) while the others run for real — connect it in Settings, or turn on demo mode to try it all as a demo`);
}
@@ -427,7 +445,7 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}
try {
for (const s of ordered) {
const after = asList(s.after);
- const made = createGenerations(requests.get(s.key)!, { batchId, ...(after.length && { dependsOn: after.map((a) => byKey[a].id) }) });
+ const made = createGenerations(requests.get(s.key)!, { batchId, ...(after.length && { dependsOn: after.map((a) => byKey[a]?.id ?? existing[a]) }) });
byKey[s.key] = made[0];
items.push(...made);
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index b2dc9bfc..57dd1b73 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -13,6 +13,7 @@ import { chainedWaitMessage, keyframeChain } from "@/lib/catalog/keyframes";
import { estimateCost, inferOperation, planGeneration, routesFor } from "@/lib/catalog/plan";
import { keepMatte } from "@/lib/catalog/payload";
import {
+ CHAIN_LIST_SLACK,
LAST_FRAME_CHAIN,
OPERATION_OUTPUT,
type ChainSlot,
@@ -581,6 +582,18 @@ export function pickOutput(outputs: OutputFile[], s: ChainSlot): OutputFile | un
const slotNoun = (s: ChainSlot) => (s.stem ? `${s.stem} stem` : s.slot === "mask" ? "mask" : SLOT_KIND[s.slot]);
+/**
+ * A planned list (ChainSlot `index` + `of`) that came back too short to read: a frame or two missing at
+ * the end is held (pickOutput takes the last one), more fails the step before it is paid for.
+ */
+export function listShortfall(outputs: OutputFile[], s: ChainSlot): string | null {
+ if (s.index === undefined || s.of === undefined) return null;
+ const made = outputs.filter((o) => o.kind === SLOT_KIND[s.slot]).length;
+ if (made >= s.of - CHAIN_LIST_SLACK) return null;
+ const noun = slotNoun(s);
+ return `made ${made} ${noun}${made === 1 ? "" : "s"} where ${s.of} were planned`;
+}
+
function placeholderFor(s: ChainSlot): string {
const kind = SLOT_KIND[s.slot];
if (kind === "text") return "Placeholder text from an earlier step";
@@ -674,11 +687,63 @@ function chainMode(p: { demo: boolean; plan: { model: { name: string } }; route:
return {};
}
+/** A waiting row's dependency ids as a json_each source (depends_on is one id, or a JSON list). */
+const DEP_IDS = "json_each(CASE WHEN substr(g.depends_on, 1, 1) = '[' AND json_valid(g.depends_on) THEN g.depends_on ELSE json_array(g.depends_on) END) d";
+
+/**
+ * Waiting steps that can move: none of their dependencies is still queued or running (so they launch), or one
+ * failed, was canceled or is gone (so they fail now, not after the others finish). A per-frame render keeps
+ * hundreds of steps waiting for its lanes, and a plain "oldest 50 waiting" would hold every chain started after
+ * it until its backlog drained. The steps this process is handing to a provider right now are still "queued":
+ * the limit makes room for them.
+ */
+const READY_DEPENDENTS = `SELECT g.* FROM generations g
+ WHERE g.status = 'queued' AND g.external_id IS NULL AND g.depends_on IS NOT NULL
+ AND (
+ NOT EXISTS (SELECT 1 FROM ${DEP_IDS} JOIN generations dep ON dep.id = d.value WHERE dep.status IN ('queued', 'running'))
+ OR EXISTS (SELECT 1 FROM ${DEP_IDS} LEFT JOIN generations dep ON dep.id = d.value WHERE dep.id IS NULL OR dep.status IN ('failed', 'canceled'))
+ )
+ ORDER BY g.created_at ASC LIMIT ?`;
+
+/** The error a waiting step gets when an input failed (framesProgress tells these from a step's own failure). */
+export const waitedOnFailure = (frame?: boolean) => `${frame ? "The previous frame" : "An earlier step"} didn't finish`;
+/** What a step dropped by dropUnused says (canceled, not by anyone: the steps it was for failed). */
+export const DROPPED_UNUSED = "Stopped before it ran: the steps it was for failed";
+
+/** Ids in a depends_on column that name `id` (one id, or a JSON list). */
+const DEPENDENTS_OF = "(depends_on = @id OR (substr(depends_on, 1, 1) = '[' AND instr(depends_on, @quoted) > 0))";
+
+/**
+ * A waiting step marked dropWhenUnused whose every dependent has failed or been canceled can no longer be
+ * used: cancel it (nothing was spent on it) and look again at the steps it waited for. `ids` are the inputs
+ * of a step that just failed. A step being handed to its provider right now is left alone.
+ */
+function dropUnused(ids: string[]): void {
+ const todo = [...ids];
+ // Settled: dropped, or not a waiting dropWhenUnused step. One still used is looked at again when a step using it is dropped.
+ const settled = new Set<string>();
+ const live = db().prepare(`SELECT 1 FROM generations WHERE status IN ('queued', 'running') AND ${DEPENDENTS_OF} LIMIT 1`);
+ while (todo.length) {
+ const id = todo.pop()!;
+ if (settled.has(id) || submitting().has(id)) continue;
+ const r = db().prepare("SELECT status, external_id, depends_on, request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id" | "depends_on" | "request_json"> | undefined;
+ if (!r || r.status !== "queued" || r.external_id || !r.depends_on || !(JSON.parse(r.request_json) as GenerationRequest).dropWhenUnused) {
+ settled.add(id);
+ continue;
+ }
+ if (live.get({ id, quoted: JSON.stringify(id) })) continue;
+ settled.add(id);
+ const now = Date.now();
+ db()
+ .prepare("UPDATE generations SET status = 'canceled', error = ?, message = NULL, completed_at = ?, updated_at = ? WHERE id = ? AND status = 'queued' AND external_id IS NULL")
+ .run(DROPPED_UNUSED, now, now, id);
+ todo.push(...depIds(r.depends_on));
+ }
+}
+
/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */
async function advanceDependents(): Promise<void> {
- const rows = db()
- .prepare("SELECT * FROM generations WHERE status = 'queued' AND external_id IS NULL AND depends_on IS NOT NULL ORDER BY created_at ASC LIMIT 50")
- .all() as Row[];
+ const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];
for (const r of rows) {
if (submitting().has(r.id)) continue;
const request = JSON.parse(r.request_json) as GenerationRequest;
@@ -686,19 +751,30 @@ async function advanceDependents(): Promise<void> {
const slots = slotsFor(request, ids.length);
const deps = ids.map((id) => db().prepare("SELECT status, provider, outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json"> | undefined);
const earlier = request.frame ? "The previous frame" : "An earlier step";
+ const fail = (error: string) => {
+ update(r.id, { status: "failed", error, message: null, completed_at: Date.now() });
+ // Steps waiting only to feed this one (the other lanes of a per-frame render) are dropped before they are paid for.
+ dropUnused(ids);
+ };
if (deps.some((d) => !d || d.status === "failed" || d.status === "canceled")) {
- update(r.id, { status: "failed", error: `${earlier} didn't finish`, message: null, completed_at: Date.now() });
+ fail(waitedOnFailure(!!request.frame));
continue;
}
if (deps.some((d) => d!.status !== "succeeded")) continue;
+ const outputs = deps.map((d) => JSON.parse(d!.outputs_json) as OutputFile[]);
+ const short = slots.map((s, i) => listShortfall(outputs[i], s)).find(Boolean);
+ if (short) {
+ fail(`${earlier} ${short}`);
+ continue;
+ }
submitting().add(r.id);
let handedOff = false;
try {
// The planned op (r.op), not request.op: a translate whose op was inferred still gets the cue list.
- const values = await Promise.all(deps.map((d, i) => chainValue(pickOutput(JSON.parse(d!.outputs_json) as OutputFile[], slots[i]), slots[i], r.op)));
+ const values = await Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op)));
const missing = values.findIndex((u) => !u);
if (missing >= 0) {
- update(r.id, { status: "failed", error: `${earlier} has no ${slotNoun(slots[missing])} to use`, message: null, completed_at: Date.now() });
+ fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);
continue;
}
// Routing reads cached reachability: make sure it's fresh for local engines.
@@ -723,7 +799,7 @@ async function advanceDependents(): Promise<void> {
handedOff = true;
void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);
} catch (e) {
- update(r.id, { status: "failed", error: (e as Error).message, message: null, completed_at: Date.now() });
+ fail((e as Error).message);
} finally {
if (!handedOff) submitting().delete(r.id);
}
@@ -1135,6 +1211,8 @@ export async function cancelGeneration(id: string): Promise<void> {
.catch(() => {});
}
update(id, { status: "canceled", completed_at: Date.now(), message: null });
+ // Steps waiting only to feed this one are dropped too (nothing was spent on them).
+ dropUnused(depIds(r.depends_on));
}
// ---------------------------------------------------------------------------
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index d1cff7c5..4d879795 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -315,8 +315,9 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", rigged: true } }];
case "ocr":
return [demoOcr(brief)];
+ // As many frames as were asked for (max_frames), 4 without a count.
case "extract-frames":
- return Array.from({ length: 4 }, (_, index) => ({ url: svgUri(demoSvg(`frame ${index + 1}`, ar, index)), kind: "image" as const, contentType: "image/svg+xml", meta: { index, demo: true } }));
+ return Array.from({ length: clamp(Math.round(Number(meta.frames ?? 4)), 1, 500) }, (_, index) => ({ url: svgUri(demoSvg(`frame ${index + 1}`, ar, index)), kind: "image" as const, contentType: "image/svg+xml", meta: { index, demo: true } }));
case "overlay":
return [{ url: svgUri(demoSvg(brief || "overlay", ar, 5)), kind: "image", contentType: "image/svg+xml", meta: { demo: true } }];
// The same tone, as long as the loop was asked to be (or the clips joined end to end).
@@ -391,6 +392,7 @@ export const mockProvider: ProviderAdapter = {
duration: input.duration,
format: input.format,
clips: input.audios?.length,
+ frames: route.op === "extract-frames" ? input.extra?.max_frames : undefined,
// Remove background: which file the demo stands for (the cut-out or its alpha mask).
matteOutput: route.op === "bg-remove-video" ? (input.matteOutput ?? model.options.matteOutputs?.[0] ?? "cutout") : undefined,
// The painted eraser's second output: the window's last tracked mask (video-inpaint-wan-vace-painted), saved
diff --git a/tests/chain-fanout.test.ts b/tests/chain-fanout.test.ts
index 9cfd83b1..851279ff 100644
--- a/tests/chain-fanout.test.ts
+++ b/tests/chain-fanout.test.ts
@@ -35,6 +35,21 @@ async function settle(id: string, ms = 80_000): Promise<Generation> {
const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+/** A step that stays "running" until the test lets go of it (no provider polls it; the runner's sweep is minutes away). */
+function held(): { id: string; fail: () => void } {
+ const id = `held${Math.random().toString(36).slice(2, 10)}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, provider_input_json, external_id, external_meta_json, outputs_json, error, cost_usd, favorite, created_at, updated_at, completed_at, depends_on)
+ VALUES (?, NULL, 't', NULL, 'nano-banana-2', 'cloud', 'mock', 't2i', 'image', 'running', NULL, 'Held for the test', NULL, ?, NULL, NULL, NULL, '[]', NULL, 0, 0, ?, ?, NULL, NULL)`,
+ )
+ .run(id, JSON.stringify({ feature: "t", modelId: "nano-banana-2", op: "t2i", prompt: "held" }), now, now);
+ return { id, fail: () => db().prepare("UPDATE generations SET status = 'failed', error = 'Let go', completed_at = ? WHERE id = ?").run(Date.now(), id) };
+}
+
+const row = (id: string) => db().prepare("SELECT status, error, external_id FROM generations WHERE id = ?").get(id) as { status: string; error: string | null; external_id: string | null };
+
describe("pickOutput with an index", () => {
const frames: OutputFile[] = [
{ url: "/api/files/f2.png", kind: "image", meta: { index: 2 } },
@@ -50,6 +65,15 @@ describe("pickOutput with an index", () => {
expect(gens.pickOutput(frames, { slot: "video", index: 0 })?.url).toBe("/api/files/clip.mp4");
});
+ it("says when a planned list came back too short to read (more than a frame or two missing)", () => {
+ const four = frames.filter((f) => f.kind === "image");
+ expect(gens.listShortfall(four, { slot: "images", index: 2, of: 5 })).toBeNull();
+ expect(gens.listShortfall(four, { slot: "images", index: 0, of: 6 })).toBe("made 3 images where 6 were planned");
+ // Without a planned count (or an index) nothing is checked.
+ expect(gens.listShortfall(four, { slot: "images", index: 40 })).toBeNull();
+ expect(gens.listShortfall([], { slot: "images", of: 9 })).toBeNull();
+ });
+
it("goes by position when the outputs carry no index, and holds the last one past the end", () => {
const plain: OutputFile[] = [
{ url: "/a.png", kind: "image" },
@@ -110,6 +134,91 @@ describe("fan-out and fan-in in createPipeline", () => {
expect(film.request.inputs?.images).toEqual(styled.map((g) => g.outputs[0].url));
});
+ it("refuses a planned count that doesn't fit its output number", () => {
+ for (const slot of [{ slot: "images" as const, index: 3, of: 3 }, { slot: "images" as const, of: 4 }]) {
+ expect(() =>
+ createPipeline([
+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames", inputs: { video: "/api/files/a.mp4" } } },
+ { key: "f3", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "ink" }, after: "frames", chain: [slot] },
+ ]),
+ ).toThrow(/Step “f3”: a list of \d+ has no output number/);
+ }
+ });
+
+ it("fails the steps reading a list far shorter than planned before they are paid for; a frame short is held", async () => {
+ // The demo extractor returns 4 frames when no count is asked for.
+ const p = createPipeline([
+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames", inputs: { video: clip() }, params: { frameInterval: 3 } } },
+ { key: "far", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, after: "frames", chain: [{ slot: "images", index: 0, of: 10 }] },
+ { key: "near", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, after: "frames", chain: [{ slot: "images", index: 4, of: 5 }] },
+ ]);
+ const far = await settle(p.byKey.far.id);
+ expect(far).toMatchObject({ status: "failed", error: "An earlier step made 4 images where 10 were planned" });
+ expect(row(far.id).external_id).toBeNull();
+ const near = await settle(p.byKey.near.id);
+ expect(near.status, near.error ?? "").toBe("succeeded");
+ expect(near.request.inputs?.images).toEqual([gens.getGeneration(p.byKey.frames.id)!.outputs[3].url]);
+ });
+
+ it("drops the waiting steps that only fed a failed one, before they are paid for", async () => {
+ // The extraction waits on a held step, so no frame can start; then a frame of the second lane fails on its own.
+ const hold = held();
+ // Lanes of 3 as the per-frame render makes them: a lane's first frame matches frame 0, the others the frame before.
+ const lane = (i: number) => (i % 3 ? [`f${i - 1}`] : i ? ["f0"] : []);
+ const p = createPipeline(
+ [
+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames", params: { frameInterval: 3, extra: { max_frames: 6 } } }, after: "hold", chain: [{ slot: "video" }] },
+ ...Array.from({ length: 6 }, (_, i) => ({
+ key: `f${i}`,
+ request: { feature: "t", modelId: "nano-banana-2", op: "edit" as const, prompt: "Ink", dropWhenUnused: true },
+ after: ["frames", ...lane(i)],
+ chain: [{ slot: "images" as const, index: i, of: 6, position: "first" as const }, ...lane(i).map(() => ({ slot: "images" as const }))],
+ })),
+ { key: "film", request: { feature: "t", modelId: "images-to-video", op: "images-to-video", params: { fps: 8 } }, after: Array.from({ length: 6 }, (_, i) => `f${i}`), chain: Array.from({ length: 6 }, () => ({ slot: "images" as const })) },
+ ],
+ { existing: { hold: hold.id } },
+ );
+ expect(p.items).toHaveLength(8);
+ expect(row(p.byKey.frames.id).status).toBe("queued");
+ db().prepare("UPDATE generations SET status = 'failed', error = 'Refused by the safety filter', completed_at = ? WHERE id = ?").run(Date.now(), p.byKey.f3.id);
+ // The film fails at once (not after the other frames), and takes the frames that only fed it along — frame 0
+ // too, once the frames that matched it are dropped.
+ const film = await settle(p.byKey.film.id, 20_000);
+ expect(film).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });
+ await settle(p.byKey.f4.id, 20_000);
+ expect(row(p.byKey.f4.id)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });
+ for (const k of ["f0", "f1", "f2", "f5"]) expect(row(p.byKey[k].id), k).toEqual({ status: "canceled", error: gens.DROPPED_UNUSED, external_id: null });
+ // A step not marked dropWhenUnused waits on (the extraction has no failed dependent of its own anyway).
+ expect(row(p.byKey.frames.id).status).toBe("queued");
+ hold.fail();
+ expect((await settle(p.byKey.frames.id, 20_000)).status).toBe("failed");
+ });
+
+ it("launches a newer chain while more than 50 older steps wait", async () => {
+ const hold = held();
+ const waiting = Array.from({ length: 60 }, () => gens.createGenerations({ feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, { dependsOn: hold.id })[0]);
+ const p = createPipeline([
+ { key: "a", request: { feature: "t", modelId: "nano-banana-2", op: "t2i", prompt: "A red chair" } },
+ { key: "b", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, after: "a" },
+ ]);
+ const b = await settle(p.byKey.b.id, 40_000);
+ expect(b.status, b.error ?? "").toBe("succeeded");
+ expect(waiting.every((w) => row(w.id).status === "queued")).toBe(true);
+ // When the held step fails, every step waiting on it fails (the oldest 50 first, the rest a tick later).
+ hold.fail();
+ for (const w of waiting) expect(await settle(w.id, 20_000)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });
+ });
+
+ it("chains a pipeline's steps onto generations made before (a retry's kept steps)", () => {
+ const hold = held();
+ expect(() => createPipeline([{ key: "x", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, after: "nope" }], { existing: { hold: hold.id } })).toThrow(/waits for “nope”, which isn't in the pipeline/);
+ expect(() => createPipeline([{ key: "hold", request: { feature: "t", modelId: "nano-banana-2", op: "t2i", prompt: "Ink" } }], { existing: { hold: hold.id } })).toThrow(/Two steps are called “hold”/);
+ const p = createPipeline([{ key: "x", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Ink" }, after: "hold" }], { existing: { hold: hold.id } });
+ expect(p.items).toHaveLength(1);
+ expect(db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(p.byKey.x.id)).toEqual({ depends_on: hold.id });
+ hold.fail();
+ });
+
it("takes the filled inputs out again for a retry, keeping the step's own", () => {
const filled: GenerationRequest = {
feature: "t",