Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address storyboard scenes by durable id, and cancel orphaned jobs on write reject (#3413)

[._.]/ Adam Eivy3432c6bb9095
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f6b2b8ddc7..f30cd8b0ff 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,7 @@
- **[issue-3396] CyberCity's ambient music no longer drifts under main-thread load.** The chord changes (every 2400ms) and the 16th-note arp plucks (every 150ms) rode two independent `setInterval`s that each read `ctx.currentTime` at fire time — so under load both drifted against the audio clock *and* against each other, the failure mode the sibling synth players adopted the shared lookahead scheduler to avoid. Both now come off one 16th-note step counter (16 steps per chord, so the arp is phase-locked to the chord changes by construction) and every event is written to the audio clock at an absolute grid time, `gridOrigin + step × 0.15s`, which cannot accumulate drift. The timing constants come from `SYNTH_TIMING` in `lib/lookaheadTransport.js` so the feel stays shared; the transport body itself is deliberately not reused, because it reads its clock from the shared `lib/audioContext.js` singleton while `cityAudioEngine` is a documented holdout that owns (and closes) its own `AudioContext` — scheduling this graph against a clock it doesn't run on would be worse than the drift. A backgrounded tab now re-anchors to the grid on return instead of dumping every missed step into one burst. Generative behavior (chord walk, mood sets, energy-driven arp gain) and the stop-ramp contract are unchanged.
- **A manually-triggered ("Run Now") perpetual claim drain no longer stalls after one item.** A `claim-issue` / `claim-work` schedule set to *perpetual* is meant to drain actionable work back-to-back. When the daemon's own scheduler drives it that works, but a manual "Run Now" (`RunTaskButton` → `POST /api/cos/schedule/trigger`) did not: the on-demand trigger only gates on the master Improve flag, so the first item ran, but `refillPerpetualForCompletedAgent` then gated the *continuation* on `canQueueImprovementTasks` — which additionally requires idle-review ON **and** CoS auto-run = `execute`. Those are exactly the postures in which a user reaches for "Run Now" (auto-run off/dry-run, or idle-review off), so the drain refused to spin up the next item even with a queue of claimable issues. The refill now routes a manual drain through `perpetualRefillPlan`'s `onDemand` lane: it re-issues an on-demand request for the same task type + app, gated only on the master Improve flag (matching what let the manual run START), and returns before the auto-run-gated queue lane — so a manual perpetual drain keeps draining, scoped to that one type+app (it can't leak unrelated rotation/idle autonomous work past the auto-run kill switch), until the work-detector parks. The on-demand spawn engines mark generated tasks `metadata.onDemand` (projected onto the agent as `taskOnDemand`) and forward the completion's `ignoreTaskId` to `addTask`, so the re-issued claim isn't rejected as a duplicate of the still-`in_progress` run that just triggered it. Scheduled perpetual drains are unchanged.
- **[issue-3400] Rendering two storyboard scenes at once no longer loses one of the jobs.** `enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`, and `refineStoryboardScenePrompt` each read `stages.storyboards.scenes` up front, then wrote the whole pre-read array back through `updateStage`. That write *is* serialized, but the array it shallow-merges was built outside the lock — so two enqueues for different scenes that both read before either wrote would revert each other's freshly-stamped `sceneVideoJobId` / `startFrameJobId`, and the losing render would run to completion with nothing left pointing at it. All three now patch a single scene through `updateStageWithLatest`, so the read-modify-write of `scenes` happens inside the write region and only the targeted index is replaced. A scene that disappeared between the caller's read and the write now 404s instead of resurrecting itself.
+- **[issue-3413] A storyboard scene is now addressed by a durable id, and a rejected render write no longer orphans its job.** #3400 stopped two concurrent enqueues from clobbering each other, but scenes were still addressed purely by array index end to end — the route took `sceneIndex`, the media-job owner encoded `scene<idx>`, and the write patched `scenes[index]` — so a reorder or delete landing between a caller's read and its write silently retargeted the job id onto whatever scene now sat in that slot (only the out-of-range case 404'd), and the completion hook routed the finished render by the same stale index, making the mis-targeting consistent rather than self-correcting. Scenes (and shots) now carry a durable `id` stamped by `sanitizeVisualStage` and backfilled on existing installs by migration 222 (file store) + db-migration 007 (Postgres); the ids are deterministic (`scene-01`, collision-escaped) so concurrent readers and federated peers derive identical values. Every write region re-resolves the captured id against the fresh array and returns 409 `PIPELINE_SCENE_STALE_TARGET` / `PIPELINE_SHOT_STALE_TARGET` when the target is gone, distinct from the 404 for an index that never existed, with the index kept only as the fallback for pre-migration records. Media-job owners carry the ids too (percent-encoded), and the filename hook still attaches jobs queued under the legacy index-only owner. Separately, all three render surfaces — storyboard scene/shot, comic page slot, and issue/volume covers — now cancel the job they just enqueued when the stage write rejects, instead of leaving it queued with nothing referencing it.
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
- **`completeAgent` is now idempotent, so the caller-level guard is no longer the only line of defense.** Six call sites funnel every terminal agent write through `completeAgent`, and each carried the same latent "I might be second" assumption. A duplicate call re-recorded `result` (success verdict, exit code, error analysis) and re-ran the completed-agent directory move; the guards that caught the TUI double-finalize above read the record *outside* the state lock, so they narrowed the race rather than closing it. `completeAgent` now returns an already-`completed` record unmutated from inside the lock it already holds — and skips the budget-ledger charge and the second `agent:completed` emit that would otherwise re-run the scheduler hand-off. `paused` records are still completable, so a resumed agent can't wedge. The one thing a duplicate *does* still do is finish a half-written archive: `archiveCompletedAgent` is now idempotent (the directory move is skipped once the date bucket exists, the index write always re-runs because `saveAgentIndex` swallows its own errors), and the cross-filesystem copy fallback rolls back a partially-copied target instead of leaving a directory that every later attempt mistakes for a finished archive.
diff --git a/scripts/migrations/222-storyboard-scene-durable-ids.js b/scripts/migrations/222-storyboard-scene-durable-ids.js
new file mode 100644
index 0000000000..d45d1c593c
--- /dev/null
+++ b/scripts/migrations/222-storyboard-scene-durable-ids.js
@@ -0,0 +1,101 @@
+/**
+ * Backfill durable ids on `stages.storyboards.scenes[]` for FILE-BACKED
+ * pipeline issues (#3413).
+ *
+ * Storyboard scenes were addressed purely by array index end to end, so a
+ * reorder or delete landing between a render's read and its write retargeted
+ * the job id onto a different scene. `sanitizeVisualStage` now stamps a
+ * durable `id` on every scene (and shot); this migration stamps the records
+ * already on disk so id resolution is live immediately.
+ *
+ * Two stores, two migrations — this is the FILE half:
+ * - `data/pipeline-issues/{id}/index.json` — the pre-#1015 file store, still
+ * the live store under `MEMORY_BACKEND=file` / `NODE_ENV=test`, and still
+ * the source the one-time `migrateIssuesToDB` import reads on installs that
+ * have not yet moved to Postgres. Stamping here first means the import
+ * carries the ids across.
+ * - `pipeline_issues` rows in Postgres — handled by the boot-time DB
+ * migration `server/scripts/db-migrations/007-storyboard-scene-durable-ids.js`
+ * (this file runner executes BEFORE the DB pool exists, so a row transform
+ * cannot live here).
+ *
+ * Ids are deterministic (`scene-01`, `shot-02`, collision-escaped with `-2`)
+ * and produced by the SAME `ensureStoryboardIds` the sanitizer uses, so every
+ * federated peer stamps a shared issue identically instead of churning
+ * conflicts. `updatedAt` is deliberately NOT bumped — a derived normalization
+ * must not advance the LWW clock and out-race real remote edits.
+ *
+ * Idempotent: a scene that already carries an `id` is untouched, so a re-run
+ * writes nothing.
+ */
+
+import { readFile, writeFile, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { ensureStoryboardIds } from '../../server/lib/storyboardScenes.js';
+
+const readJsonOrNull = async (path) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+};
+
+// Stamp one issue record in place. Returns true when the record changed.
+const stampIssue = (issue) => {
+ const scenes = issue?.stages?.storyboards?.scenes;
+ if (!Array.isArray(scenes) || scenes.length === 0) return false;
+ const stamped = ensureStoryboardIds(scenes);
+ if (stamped === scenes) return false;
+ issue.stages.storyboards.scenes = stamped;
+ return true;
+};
+
+const listIssueDirs = async (typeDir) => {
+ const entries = await readdir(typeDir).catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (entries == null) return [];
+ const dirs = [];
+ for (const name of entries) {
+ if (name === 'index.json') continue;
+ const full = join(typeDir, name);
+ const st = await stat(full).catch(() => null);
+ if (st?.isDirectory()) dirs.push(full);
+ }
+ return dirs;
+};
+
+export default {
+ async up({ rootDir }) {
+ const typeDir = join(rootDir, 'data', 'pipeline-issues');
+ const dirs = await listIssueDirs(typeDir);
+ if (dirs.length === 0) {
+ console.log('🎬 storyboard scene ids: no file-backed pipeline issues — nothing to do (Postgres rows are handled by db-migration 007)');
+ return;
+ }
+
+ let touched = 0;
+ for (const dir of dirs) {
+ const recordPath = join(dir, 'index.json');
+ const issue = await readJsonOrNull(recordPath);
+ if (!issue) continue;
+ if (stampIssue(issue)) {
+ await writeFile(recordPath, `${JSON.stringify(issue, null, 2)}\n`);
+ touched += 1;
+ }
+ }
+
+ if (touched > 0) {
+ console.log(`🎬 storyboard scene ids: stamped scene/shot ids on ${touched} issue${touched === 1 ? '' : 's'}`);
+ } else {
+ console.log('✅ storyboard scene ids: every file-backed issue already carries scene ids — nothing to do');
+ }
+ },
+};
diff --git a/scripts/migrations/222-storyboard-scene-durable-ids.test.js b/scripts/migrations/222-storyboard-scene-durable-ids.test.js
new file mode 100644
index 0000000000..5ef1e84995
--- /dev/null
+++ b/scripts/migrations/222-storyboard-scene-durable-ids.test.js
@@ -0,0 +1,82 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './222-storyboard-scene-durable-ids.js';
+
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 222 — storyboard scene durable ids', () => {
+ let rootDir;
+ let typeDir;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-222-'));
+ typeDir = join(rootDir, 'data', 'pipeline-issues');
+ mkdirSync(typeDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ const writeIssue = (id, issue) => {
+ const dir = join(typeDir, id);
+ mkdirSync(dir, { recursive: true });
+ writeJson(join(dir, 'index.json'), issue);
+ };
+ const readIssue = (id) => readJson(join(typeDir, id, 'index.json'));
+
+ it('backfills scene + shot ids on an existing install', async () => {
+ writeIssue('iss-a', {
+ id: 'iss-a',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ stages: {
+ storyboards: {
+ scenes: [
+ { description: 'one', shots: [{ description: 'wide' }] },
+ { description: 'two' },
+ ],
+ },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ const a = readIssue('iss-a');
+ expect(a.stages.storyboards.scenes.map((s) => s.id)).toEqual(['scene-01', 'scene-02']);
+ expect(a.stages.storyboards.scenes[0].shots[0].id).toBe('shot-01');
+ // Derived normalization — the LWW clock must not advance.
+ expect(a.updatedAt).toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('is idempotent and leaves already-stamped records byte-identical', async () => {
+ writeIssue('iss-b', {
+ id: 'iss-b',
+ stages: { storyboards: { scenes: [{ id: 'custom', description: 'kept' }] } },
+ });
+ const before = readFileSync(join(typeDir, 'iss-b', 'index.json'), 'utf-8');
+
+ await migration.up({ rootDir });
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(typeDir, 'iss-b', 'index.json'), 'utf-8')).toBe(before);
+ });
+
+ it('skips issues with no storyboard scenes and tolerates unreadable records', async () => {
+ writeIssue('iss-c', { id: 'iss-c', stages: { storyboards: { scenes: [] } } });
+ writeIssue('iss-d', { id: 'iss-d', stages: {} });
+ mkdirSync(join(typeDir, 'iss-e'), { recursive: true });
+ writeFileSync(join(typeDir, 'iss-e', 'index.json'), '{ not json');
+
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ expect(readIssue('iss-c').stages.storyboards.scenes).toEqual([]);
+ });
+
+ it('no-ops on a fresh install with no pipeline-issues dir', async () => {
+ rmSync(typeDir, { recursive: true, force: true });
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 76aa1cf25e..98a1e2858c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -71,6 +71,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |
| `proseExportSettings.js` | Per-series prose-export settings (#2181): `sanitizeProseExportSettings` + `resolveExportSettings` + `TRIM_SIZES`/`INTERIOR_FONTS` for the manuscript/ePub/PDF exports. |
| `shotGrammar.js` | Pure shot-grammar vocabularies (`SHOT_TYPES`, `SCREEN_DIRECTIONS`) + normalizers (`normalizeShotType`, `normalizeScreenDirection`) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the `visual.shot-continuity` editorial check (#1315). |
+| `storyboardScenes.js` | Durable ids + id-first addressing for `stages.storyboards.scenes[]` (#3413). `ensureStoryboardIds(scenes)` stamps a deterministic `scene-NN` / `shot-NN` id on any entry lacking one (collision-escaped with a `-2` suffix, so peers and concurrent readers derive identical ids); `resolveStoryboardTarget(list, { id, index })` → `{ index, record, matchedBy, stale }` resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting `stale: true` (409, never an index retarget) when a captured id is gone. |
| `seasonStructure.js` | Season/episode structure recommendation. |
| `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. |
| `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 5412bfb2b1..6cd2a6e116 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -63,6 +63,7 @@ export * from './sceneExtractor.js';
export * from './scenePrompt.js';
export * from './proseExportSettings.js';
export * from './shotGrammar.js';
+export * from './storyboardScenes.js';
export * from './seasonStructure.js';
export * from './seriesCharacterArc.js';
export * from './seriesLlmOverride.js';
diff --git a/server/lib/storyboardScenes.js b/server/lib/storyboardScenes.js
new file mode 100644
index 0000000000..b7affc60ed
--- /dev/null
+++ b/server/lib/storyboardScenes.js
@@ -0,0 +1,123 @@
+/**
+ * Storyboard scene/shot durable ids + id-first target resolution (#3413).
+ *
+ * Storyboard scenes used to be addressed purely by ARRAY INDEX end to end —
+ * the route took `sceneIndex`, the media-job owner encoded `scene<idx>`, and
+ * the stage write patched `scenes[index]`. A reorder or delete landing between
+ * a caller's read and its (serialized) write therefore retargeted the write
+ * onto whatever scene now occupied that slot, and the completion hook routed
+ * the finished render by the same stale index, so the mis-targeting was
+ * consistent rather than self-correcting.
+ *
+ * Both halves of the fix live here:
+ *
+ * - `ensureStoryboardIds` stamps a durable `id` on any scene (and shot) that
+ * lacks one. It is called from `sanitizeVisualStage`'s storyboards branch,
+ * so every persisted record grows ids on its next write, and from the
+ * backfill migrations for records already on disk / in Postgres.
+ * - `resolveStoryboardTarget` resolves a captured id against a FRESH array,
+ * falling back to the index only for pre-migration records that carry no
+ * id at all.
+ *
+ * Ids are DETERMINISTIC (`scene-01`, `shot-02`, …) rather than random on
+ * purpose:
+ * - Two concurrent readers of the same un-migrated record must derive the
+ * same id, otherwise their writes would disagree about what they targeted.
+ * - Federated peers each run the backfill over their own copy of a shared
+ * record; a random id would make every peer stamp something different and
+ * churn conflicts forever. Deterministic ids converge.
+ *
+ * A deterministic base that is already taken gets a `-2`, `-3`, … suffix, so
+ * an array that already holds `scene-01` never gets a duplicate stamped onto
+ * it (duplicate ids would make id resolution ambiguous).
+ */
+
+const ID_MAX = 80;
+
+const isNonEmptyStr = (v) => typeof v === 'string' && v.trim().length > 0;
+
+export const sceneIdForIndex = (index) => `scene-${String(index + 1).padStart(2, '0')}`;
+export const shotIdForIndex = (index) => `shot-${String(index + 1).padStart(2, '0')}`;
+
+// Deterministic collision escape: `scene-03` → `scene-03-2` → `scene-03-3`.
+const uniqueId = (base, taken) => {
+ if (!taken.has(base)) return base;
+ let n = 2;
+ while (taken.has(`${base}-${n}`)) n += 1;
+ return `${base}-${n}`;
+};
+
+// Stamp `id` on every entry that lacks one. Returns the ORIGINAL array
+// reference when nothing changed so callers can cheaply detect a no-op.
+const stampIds = (list, idFor) => {
+ if (!Array.isArray(list) || list.length === 0) return list;
+ const taken = new Set(
+ list.filter((r) => r && typeof r === 'object' && isNonEmptyStr(r.id)).map((r) => r.id),
+ );
+ let changed = false;
+ const out = list.map((rec, i) => {
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return rec;
+ if (isNonEmptyStr(rec.id)) return rec;
+ const id = uniqueId(idFor(i).slice(0, ID_MAX), taken);
+ taken.add(id);
+ changed = true;
+ return { ...rec, id };
+ });
+ return changed ? out : list;
+};
+
+/**
+ * Stamp durable ids onto a storyboard `scenes[]` array (and each scene's
+ * `shots[]`). Pure: returns a new array only when something was stamped,
+ * otherwise the input reference. Non-object entries pass through untouched —
+ * the sanitizer above this is the one that decides what a scene may be.
+ */
+export function ensureStoryboardIds(scenes) {
+ if (!Array.isArray(scenes) || scenes.length === 0) return scenes;
+ let shotsChanged = false;
+ const withShotIds = scenes.map((scene) => {
+ if (!scene || typeof scene !== 'object' || !Array.isArray(scene.shots)) return scene;
+ const shots = stampIds(scene.shots, shotIdForIndex);
+ if (shots === scene.shots) return scene;
+ shotsChanged = true;
+ return { ...scene, shots };
+ });
+ const stamped = stampIds(withShotIds, sceneIdForIndex);
+ if (stamped !== withShotIds) return stamped;
+ return shotsChanged ? withShotIds : scenes;
+}
+
+/**
+ * Resolve a render target (a scene inside `scenes[]`, or a shot inside
+ * `scene.shots[]`) against the FRESHEST array, given the id + index captured
+ * when the caller read the record.
+ *
+ * Returns `{ index, record, matchedBy, stale }`:
+ * - `matchedBy: 'id'` — the captured id is still present (authoritative,
+ * survives a reorder). When the id appears more than once (a duplicated
+ * record), the captured index wins the tiebreak, else the first match.
+ * - `matchedBy: 'index'` — no id was captured (pre-migration record), so the
+ * index is the only addressing available.
+ * - `matchedBy: null, stale: true` — an id WAS captured and is gone: the
+ * target was removed between read and write. Callers surface this as a 409
+ * (distinct from a never-existed index, which is a 404) and must NOT fall
+ * back to the index, since that is exactly the mis-target this prevents.
+ * - `matchedBy: null, stale: false` — no id, and the index is out of range.
+ */
+export function resolveStoryboardTarget(list, { id = null, index = null } = {}) {
+ const arr = Array.isArray(list) ? list : [];
+ // `Number(null)` / `Number('')` are 0 — an absent index must NOT read as
+ // "index 0" (CLAUDE.md sentinel discipline), so coerce only real numerics.
+ const idx = index === null || index === undefined || index === '' ? NaN : Number(index);
+ const hasIndex = Number.isInteger(idx) && idx >= 0;
+ if (isNonEmptyStr(id)) {
+ if (hasIndex && arr[idx] && arr[idx].id === id) {
+ return { index: idx, record: arr[idx], matchedBy: 'id', stale: false };
+ }
+ const found = arr.findIndex((r) => r && r.id === id);
+ if (found >= 0) return { index: found, record: arr[found], matchedBy: 'id', stale: false };
+ return { index: -1, record: null, matchedBy: null, stale: true };
+ }
+ if (hasIndex && arr[idx]) return { index: idx, record: arr[idx], matchedBy: 'index', stale: false };
+ return { index: -1, record: null, matchedBy: null, stale: false };
+}
diff --git a/server/lib/storyboardScenes.test.js b/server/lib/storyboardScenes.test.js
new file mode 100644
index 0000000000..6cc9a28b41
--- /dev/null
+++ b/server/lib/storyboardScenes.test.js
@@ -0,0 +1,83 @@
+import { describe, it, expect } from 'vitest';
+import { ensureStoryboardIds, resolveStoryboardTarget, sceneIdForIndex, shotIdForIndex } from './storyboardScenes.js';
+
+describe('ensureStoryboardIds', () => {
+ it('stamps deterministic ids on scenes that lack one', () => {
+ const scenes = [{ description: 'a' }, { description: 'b' }];
+ const out = ensureStoryboardIds(scenes);
+ expect(out.map((s) => s.id)).toEqual(['scene-01', 'scene-02']);
+ // Two independent readers of the same un-migrated record must agree.
+ expect(ensureStoryboardIds(structuredClone(scenes)).map((s) => s.id)).toEqual(out.map((s) => s.id));
+ });
+
+ it('stamps shot ids inside each scene', () => {
+ const out = ensureStoryboardIds([{ description: 'a', shots: [{ description: 's1' }, { id: 'kept', description: 's2' }] }]);
+ expect(out[0].shots.map((s) => s.id)).toEqual(['shot-01', 'kept']);
+ });
+
+ it('leaves existing ids alone and returns the SAME array reference when nothing changed', () => {
+ const scenes = [{ id: 'custom-a', description: 'a' }, { id: 'custom-b', description: 'b', shots: [{ id: 'shot-01' }] }];
+ expect(ensureStoryboardIds(scenes)).toBe(scenes);
+ });
+
+ it('escapes a collision instead of stamping a duplicate id', () => {
+ // The scene at index 0 has no id, but `scene-01` is already taken by a
+ // later scene — a duplicate would make id resolution ambiguous.
+ const out = ensureStoryboardIds([{ description: 'a' }, { id: 'scene-01', description: 'b' }]);
+ expect(out[0].id).toBe('scene-01-2');
+ expect(out[1].id).toBe('scene-01');
+ });
+
+ it('passes non-array / empty input straight through', () => {
+ expect(ensureStoryboardIds(null)).toBe(null);
+ expect(ensureStoryboardIds(undefined)).toBe(undefined);
+ const empty = [];
+ expect(ensureStoryboardIds(empty)).toBe(empty);
+ });
+
+ it('leaves non-object entries untouched', () => {
+ const scenes = ['nope', null, { description: 'real' }];
+ const out = ensureStoryboardIds(scenes);
+ expect(out[0]).toBe('nope');
+ expect(out[1]).toBe(null);
+ expect(out[2].id).toBe('scene-03');
+ });
+
+ it('exposes the id formats it stamps', () => {
+ expect(sceneIdForIndex(0)).toBe('scene-01');
+ expect(shotIdForIndex(11)).toBe('shot-12');
+ });
+});
+
+describe('resolveStoryboardTarget', () => {
+ const list = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
+
+ it('resolves by id after a reorder, ignoring the stale index', () => {
+ const hit = resolveStoryboardTarget([{ id: 'c' }, { id: 'a' }], { id: 'a', index: 0 });
+ expect(hit).toMatchObject({ index: 1, matchedBy: 'id', stale: false });
+ });
+
+ it('prefers the captured index when a duplicated id matches twice', () => {
+ const dup = [{ id: 'a', tag: 'first' }, { id: 'a', tag: 'second' }];
+ expect(resolveStoryboardTarget(dup, { id: 'a', index: 1 }).record.tag).toBe('second');
+ // …and falls back to the first match when the index does not carry the id.
+ expect(resolveStoryboardTarget(dup, { id: 'a', index: 5 }).record.tag).toBe('first');
+ });
+
+ it('reports stale (never an index retarget) when a captured id is gone', () => {
+ const hit = resolveStoryboardTarget(list, { id: 'gone', index: 1 });
+ expect(hit).toMatchObject({ index: -1, record: null, matchedBy: null, stale: true });
+ });
+
+ it('falls back to the index only when no id was captured', () => {
+ expect(resolveStoryboardTarget(list, { index: 2 })).toMatchObject({ index: 2, matchedBy: 'index' });
+ expect(resolveStoryboardTarget(list, { id: ' ', index: 2 })).toMatchObject({ index: 2, matchedBy: 'index' });
+ expect(resolveStoryboardTarget(list, { index: 9 })).toMatchObject({ index: -1, matchedBy: null, stale: false });
+ });
+
+ it('tolerates a non-array list and a non-integer index', () => {
+ expect(resolveStoryboardTarget(null, { index: 0 }).record).toBe(null);
+ expect(resolveStoryboardTarget(list, { index: 'nope' }).record).toBe(null);
+ expect(resolveStoryboardTarget(list, {}).record).toBe(null);
+ });
+});
diff --git a/server/scripts/db-migrations/007-storyboard-scene-durable-ids.js b/server/scripts/db-migrations/007-storyboard-scene-durable-ids.js
new file mode 100644
index 0000000000..709fa75b23
--- /dev/null
+++ b/server/scripts/db-migrations/007-storyboard-scene-durable-ids.js
@@ -0,0 +1,51 @@
+/**
+ * Backfill durable ids on `stages.storyboards.scenes[]` (and each scene's
+ * `shots[]`) for pipeline issues already in Postgres (#3413).
+ *
+ * Storyboard scenes were addressed purely by array index — the render enqueue,
+ * the stage write, and the completion hook all agreed on `scenes[i]`, so a
+ * reorder or delete between a caller's read and its write silently retargeted
+ * the render onto whatever scene occupied that slot. `sanitizeVisualStage` now
+ * stamps a durable `id` on write, and every write path resolves BY id; this
+ * migration stamps the records that are already stored so id resolution is
+ * live immediately instead of only after each issue's next save.
+ *
+ * The stamp comes from the SAME `ensureStoryboardIds` the sanitizer uses, and
+ * it is deterministic (`scene-01`, `shot-02`, collision-escaped with `-2`).
+ * That matters for federation: every peer runs this over its own copy of a
+ * shared issue, and a random id would make each peer stamp something different
+ * and churn conflicts forever. Deterministic ids converge.
+ *
+ * `updated_at` is deliberately NOT bumped — this is a derived normalization,
+ * not a user edit, and advancing the LWW clock would make every issue look
+ * freshly edited to peers and out-race real remote edits.
+ *
+ * Idempotent: a scene that already carries an `id` is left untouched, so a
+ * re-run writes nothing. Tombstoned issues are included — they can be restored,
+ * and a restored issue should not be the one record still addressed by index.
+ */
+
+import { ensureStoryboardIds } from '../../lib/storyboardScenes.js';
+
+export async function up(client) {
+ const { rows } = await client.query(
+ `SELECT id, data FROM pipeline_issues
+ WHERE jsonb_typeof(data->'stages'->'storyboards'->'scenes') = 'array'
+ AND jsonb_array_length(data->'stages'->'storyboards'->'scenes') > 0`,
+ );
+ let touched = 0;
+ for (const row of rows) {
+ const scenes = row.data?.stages?.storyboards?.scenes;
+ if (!Array.isArray(scenes)) continue;
+ const stamped = ensureStoryboardIds(scenes);
+ if (stamped === scenes) continue;
+ await client.query(
+ `UPDATE pipeline_issues
+ SET data = jsonb_set(data, '{stages,storyboards,scenes}', $1::jsonb, false)
+ WHERE id = $2`,
+ [JSON.stringify(stamped), row.id],
+ );
+ touched += 1;
+ }
+ console.log(`🎬 storyboard scene ids: stamped ${touched} of ${rows.length} issue${rows.length === 1 ? '' : 's'} with storyboard scenes`);
+}
diff --git a/server/scripts/db-migrations/007-storyboard-scene-durable-ids.test.js b/server/scripts/db-migrations/007-storyboard-scene-durable-ids.test.js
new file mode 100644
index 0000000000..ed986237f9
--- /dev/null
+++ b/server/scripts/db-migrations/007-storyboard-scene-durable-ids.test.js
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi } from 'vitest';
+import { up } from './007-storyboard-scene-durable-ids.js';
+
+const makeClient = (rows) => {
+ const updates = [];
+ const query = vi.fn(async (sql, params) => {
+ if (sql.startsWith('SELECT')) return { rows };
+ updates.push({ sql, params });
+ return { rows: [] };
+ });
+ return { client: { query }, updates, query };
+};
+
+describe('db-migration 007 — storyboard scene durable ids', () => {
+ it('stamps scene + shot ids and writes only the scenes path', async () => {
+ const { client, updates } = makeClient([
+ {
+ id: 'iss-a',
+ data: { stages: { storyboards: { scenes: [{ description: 'one', shots: [{ description: 'wide' }] }] } } },
+ },
+ ]);
+
+ await up(client);
+
+ expect(updates).toHaveLength(1);
+ expect(updates[0].sql).toContain("jsonb_set(data, '{stages,storyboards,scenes}'");
+ // Never bumps updated_at — a derived normalization must not advance the LWW clock.
+ expect(updates[0].sql).not.toContain('updated_at');
+ const stamped = JSON.parse(updates[0].params[0]);
+ expect(stamped[0].id).toBe('scene-01');
+ expect(stamped[0].shots[0].id).toBe('shot-01');
+ expect(updates[0].params[1]).toBe('iss-a');
+ });
+
+ it('writes nothing for rows whose scenes already carry ids (idempotent re-run)', async () => {
+ const { client, updates } = makeClient([
+ { id: 'iss-b', data: { stages: { storyboards: { scenes: [{ id: 'scene-01', description: 'one' }] } } } },
+ ]);
+
+ await up(client);
+
+ expect(updates).toEqual([]);
+ });
+
+ it('skips a row whose scenes are not an array', async () => {
+ const { client, updates } = makeClient([
+ { id: 'iss-c', data: { stages: { storyboards: { scenes: null } } } },
+ { id: 'iss-d', data: {} },
+ ]);
+
+ await up(client);
+
+ expect(updates).toEqual([]);
+ });
+});
diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.js
index 7bc87290d2..10ef508934 100644
--- a/server/services/pipeline/comicPages.js
+++ b/server/services/pipeline/comicPages.js
@@ -25,6 +25,7 @@ import {
REFINE_RENDER_DEFAULT_STRENGTH, applyCharacterLorasToRender, loraRenderOptions,
enqueueImageJob, buildRenderSlot, composeVisualPrompt, seriesBibleCtx,
issueCtx, neighborText, loadRefineContext, assertCharacterAppearancesResolve,
+ persistRenderOrCancel,
} from './visualStageHelpers.js';
// Resolve the `referencePage` option ('prior' | 'next' | <0-based index>) to a
@@ -322,12 +323,17 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
* image when the target slot already carries the returned jobId (the reason
* this write must live behind the shared entry points, not only in the route).
*
+ * The job is enqueued BEFORE this write, so a rejected write (the page was
+ * deleted between the caller's read and here) would leave the job queued with
+ * nothing referencing it — `persistRenderOrCancel` cancels that orphan and
+ * rethrows (#3413).
+ *
* Returns { issue, stage } from the write tail.
*/
async function persistComicPageSlot(issueId, pageIndex, { variant, jobId, prompt, width, height, fromProof }) {
const slotKey = slotKeyForVariant(variant);
const slotRecord = buildRenderSlot({ slotKey, jobId, prompt, width, height, fromProof });
- return updateStageWithLatest(issueId, 'comicPages', (currentStage) => {
+ return persistRenderOrCancel(jobId, () => updateStageWithLatest(issueId, 'comicPages', (currentStage) => {
const currentPages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];
if (!currentPages[pageIndex]) {
throw new ServerError(
@@ -338,7 +344,7 @@ async function persistComicPageSlot(issueId, pageIndex, { variant, jobId, prompt
const nextPages = [...currentPages];
nextPages[pageIndex] = { ...currentPages[pageIndex], [slotKey]: slotRecord };
return { status: 'edited', pages: nextPages };
- });
+ }), 'comic page slot');
}
/**
diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.js
index b92fc06a37..d2dd537d0c 100644
--- a/server/services/pipeline/covers.js
+++ b/server/services/pipeline/covers.js
@@ -17,6 +17,7 @@ import {
stackStyle, buildMastheadClause, buildAuthorClause, applyWorldStyle,
loadBibleContext, resolveMode, resolveVariant, resolveProofInitImage,
PROOF_AS_BASE_DEFAULT_STRENGTH, enqueueImageJob, buildRenderSlot,
+ persistRenderOrCancel,
} from './visualStageHelpers.js';
/**
@@ -233,12 +234,17 @@ async function renderComicCoverLike(issueId, target, options = {}) {
slotKey, jobId: rest.jobId, prompt: rest.prompt,
width: options.width, height: options.height, fromProof: rest.fromProof,
});
- const { issue, stage } = await updateStageWithLatest(issueId, 'comicPages', (current) => {
- const currentSlot = current?.[target] || {};
- const nextSlot = { ...currentSlot, [slotKey]: slotRecord };
- if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];
- return { [target]: nextSlot };
- });
+ // The job is already queued; a rejected slot write would orphan it (#3413).
+ const { issue, stage } = await persistRenderOrCancel(
+ rest.jobId,
+ () => updateStageWithLatest(issueId, 'comicPages', (current) => {
+ const currentSlot = current?.[target] || {};
+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };
+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];
+ return { [target]: nextSlot };
+ }),
+ `comic ${target}`,
+ );
return { ...rest, [scriptField]: script, issue, stage };
}
@@ -400,12 +406,18 @@ async function renderVolumeCoverLike(seriesId, seasonId, target, options = {}) {
slotKey, jobId: rest.jobId, prompt: rest.prompt,
width: options.width, height: options.height, fromProof: rest.fromProof,
});
- const series = await updateSeasonOnSeries(seriesId, seasonId, (current) => {
- const currentSlot = current?.[target] || {};
- const nextSlot = { ...currentSlot, [slotKey]: slotRecord };
- if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];
- return { [target]: nextSlot };
- });
+ // Same orphan-cancel treatment as the issue-cover path (#3413) — a season
+ // deleted mid-render must not leave a queued job nothing points at.
+ const series = await persistRenderOrCancel(
+ rest.jobId,
+ () => updateSeasonOnSeries(seriesId, seasonId, (current) => {
+ const currentSlot = current?.[target] || {};
+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };
+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];
+ return { [target]: nextSlot };
+ }),
+ `volume ${target}`,
+ );
const season = (series.seasons || []).find((s) => s.id === seasonId);
return { ...rest, [scriptField]: script, season, series };
}
diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.js
index c02f994137..5731cc99e0 100644
--- a/server/services/pipeline/issuesShared.js
+++ b/server/services/pipeline/issuesShared.js
@@ -31,6 +31,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { ARC_ROLES } from '../../lib/storyArc.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeCoverLike } from '../../lib/renderSlot.js';
+import { ensureStoryboardIds } from '../../lib/storyboardScenes.js';
import { applyVolumeOrderedNumbers } from '../../lib/pipelineIssueOrder.js';
import * as seriesSvc from './series.js';
@@ -392,7 +393,20 @@ const sanitizeVisualStage = (raw, stageId = null) => {
return {
...base,
pages: Array.isArray(raw?.pages) ? raw.pages.slice(0, 200) : [],
- scenes: Array.isArray(raw?.scenes) ? raw.scenes.slice(0, 200) : [],
+ // Storyboard scenes (and their shots) carry a DURABLE `id` (#3413) so a
+ // render enqueue, its stage write, and the completion hook all address the
+ // same scene even when a concurrent reorder/delete shifts the indexes. The
+ // stamp is deterministic (`scene-01`, …) so two concurrent readers of an
+ // un-migrated record — and two federated peers running the backfill
+ // independently — derive identical ids. `stageId === null` is the legacy
+ // context-free sanitize; stamping there too keeps a load-time normalize
+ // from dropping the field back off. Migrations 222 / db-007 backfill the
+ // records already on disk.
+ scenes: Array.isArray(raw?.scenes)
+ ? (stageId === null || stageId === 'storyboards'
+ ? ensureStoryboardIds(raw.scenes.slice(0, 200))
+ : raw.scenes.slice(0, 200))
+ : [],
cdProjectId: isStr(raw?.cdProjectId) && raw.cdProjectId ? raw.cdProjectId : null,
videoPath: isStr(raw?.videoPath) && raw.videoPath ? raw.videoPath : null,
aspectRatio: ASPECT_RATIO_VALUES.has(raw?.aspectRatio) ? raw.aspectRatio : null,
diff --git a/server/services/pipeline/owners.js b/server/services/pipeline/owners.js
index 0ac334d37d..76de11cb26 100644
--- a/server/services/pipeline/owners.js
+++ b/server/services/pipeline/owners.js
@@ -73,25 +73,57 @@ export function parseSeasonCoverOwner(owner) {
return { seriesId, seasonId, target, variant };
}
-// Per-shot start-frame renders inside the storyboards stage. Scene-level
-// owners (`pipeline:<id>:storyboards:scene<N>`) still exist for legacy
-// scene-image renders that don't decompose into shots — that string is
-// produced inline by `enqueueVisualImage` and intentionally falls outside
-// this parser (no filename hook needed for the scene-level path).
-export function buildStoryboardsShotOwner({ issueId, sceneIndex, shotIndex }) {
- return `${PREFIX}:${issueId}:storyboards:scene${sceneIndex}:shot${shotIndex}`;
+// Per-shot start-frame renders inside the storyboards stage.
+//
+// Owners carry BOTH the durable scene/shot ids (#3413) and the indexes:
+// `pipeline:<id>:storyboards:scene<N>:shot<M>:sid<sceneId>:tid<shotId>`. The
+// completion hook resolves by id (so a reorder between enqueue and completion
+// still lands the render on the right shot) and falls back to the index for
+// LEGACY owners already sitting in the queue at upgrade time, which carry no
+// `:sid`/`:tid` suffix. Ids are percent-encoded so a `:` inside an id can't
+// break the parse.
+const encodeOwnerId = (id) => (typeof id === 'string' && id ? encodeURIComponent(id) : '');
+const decodeOwnerId = (raw) => {
+ if (!raw) return null;
+ // A malformed percent-escape would throw out of decodeURIComponent; a job
+ // owner is never worth crashing a completion handler over, so fall back to
+ // the raw token (which then simply fails to match any scene id and drops
+ // through to the index fallback).
+ try { return decodeURIComponent(raw); } catch { return raw; }
+};
+
+export function buildStoryboardsShotOwner({ issueId, sceneIndex, shotIndex, sceneId = null, shotId = null }) {
+ const base = `${PREFIX}:${issueId}:storyboards:scene${sceneIndex}:shot${shotIndex}`;
+ if (!sceneId && !shotId) return base;
+ return `${base}:sid${encodeOwnerId(sceneId)}:tid${encodeOwnerId(shotId)}`;
+}
+
+// Scene-level owners (`pipeline:<id>:storyboards:scene<N>[:sid<sceneId>]`) are
+// used by the single-scene VIDEO render (no shot decomposition). Nothing parses
+// them today — the render is tracked by the `sceneVideoJobId` stamped on the
+// scene — but the id rides along so `listJobs({ owner })` and the queue UI
+// identify the target unambiguously after a reorder.
+export function buildStoryboardsSceneOwner({ issueId, sceneIndex, sceneId = null }) {
+ const base = `${PREFIX}:${issueId}:storyboards:scene${sceneIndex}`;
+ return sceneId ? `${base}:sid${encodeOwnerId(sceneId)}` : base;
}
-const STORYBOARDS_SHOT_RE = /^pipeline:([^:]+):storyboards:scene(\d+):shot(\d+)$/;
+const STORYBOARDS_SHOT_RE = /^pipeline:([^:]+):storyboards:scene(\d+):shot(\d+)(?::sid([^:]*):tid([^:]*))?$/;
export function parseStoryboardsShotOwner(owner) {
if (typeof owner !== 'string') return null;
const m = owner.match(STORYBOARDS_SHOT_RE);
if (!m) return null;
- const [, issueId, sceneIdxStr, shotIdxStr] = m;
+ const [, issueId, sceneIdxStr, shotIdxStr, sceneIdRaw, shotIdRaw] = m;
const sceneIndex = Number(sceneIdxStr);
const shotIndex = Number(shotIdxStr);
if (!Number.isInteger(sceneIndex) || sceneIndex < 0) return null;
if (!Number.isInteger(shotIndex) || shotIndex < 0) return null;
- return { issueId, sceneIndex, shotIndex };
+ return {
+ issueId,
+ sceneIndex,
+ shotIndex,
+ sceneId: decodeOwnerId(sceneIdRaw),
+ shotId: decodeOwnerId(shotIdRaw),
+ };
}
diff --git a/server/services/pipeline/owners.test.js b/server/services/pipeline/owners.test.js
index ff8fb79097..cf5c000aa0 100644
--- a/server/services/pipeline/owners.test.js
+++ b/server/services/pipeline/owners.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
buildComicPagesOwner, parseComicPagesOwner,
- buildStoryboardsShotOwner, parseStoryboardsShotOwner,
+ buildStoryboardsShotOwner, parseStoryboardsShotOwner, buildStoryboardsSceneOwner,
buildSeasonCoverOwner, parseSeasonCoverOwner,
} from './owners.js';
@@ -61,10 +61,38 @@ describe('pipeline owner strings', () => {
expect(parseComicPagesOwner('pipeline:iss:comicPages:cover:sketch')).toBeNull();
});
- it('round-trips a storyboards shot owner', () => {
- const owner = buildStoryboardsShotOwner({ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5 });
- expect(owner).toBe('pipeline:iss-789:storyboards:scene2:shot5');
- expect(parseStoryboardsShotOwner(owner)).toEqual({ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5 });
+ it('round-trips a storyboards shot owner carrying durable ids', () => {
+ const owner = buildStoryboardsShotOwner({
+ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5, sceneId: 'scene-03', shotId: 'shot-06',
+ });
+ expect(owner).toBe('pipeline:iss-789:storyboards:scene2:shot5:sidscene-03:tidshot-06');
+ expect(parseStoryboardsShotOwner(owner)).toEqual({
+ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5, sceneId: 'scene-03', shotId: 'shot-06',
+ });
+ });
+
+ it('percent-encodes ids so a colon inside one cannot break the parse', () => {
+ const owner = buildStoryboardsShotOwner({
+ issueId: 'iss-789', sceneIndex: 0, shotIndex: 0, sceneId: 'a:b c', shotId: 'x:y',
+ });
+ expect(owner).toBe('pipeline:iss-789:storyboards:scene0:shot0:sida%3Ab%20c:tidx%3Ay');
+ expect(parseStoryboardsShotOwner(owner)).toMatchObject({ sceneId: 'a:b c', shotId: 'x:y' });
+ });
+
+ it('parses a LEGACY index-only shot owner with null ids (jobs queued pre-#3413)', () => {
+ expect(parseStoryboardsShotOwner('pipeline:iss-789:storyboards:scene2:shot5')).toEqual({
+ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5, sceneId: null, shotId: null,
+ });
+ // A build with no ids available (an un-migrated record) emits the legacy shape.
+ expect(buildStoryboardsShotOwner({ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5 }))
+ .toBe('pipeline:iss-789:storyboards:scene2:shot5');
+ });
+
+ it('round-trips a storyboards scene owner (scene-level video render)', () => {
+ expect(buildStoryboardsSceneOwner({ issueId: 'iss-789', sceneIndex: 1, sceneId: 'scene-02' }))
+ .toBe('pipeline:iss-789:storyboards:scene1:sidscene-02');
+ expect(buildStoryboardsSceneOwner({ issueId: 'iss-789', sceneIndex: 1 }))
+ .toBe('pipeline:iss-789:storyboards:scene1');
});
it('shot parser rejects non-shot owners and malformed indices', () => {
@@ -72,6 +100,8 @@ describe('pipeline owner strings', () => {
expect(parseStoryboardsShotOwner('pipeline:iss:comicPages:cover')).toBeNull();
expect(parseStoryboardsShotOwner('pipeline:iss:storyboards:scene0')).toBeNull();
expect(parseStoryboardsShotOwner('pipeline:iss:storyboards:scene1:shotNaN')).toBeNull();
+ // A scene-level owner (with or without its id) is never a shot owner.
+ expect(parseStoryboardsShotOwner('pipeline:iss:storyboards:scene0:sidscene-01')).toBeNull();
});
it('comic parser does not match shot owners and vice versa', () => {
diff --git a/server/services/pipeline/storyboards.js b/server/services/pipeline/storyboards.js
index a41bd3df03..32542dbb91 100644
--- a/server/services/pipeline/storyboards.js
+++ b/server/services/pipeline/storyboards.js
@@ -8,45 +8,65 @@
import { enqueueJob } from '../mediaJobQueue/index.js';
import { updateStageWithLatest, assertStageUnlocked } from './issues.js';
-import { buildStoryboardsShotOwner } from './owners.js';
+import { buildStoryboardsSceneOwner, buildStoryboardsShotOwner } from './owners.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { resolveStoryboardTarget } from '../../lib/storyboardScenes.js';
import { matchCharactersInText } from '../../lib/scenePrompt.js';
import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';
import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';
import { runPromptRefine, runImagePromptCandidates } from './refineHelpers.js';
import {
composeVisualPrompt, resolveMode, enqueueImageJob, loadBibleContext,
- seriesBibleCtx, issueCtx, neighborText, loadRefineContext,
+ seriesBibleCtx, issueCtx, neighborText, loadRefineContext, persistRenderOrCancel,
} from './visualStageHelpers.js';
/**
* Splice ONE storyboard scene through `updateStageWithLatest` (the serialized
* issue write tail) so the write merges against the freshest persisted
- * `scenes` array (#3400).
+ * `scenes` array (#3400) AND lands on the scene the caller actually read
+ * (#3413).
*
* `updateStage` serializes, but it shallow-merges whatever `scenes` value the
* caller computed *outside* the lock. Two enqueues for different scenes that
* both read the stage before either wrote would therefore clobber each other's
* freshly-stamped job id, leaving the losing job running untracked. Passing a
* mutator instead keeps the read-modify-write of `scenes` inside the lock, so
- * only the targeted index is replaced.
+ * only the targeted scene is replaced.
*
- * `mutate(scene) → nextScene` runs against the freshest scene at `index`.
- * Returns `{ issue, stage }` from the write tail.
+ * The target is `{ id, index }` captured during the caller's read. Inside the
+ * lock the id is re-resolved against the FRESH array, so a reorder that keeps
+ * `index` in range can no longer retarget the write onto a different scene. A
+ * captured id that is gone is a 409 (the scene was removed mid-flight), which
+ * is deliberately distinct from the 404 for an index that never existed. The
+ * index is used only when no id was captured — a record that predates the
+ * scene-id backfill.
+ *
+ * `mutate(scene) → nextScene` runs against the freshest matching scene.
+ * Returns `{ issue, stage, index }` — `index` is where the write LANDED, which
+ * is not necessarily the index the caller read.
*/
-function patchStoryboardScene(issueId, index, mutate) {
- return updateStageWithLatest(issueId, 'storyboards', (currentStage) => {
+async function patchStoryboardScene(issueId, target, mutate) {
+ let landedIndex = -1;
+ const { issue, stage } = await updateStageWithLatest(issueId, 'storyboards', (currentStage) => {
const currentScenes = Array.isArray(currentStage?.scenes) ? currentStage.scenes : [];
- const current = currentScenes[index];
- if (!current) {
- throw new ServerError(`sceneIndex ${index} out of range (have ${currentScenes.length})`, {
+ const { index, record, stale } = resolveStoryboardTarget(currentScenes, target);
+ if (stale) {
+ throw new ServerError(
+ `storyboard scene "${target.id}" no longer exists — it was removed or replaced while this render was being prepared`,
+ { status: 409, code: 'PIPELINE_SCENE_STALE_TARGET' },
+ );
+ }
+ if (!record) {
+ throw new ServerError(`sceneIndex ${target.index} out of range (have ${currentScenes.length})`, {
status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',
});
}
+ landedIndex = index;
const nextScenes = [...currentScenes];
- nextScenes[index] = mutate(current);
+ nextScenes[index] = mutate(record);
return { status: 'edited', scenes: nextScenes };
});
+ return { issue, stage, index: landedIndex };
}
/**
@@ -134,14 +154,20 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =
tiling: 'auto',
chunks: 1,
},
- owner: `pipeline:${issueId}:storyboards:scene${idx}`,
+ owner: buildStoryboardsSceneOwner({ issueId, sceneIndex: idx, sceneId: scene.id || null }),
});
- const { issue: updatedIssue, stage } = await patchStoryboardScene(
- issueId, idx, (current) => ({ ...current, sceneVideoJobId: jobId }),
+ const { issue: updatedIssue, stage, index: landedIndex } = await persistRenderOrCancel(
+ jobId,
+ () => patchStoryboardScene(
+ issueId,
+ { id: scene.id || null, index: idx },
+ (current) => ({ ...current, sceneVideoJobId: jobId }),
+ ),
+ 'storyboard scene video',
);
- console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${idx + 1} jobId=${jobId.slice(0, 8)}`);
- return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };
+ console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${landedIndex + 1} jobId=${jobId.slice(0, 8)}`);
+ return { jobId, prompt, sceneIndex: landedIndex, issue: updatedIssue, stage };
}
/**
@@ -205,21 +231,43 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI
const jobId = enqueueImageJob({
prompt, world, settings, options, mode, series,
- owner: buildStoryboardsShotOwner({ issueId, sceneIndex: sIdx, shotIndex: tIdx }),
+ owner: buildStoryboardsShotOwner({
+ issueId, sceneIndex: sIdx, shotIndex: tIdx,
+ sceneId: scene.id || null, shotId: shot.id || null,
+ }),
logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,
});
- const { issue: updatedIssue, stage } = await patchStoryboardScene(issueId, sIdx, (current) => {
- const currentShots = Array.isArray(current.shots) ? [...current.shots] : [];
- if (!currentShots[tIdx]) {
- throw new ServerError(`shotIndex ${tIdx} out of range (have ${currentShots.length})`, {
- status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',
- });
- }
- currentShots[tIdx] = { ...currentShots[tIdx], startFrameJobId: jobId };
- return { ...current, shots: currentShots };
- });
- return { jobId, mode, prompt, sceneIndex: sIdx, shotIndex: tIdx, issue: updatedIssue, stage };
+ // Both the scene AND the shot are re-resolved by their captured ids inside
+ // the write region — a reorder of either level must not move this job id
+ // onto a different shot.
+ let landedShotIndex = tIdx;
+ const { issue: updatedIssue, stage, index: landedSceneIndex } = await persistRenderOrCancel(
+ jobId,
+ () => patchStoryboardScene(issueId, { id: scene.id || null, index: sIdx }, (current) => {
+ const currentShots = Array.isArray(current.shots) ? [...current.shots] : [];
+ const resolved = resolveStoryboardTarget(currentShots, { id: shot.id || null, index: tIdx });
+ if (resolved.stale) {
+ throw new ServerError(
+ `storyboard shot "${shot.id}" no longer exists — it was removed or replaced while this render was being prepared`,
+ { status: 409, code: 'PIPELINE_SHOT_STALE_TARGET' },
+ );
+ }
+ if (!resolved.record) {
+ throw new ServerError(`shotIndex ${tIdx} out of range (have ${currentShots.length})`, {
+ status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',
+ });
+ }
+ landedShotIndex = resolved.index;
+ currentShots[resolved.index] = { ...resolved.record, startFrameJobId: jobId };
+ return { ...current, shots: currentShots };
+ }),
+ 'storyboard shot start-frame',
+ );
+ return {
+ jobId, mode, prompt, sceneIndex: landedSceneIndex, shotIndex: landedShotIndex,
+ issue: updatedIssue, stage,
+ };
}
// Validate the scene index, lock, and non-empty description, then build the
@@ -272,7 +320,7 @@ async function loadStoryboardScenePromptContext(issueId, sceneIndex) {
* description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.
*/
export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {
- const { idx, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);
+ const { idx, scene, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);
const { refined, changes, runId, providerId } = await runPromptRefine({
templateName: 'pipeline-storyboard-image-prompt',
@@ -284,11 +332,13 @@ export async function refineStoryboardScenePrompt(issueId, sceneIndex, options =
// Same freshest-scenes merge as the enqueue paths — the LLM round-trip above
// is the widest read→write window in this file, so a sibling scene's render
- // enqueue landing mid-refine must not be reverted by this write.
- const { issue: updatedIssue, stage } = await patchStoryboardScene(
- issueId, idx, (current) => ({ ...current, description: refined }),
+ // enqueue landing mid-refine must not be reverted by this write, and a
+ // reorder during that window must not park the refined description on a
+ // different scene.
+ const { issue: updatedIssue, stage, index: landedIndex } = await patchStoryboardScene(
+ issueId, { id: scene.id || null, index: idx }, (current) => ({ ...current, description: refined }),
);
- return { scene: stage.scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };
+ return { scene: stage.scenes[landedIndex], issue: updatedIssue, stage, runId, changes, providerId };
}
/**
diff --git a/server/services/pipeline/storyboardsFilenameHook.js b/server/services/pipeline/storyboardsFilenameHook.js
index 1e7d39da45..4af2ca85bc 100644
--- a/server/services/pipeline/storyboardsFilenameHook.js
+++ b/server/services/pipeline/storyboardsFilenameHook.js
@@ -6,9 +6,16 @@
* TTL expires. Legacy scene-level renders (no shot decomposition) use the
* media-job record directly; only per-shot owners produced by
* `buildStoryboardsShotOwner` are handled here.
+ *
+ * Targets resolve by the durable scene/shot ids the owner carries (#3413), so
+ * a reorder between enqueue and completion still lands the render on the shot
+ * the user asked for. Owners enqueued before that change carry no ids — those
+ * fall back to the indexes, which is exactly the behavior they were queued
+ * under, so in-flight jobs still attach across the upgrade.
*/
import { parseStoryboardsShotOwner } from './owners.js';
+import { resolveStoryboardTarget } from '../../lib/storyboardScenes.js';
import { createFilenameHook } from './filenameHookFactory.js';
const hook = createFilenameHook({
@@ -17,20 +24,23 @@ const hook = createFilenameHook({
parseOwner: parseStoryboardsShotOwner,
applyFilename: (currentStage, parsed, job, filename) => {
const scenes = Array.isArray(currentStage?.scenes) ? currentStage.scenes : [];
- const scene = scenes[parsed.sceneIndex];
- const shots = Array.isArray(scene?.shots) ? scene.shots : [];
- const shot = shots[parsed.shotIndex];
+ const sceneHit = resolveStoryboardTarget(scenes, { id: parsed.sceneId, index: parsed.sceneIndex });
+ const scene = sceneHit.record;
+ if (!scene) return null;
+ const shots = Array.isArray(scene.shots) ? scene.shots : [];
+ const shotHit = resolveStoryboardTarget(shots, { id: parsed.shotId, index: parsed.shotIndex });
+ const shot = shotHit.record;
// Skip if THIS job isn't the shot's active render — a re-render that
// landed between enqueue and this event would otherwise be overwritten
// with the older filename.
if (!shot || shot.startFrameJobId !== job.id) return null;
const nextShots = [...shots];
- nextShots[parsed.shotIndex] = { ...shot, startFrameFilename: filename };
+ nextShots[shotHit.index] = { ...shot, startFrameFilename: filename };
const nextScenes = [...scenes];
- nextScenes[parsed.sceneIndex] = { ...scene, shots: nextShots };
+ nextScenes[sceneHit.index] = { ...scene, shots: nextShots };
return {
patch: { scenes: nextScenes },
- label: `scene${parsed.sceneIndex}/shot${parsed.shotIndex}`,
+ label: `scene${sceneHit.index}/shot${shotHit.index}`,
};
},
});
diff --git a/server/services/pipeline/storyboardsFilenameHook.test.js b/server/services/pipeline/storyboardsFilenameHook.test.js
new file mode 100644
index 0000000000..a4b0565647
--- /dev/null
+++ b/server/services/pipeline/storyboardsFilenameHook.test.js
@@ -0,0 +1,127 @@
+/**
+ * Storyboards shot filename hook — completion routing (#3413).
+ *
+ * The hook must stamp the finished render onto the shot the render was
+ * ENQUEUED for, even when the scenes/shots reordered while the job was in the
+ * queue, and must still attach jobs queued under the LEGACY index-only owner
+ * format (no ids) so an upgrade doesn't strand in-flight renders.
+ *
+ * The hook's handler runs inside a `void (async () => {})` IIFE, so each test
+ * waits for the side effect rather than awaiting the emit.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const issuesStore = new Map();
+
+const updateStageWithLatestMock = vi.fn(async (issueId, stageId, computeFn) => {
+ const issue = issuesStore.get(issueId);
+ if (!issue) throw new Error('issue not found');
+ const currentStage = issue.stages?.[stageId] || null;
+ const patch = computeFn(currentStage);
+ if (!patch || Object.keys(patch).length === 0) return { issue, stage: currentStage };
+ issue.stages[stageId] = { ...currentStage, ...patch };
+ return { issue, stage: issue.stages[stageId] };
+});
+
+vi.mock('./issues.js', () => ({
+ updateStageWithLatest: (...a) => updateStageWithLatestMock(...a),
+}));
+
+const { mediaJobEvents } = await import('../mediaJobQueue/index.js');
+const hook = await import('./storyboardsFilenameHook.js');
+const { buildStoryboardsShotOwner } = await import('./owners.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+const seedIssue = (scenes) => {
+ issuesStore.set('iss-1', { id: 'iss-1', stages: { storyboards: { scenes } } });
+};
+const shotsOf = (sceneIndex) => issuesStore.get('iss-1').stages.storyboards.scenes[sceneIndex].shots;
+
+beforeEach(() => {
+ issuesStore.clear();
+ updateStageWithLatestMock.mockClear();
+ hook.__testing.reset();
+ hook.initStoryboardsFilenameHook();
+});
+
+afterEach(() => {
+ hook.__testing.reset();
+});
+
+describe('storyboardsFilenameHook', () => {
+ it('routes the completed render by scene/shot id after a reorder', async () => {
+ // Enqueued against scene index 1 / shot index 0; by completion time the
+ // scenes have been reordered, so index addressing would hit the wrong shot.
+ seedIssue([
+ { id: 'scene-02', shots: [{ id: 'shot-01', startFrameJobId: 'other-job' }] },
+ { id: 'scene-01', shots: [{ id: 'shot-07', startFrameJobId: 'job-1' }] },
+ ]);
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-1',
+ kind: 'image',
+ result: { filename: 'shot.png' },
+ owner: buildStoryboardsShotOwner({
+ issueId: 'iss-1', sceneIndex: 0, shotIndex: 0, sceneId: 'scene-01', shotId: 'shot-07',
+ }),
+ });
+
+ await waitFor(() => shotsOf(1)[0].startFrameFilename === 'shot.png');
+ expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
+ });
+
+ it('attaches a job queued under a LEGACY index-only owner (no ids)', async () => {
+ seedIssue([
+ { id: 'scene-01', shots: [{ id: 'shot-01', startFrameJobId: 'legacy-job' }] },
+ ]);
+
+ mediaJobEvents.emit('completed', {
+ id: 'legacy-job',
+ kind: 'image',
+ result: { filename: 'legacy.png' },
+ owner: 'pipeline:iss-1:storyboards:scene0:shot0',
+ });
+
+ await waitFor(() => shotsOf(0)[0].startFrameFilename === 'legacy.png');
+ });
+
+ it('skips when the shot is no longer pointing at this job (stale re-render)', async () => {
+ seedIssue([{ id: 'scene-01', shots: [{ id: 'shot-01', startFrameJobId: 'newer-job' }] }]);
+
+ mediaJobEvents.emit('completed', {
+ id: 'stale-job',
+ kind: 'image',
+ result: { filename: 'stale.png' },
+ owner: buildStoryboardsShotOwner({
+ issueId: 'iss-1', sceneIndex: 0, shotIndex: 0, sceneId: 'scene-01', shotId: 'shot-01',
+ }),
+ });
+
+ await waitFor(() => updateStageWithLatestMock.mock.calls.length > 0);
+ expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
+ });
+
+ it('skips when the scene the owner names is gone entirely', async () => {
+ seedIssue([{ id: 'scene-02', shots: [{ id: 'shot-01', startFrameJobId: 'job-1' }] }]);
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-1',
+ kind: 'image',
+ result: { filename: 'orphan.png' },
+ owner: buildStoryboardsShotOwner({
+ issueId: 'iss-1', sceneIndex: 0, shotIndex: 0, sceneId: 'scene-99', shotId: 'shot-99',
+ }),
+ });
+
+ await waitFor(() => updateStageWithLatestMock.mock.calls.length > 0);
+ expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
+ });
+});
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index 84c66046fc..99f2c51a07 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -8,7 +8,7 @@
* the LLM-refine context loaders. Pure move — no behavior change.
*/
-import { enqueueJob } from '../mediaJobQueue/index.js';
+import { enqueueJob, cancelJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries, STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';
import { getIssue } from './issues.js';
@@ -462,7 +462,30 @@ async function loadRefineContext(issueId) {
return { issue, series };
}
-
+/**
+ * Every render surface here follows the same two-step shape: enqueue the media
+ * job FIRST (so the job id exists), then persist that id onto the record the
+ * completion hook will read. When step two rejects — the page/scene/shot
+ * vanished between the caller's read and the serialized write — the job is
+ * already queued and nothing references it: it burns GPU time and leaves an
+ * untracked artifact (#3413).
+ *
+ * `persistRenderOrCancel` wraps step two so a rejected write cancels the job it
+ * just enqueued and then rethrows the ORIGINAL error (the caller's 404/409 is
+ * what the user needs to see; a cancel failure must not mask it). Cancel
+ * failures are logged, never thrown — cleanup is best-effort bookkeeping.
+ */
+const persistRenderOrCancel = (jobId, persist, label = 'render') =>
+ Promise.resolve().then(persist).catch(async (err) => {
+ const short = String(jobId || '').slice(0, 8);
+ const outcome = await cancelJob(jobId).catch((cancelErr) => ({ ok: false, error: cancelErr.message }));
+ if (outcome?.ok) {
+ console.log(`🧹 Canceled orphaned media-job [${short}] — ${label} write rejected: ${err.message}`);
+ } else {
+ console.error(`❌ Could not cancel orphaned media-job [${short}] after ${label} write rejected: ${outcome?.error || outcome?.code || 'unknown'}`);
+ }
+ throw err;
+ });
// Shared helpers consumed by covers / comicPages / storyboards. Exported here
// (rather than inline) so the split feature modules reach one implementation.
@@ -472,5 +495,5 @@ export {
PROOF_AS_BASE_DEFAULT_STRENGTH, enqueueImageJob, formatBalloon,
resolvePageReferenceImage, REFERENCE_PAGE_DEFAULT_STRENGTH,
REFINE_RENDER_DEFAULT_STRENGTH, applyCharacterLorasToRender, loraRenderOptions,
- seriesBibleCtx, issueCtx, neighborText, loadRefineContext,
+ seriesBibleCtx, issueCtx, neighborText, loadRefineContext, persistRenderOrCancel,
};
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index 44e6894804..6e44dca1e6 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -83,7 +83,28 @@ vi.mock('../universeBuilder.js', () => ({
}));
const enqueueJobMock = vi.fn(() => ({ jobId: 'job-fake-1234' }));
-vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJobMock(...a) }));
+// A tiny stand-in queue so the orphan-cancel tests (#3413) can assert that a
+// rejected stage write leaves NO queued job behind for that owner — the real
+// `listJobs({ owner })` contract, without the real worker.
+const fakeQueue = [];
+const enqueueIntoFakeQueue = (args) => {
+ const result = enqueueJobMock(args);
+ fakeQueue.push({ id: result.jobId, owner: args.owner, status: 'queued' });
+ return result;
+};
+const listFakeJobs = ({ owner, status } = {}) => fakeQueue.filter(
+ (j) => (!owner || j.owner === owner) && (!status || j.status === status),
+);
+const cancelJobMock = vi.fn(async (jobId) => {
+ const job = fakeQueue.find((j) => j.id === jobId && j.status === 'queued');
+ if (!job) return { ok: false, code: 'NOT_FOUND' };
+ job.status = 'canceled';
+ return { ok: true, status: 'canceled' };
+});
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: (...a) => enqueueIntoFakeQueue(...a),
+ cancelJob: (...a) => cancelJobMock(...a),
+}));
const DEFAULT_RUN_STAGED_LLM = async () => ({
content: { prompt: 'refined prompt body', changes: ['tightened the framing'] },
@@ -161,6 +182,8 @@ beforeEach(() => {
updateStageWithLatestMock.mockImplementation(DEFAULT_UPDATE_STAGE_WITH_LATEST);
enqueueJobMock.mockReset();
enqueueJobMock.mockImplementation(() => ({ jobId: 'job-fake-1234' }));
+ fakeQueue.length = 0;
+ cancelJobMock.mockClear();
updateSeasonOnSeriesMock.mockClear();
assertStageUnlockedMock.mockClear();
// Restore the default implementation — several #904 tests install a
@@ -634,7 +657,9 @@ describe('enqueueStoryboardShotStartFrame', () => {
expect(result.shotIndex).toBe(0);
expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({
kind: 'image',
- owner: 'pipeline:iss-test:storyboards:scene0:shot0',
+ // scene carries no id in this fixture (pre-migration record) — the owner
+ // still stamps the shot's durable id (#3413).
+ owner: 'pipeline:iss-test:storyboards:scene0:shot0:sid:tids1',
}));
expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.any(Function));
expect(result.stage.scenes[0].shots[0].startFrameJobId).toBe('job-fake-1234');
@@ -747,6 +772,161 @@ describe('concurrent storyboard scene enqueues (#3400)', () => {
});
});
+// #3413 — index addressing survived #3400: a reorder/delete that kept `index`
+// IN RANGE still retargeted the write onto whatever scene now sat in that slot,
+// and a rejected write left the already-enqueued job orphaned in the queue.
+// Scenes now carry a durable `id`; the write region resolves by it.
+describe('storyboard scene durable-id addressing (#3413)', () => {
+ // Same serialized write tail as the #3400 block, but the persisted array can
+ // differ from what the caller read — that IS the race being modeled.
+ const installWriteTail = (persistedScenes) => {
+ const persisted = { storyboards: { scenes: structuredClone(persistedScenes) } };
+ let tail = Promise.resolve();
+ updateStageWithLatestMock.mockImplementation((issueId, stageId, computeFn) => {
+ tail = tail.then(async () => {
+ await Promise.resolve();
+ const current = structuredClone(persisted[stageId] || {});
+ const patch = computeFn(current);
+ persisted[stageId] = { ...current, ...patch };
+ return { issue: { ...mockIssue, stages: structuredClone(persisted) }, stage: structuredClone(persisted[stageId]) };
+ });
+ return tail;
+ });
+ return persisted;
+ };
+
+ // What the CALLER read (which may no longer match what is persisted).
+ const readScenes = (scenes) => {
+ getIssueMock.mockResolvedValue({
+ ...structuredClone(mockIssue),
+ stages: { ...structuredClone(mockIssue.stages), storyboards: { scenes: structuredClone(scenes) } },
+ });
+ };
+
+ const SCENE_A = { id: 'scene-01', slugline: 'A', description: 'Scene A.' };
+ const SCENE_B = { id: 'scene-02', slugline: 'B', description: 'Scene B.' };
+
+ it('a reorder that keeps the index in range does NOT move the job id onto the wrong scene', async () => {
+ // Persisted order is B, A — the caller read A, B and asked for index 0 (A).
+ const persisted = installWriteTail([SCENE_B, SCENE_A]);
+ readScenes([SCENE_A, SCENE_B]);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-scene-a' });
+
+ const result = await enqueueStoryboardSceneVideo('iss-test', 0, {});
+
+ expect(persisted.storyboards.scenes[1].id).toBe('scene-01');
+ expect(persisted.storyboards.scenes[1].sceneVideoJobId).toBe('job-scene-a');
+ expect(persisted.storyboards.scenes[0].sceneVideoJobId).toBeUndefined();
+ // The response reports where the write LANDED, not the stale read index.
+ expect(result.sceneIndex).toBe(1);
+ });
+
+ it('409s (not a mis-targeted write) when the scene was removed between read and write', async () => {
+ const persisted = installWriteTail([SCENE_A, SCENE_B]);
+ // Caller read a third scene that is already gone by write time — its index
+ // (1) is still in range, so index addressing would have hit SCENE_B.
+ readScenes([SCENE_A, { id: 'scene-99', slugline: 'gone', description: 'Deleted scene.' }, SCENE_B]);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-doomed' });
+
+ await expect(enqueueStoryboardSceneVideo('iss-test', 1, {}))
+ .rejects.toMatchObject({ status: 409, code: 'PIPELINE_SCENE_STALE_TARGET' });
+ expect(persisted.storyboards.scenes.every((s) => !s.sceneVideoJobId)).toBe(true);
+ });
+
+ it('cancels the orphaned job when the stage write rejects — no queued job left for that owner', async () => {
+ installWriteTail([SCENE_A, SCENE_B]);
+ readScenes([SCENE_A, { id: 'scene-99', description: 'Deleted scene.' }, SCENE_B]);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-doomed' });
+
+ await expect(enqueueStoryboardSceneVideo('iss-test', 1, {})).rejects.toThrow(/no longer exists/);
+
+ const owner = 'pipeline:iss-test:storyboards:scene1:sidscene-99';
+ expect(cancelJobMock).toHaveBeenCalledWith('job-doomed');
+ expect(listFakeJobs({ owner, status: 'queued' })).toEqual([]);
+ expect(listFakeJobs({ owner })).toEqual([{ id: 'job-doomed', owner, status: 'canceled' }]);
+ });
+
+ it('resolves the SHOT by id too, so a shot reorder cannot move the start-frame job', async () => {
+ const shotOne = { id: 'shot-01', description: 'shot one' };
+ const shotTwo = { id: 'shot-02', description: 'shot two' };
+ const persisted = installWriteTail([{ ...SCENE_A, shots: [shotTwo, shotOne] }]);
+ readScenes([{ ...SCENE_A, shots: [shotOne, shotTwo] }]);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-shot-one' });
+
+ const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
+
+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({
+ owner: 'pipeline:iss-test:storyboards:scene0:shot0:sidscene-01:tidshot-01',
+ }));
+ const shots = persisted.storyboards.scenes[0].shots;
+ expect(shots[1].id).toBe('shot-01');
+ expect(shots[1].startFrameJobId).toBe('job-shot-one');
+ expect(shots[0].startFrameJobId).toBeUndefined();
+ expect(result.shotIndex).toBe(1);
+ });
+
+ it('409s + cancels when the SHOT vanished between read and write', async () => {
+ installWriteTail([{ ...SCENE_A, shots: [{ id: 'shot-01', description: 'shot one' }] }]);
+ readScenes([{
+ ...SCENE_A,
+ shots: [{ id: 'shot-01', description: 'shot one' }, { id: 'shot-99', description: 'deleted shot' }],
+ }]);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-shot-doomed' });
+
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 0, 1))
+ .rejects.toMatchObject({ status: 409, code: 'PIPELINE_SHOT_STALE_TARGET' });
+ expect(cancelJobMock).toHaveBeenCalledWith('job-shot-doomed');
+ expect(listFakeJobs({ status: 'queued' })).toEqual([]);
+ });
+
+ it('falls back to the index for a PRE-MIGRATION record whose scenes carry no ids', async () => {
+ const legacy = [{ description: 'Scene 1.' }, { description: 'Scene 2.' }];
+ const persisted = installWriteTail(legacy);
+ readScenes(legacy);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-legacy' });
+
+ const result = await enqueueStoryboardSceneVideo('iss-test', 1, {});
+
+ expect(persisted.storyboards.scenes[1].sceneVideoJobId).toBe('job-legacy');
+ expect(result.sceneIndex).toBe(1);
+ // No ids anywhere → the owner keeps the legacy index-only shape.
+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({
+ owner: 'pipeline:iss-test:storyboards:scene1',
+ }));
+ });
+
+ it('a scene-prompt refine lands on the scene it read, not the slot it read', async () => {
+ const persisted = installWriteTail([SCENE_B, SCENE_A]);
+ readScenes([SCENE_A, SCENE_B]);
+
+ const result = await refineStoryboardScenePrompt('iss-test', 0);
+
+ expect(persisted.storyboards.scenes[1].description).toBe('refined prompt body');
+ expect(persisted.storyboards.scenes[0].description).toBe('Scene B.');
+ expect(result.scene.id).toBe('scene-01');
+ });
+
+ it('a rejected COMIC PAGE slot write cancels its orphaned job too', async () => {
+ updateStageWithLatestMock.mockRejectedValue(
+ Object.assign(new Error('pageIndex 0 out of range'), { status: 404 }),
+ );
+ enqueueJobMock.mockReturnValue({ jobId: 'job-page-doomed' });
+
+ await expect(renderComicPage('iss-test', { pageIndex: 0 })).rejects.toThrow(/out of range/);
+ expect(cancelJobMock).toHaveBeenCalledWith('job-page-doomed');
+ expect(listFakeJobs({ status: 'queued' })).toEqual([]);
+ });
+
+ it('a rejected COVER slot write cancels its orphaned job too', async () => {
+ updateStageWithLatestMock.mockRejectedValue(new Error('issue vanished'));
+ enqueueJobMock.mockReturnValue({ jobId: 'job-cover-doomed' });
+
+ await expect(renderComicCover('iss-test', {})).rejects.toThrow(/issue vanished/);
+ expect(cancelJobMock).toHaveBeenCalledWith('job-cover-doomed');
+ expect(listFakeJobs({ status: 'queued' })).toEqual([]);
+ });
+});
+
describe('refineComicPanelPrompt', () => {
it('rejects a non-integer pageIndex / panelIndex', async () => {
await expect(refineComicPanelPrompt('iss-test', 'nope', 0)).rejects.toThrow(/non-negative integers/);