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

fix: admit generated-video finalizers to backup cuts (#9982)

[._.]/ Adam Eivy557d965ac13e
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 84b8ac797d..fb5970de16 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -236,6 +236,17 @@ The completion-hook and reconcile writes to `media_assets`, and poster edits
leaving its old thumbnail pointer, are explicitly outstanding as
`media-asset-index-refresh`; the final sweep must settle their restore semantics.
+Local generated videos (including each batch member) and Grok, fal and Reactor
+videos share an admitted finalizer. Fresh producer output is unreferenced until
+that finalizer takes admission before faststart and poster creation, then commits
+serialized history or removes the owned video, possible partial poster and
+faststart staging file before releasing the lease. A missing thumbnail retains
+the existing thumbnail-less behavior. Terminal status and notifications follow
+the durable commit. Caller publication latches keep committed outputs and earlier
+batch members out of later failure or cancellation cleanup. Federated video
+replacement/replay and derived stitch, upscale, timeline and HTML-composition
+lanes remain outstanding; this does not settle the derived media index.
+
Code Animation writes its HTML, revision trees and run artifacts before the row
that first names them. A generated animation's HTML and the job row marking it
completed hold one lease. A package import or repair stages its revision into a
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index bfb9394b9b..1924b72274 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -296,13 +296,21 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
modules: ['services/videoUpload.js', 'services/videoDownload.js', 'services/videoGen/poster.js'],
},
{
- // Local, cloud and federated finalize, derived clips (stitch, upscale,
- // timeline, HTML composition). Library imports and poster edits are above.
+ // The shared local, batch and cloud (Grok/fal/Reactor) finalize owns
+ // faststart, poster, serialized history and rollback. Caller latches keep
+ // committed outputs out of later failure/cancellation cleanup. Long fresh
+ // producers remain outside admission; only unreferenced outputs are discarded.
+ id: 'generated-video-shared-finalizer',
+ status: 'admitted',
+ modules: ['services/videoGen/generateVideoHelpers.js'],
+ },
+ {
+ // Federated replacement/replay and derived clips (stitch, upscale,
+ // timeline, HTML composition) have not yet proven their publication tails.
id: 'video-generation-finalize-and-derived-clips',
status: 'outstanding',
modules: [
- 'services/videoGen/generateVideoHelpers.js', 'services/videoGen/spawnWatch.js', 'services/videoGen/grok.js',
- 'services/videoGen/fal.js', 'services/videoGen/reactor.js', 'services/videoGen/remote.js',
+ 'services/videoGen/remote.js',
'services/videoGen/stitchVideos.js', 'services/videoGen/upscaleVideo.js', 'services/videoGen/upscaleJob.js',
'services/videoTimeline/local.js', 'services/htmlComposition/index.js',
],
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 359c2483ef..2d412a765b 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -39,7 +39,8 @@ import {
import { probeVideoDuration, probeVideoGeometry } from '../../lib/ffmpeg.js';
import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
-import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
+import { discardUnpublishedVideo, finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
+import { maintenance } from '../../lib/maintenanceAdmission.js';
import { mutateVideoHistory } from './history.js';
import { getSettings } from '../settings.js';
import { nearestAspectRatio } from '../imageGen/modes.js';
@@ -261,6 +262,7 @@ async function runFalVideo(job, jobId, {
audioFilePath = null, enableTranscription = false, requestSpec = null,
}) {
const entry = createFalRequestEntry(apiKey);
+ const publication = {};
activeRequests.set(jobId, entry);
const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;
try {
@@ -323,7 +325,7 @@ async function runFalVideo(job, jobId, {
}
activeRequests.delete(jobId);
activeJobs.delete(jobId);
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, ...measured }, actualSeed: null, mutateHistory: mutateVideoHistory });
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, ...measured }, actualSeed: null, mutateHistory: mutateVideoHistory, publication });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
// Best-effort: an unanticipated throw (e.g. from fetchFalResult or the
@@ -333,12 +335,13 @@ async function runFalVideo(job, jobId, {
// request was never submitted (no cancelUrl yet), so this never sends a
// stray cancel for a job that already finished on fal.ai's side (#8340).
//
- // finalizeGeneratedVideo marks job.status='complete' BEFORE its async
- // post-processing (faststart/thumbnail/history), and the request slot is
- // already released above — a throw there must still surface as a terminal
- // failure or the queue's job stays 'running' until the watchdog and the
- // client never gets a terminal frame. Force past the idempotence guard,
- // same as videoGen/grok.js's post-exit catch and reactor.js's catch-all (#6831).
+ // A dispatch failure can follow the durable commit. Never remove those
+ // bytes; a failure before publication cleans only this fresh output.
+ if (!publication.committed) await discardUnpublishedVideo({ jobId, outputPath }).catch(error => {
+ maintenance.markCurrentUnsettled();
+ maintenance.markResourceUnsettled('media', jobId);
+ console.error(`❌ fal video publication cleanup failed [${jobId.slice(0, 8)}]: ${error.message}`);
+ });
await cancelFalRequest(entry);
if (entry.aborted) return finalizeCanceled(job, jobId);
finalizeJobFailure(job, jobId, null, `fal.ai video generation failed: ${err?.message || err}`, { force: true });
diff --git a/server/services/videoGen/fal.test.js b/server/services/videoGen/fal.test.js
index 568cf41656..89499275db 100644
--- a/server/services/videoGen/fal.test.js
+++ b/server/services/videoGen/fal.test.js
@@ -11,6 +11,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
actual.PATHS.videos = FAKE_VIDEOS_DIR;
actual.PATHS.data = FAKE_DATA_DIR;
+ actual.PATHS.videoThumbnails = join(TEST_ROOT, 'thumbnails');
return {
...actual,
ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
@@ -34,7 +35,7 @@ const ffmpeg = await import('../../lib/ffmpeg.js');
const { videoGenEvents } = await import('./events.js');
const { loadHistory } = await import('./history.js');
-// A returned job (or its early 'complete' status stamp) is not a settled run.
+ // A returned job is not a settled run.
// Track from 'started', before generateVideo returns, through the terminal
// event after the real finalization/history tail. Keep mocks and files alive
// until every started job has reached that boundary, even if a test throws.
@@ -334,15 +335,8 @@ describe('videoGen/fal — generateVideo', () => {
}
});
- // Regression (#6831): finalizeGeneratedVideo stamps job.status = 'complete'
- // BEFORE its own faststart/thumbnail/history tail, and runFalVideo has
- // already released the request slot by then, so a throw from that tail
- // lands in the catch-all with the job already reading 'complete'. Without
- // `force: true` the shared finalizer's idempotency guard made that a silent
- // no-op — no 'failed' event for the media queue, no SSE error frame for the
- // client — the window videoGen/grok.js's post-exit catch (fa3796650) and
- // reactor.js's catch-all already force past.
- it('still emits failed when finalizeGeneratedVideo throws after job.status is already complete', async () => {
+ // A post-download failure must settle the queue and SSE client after cleanup.
+ it('emits failed when post-download finalization throws', async () => {
const requestId = 'req-tail';
const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;
const responseUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}`;
@@ -355,8 +349,7 @@ describe('videoGen/fal — generateVideo', () => {
}
throw new Error(`unexpected fetch: ${url}`);
}));
- // The first step after the 'complete' stamp rejects — the download has
- // already landed on disk, so this is purely the post-processing window.
+ // The download has landed; reject the first post-processing step.
ffmpeg.optimizeForStreaming.mockRejectedValueOnce(new Error('faststart remux failed'));
const failed = vi.fn();
diff --git a/server/services/videoGen/finalizeBackupAdmission.test.js b/server/services/videoGen/finalizeBackupAdmission.test.js
new file mode 100644
index 0000000000..c7e7f2f908
--- /dev/null
+++ b/server/services/videoGen/finalizeBackupAdmission.test.js
@@ -0,0 +1,397 @@
+/** Real copied assets/history against shared generated-video publication. */
+import { afterAll, afterEach, beforeEach, describe, expect, it as vitestIt, vi } from 'vitest';
+import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { EventEmitter } from 'node:events';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy, ownTestBodies } from '../../lib/mockPathsDataRoot.js';
+
+const state = vi.hoisted(() => ({
+ bypass: false, admission: null, historyGate: null, unlinkGate: null, faststartGate: null,
+ failHistory: false, failFaststart: false, thumbnailFailure: null, child: null, input: null, localChild: null,
+}));
+vi.mock('../../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: () => lazyTempDataRoot('portos-generated-video-cut-'),
+ overrides: {
+ atomicWrite: async (path, value) => {
+ if (basename(path) === 'video-history.json') {
+ state.historyGate?.entered.resolve();
+ if (state.historyGate) await state.historyGate.finish.promise;
+ if (state.failHistory) throw new Error('history commit failed');
+ }
+ return actual.atomicWrite(path, value);
+ },
+ unlinkGuarded: async path => {
+ if (state.unlinkGate?.matches(path)) {
+ state.unlinkGate.entered.resolve();
+ await state.unlinkGate.finish.promise;
+ }
+ return actual.unlinkGuarded(path);
+ },
+ },
+ });
+});
+vi.mock('../../lib/databaseMaintenanceJournal.js', async importOriginal => ({
+ ...(await importOriginal()), assertDatabaseAdmission: () => {},
+}));
+vi.mock('../../lib/backupSnapshotBoundary.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, withBackupAssetPublication: work => {
+ state.admission?.resolve();
+ return state.bypass ? work() : actual.withBackupAssetPublication(work);
+ } };
+});
+vi.mock('../../lib/ffmpeg.js', () => ({
+ probeFrameCount: async () => 25,
+ probeVideoDuration: async () => 1,
+ optimizeForStreaming: vi.fn(async path => {
+ await writeFile(`${path}.fs.mp4`, 'faststart staging');
+ state.faststartGate?.entered.resolve();
+ if (state.faststartGate) await state.faststartGate.finish.promise;
+ if (state.failFaststart) throw new Error('faststart failed');
+ await rm(`${path}.fs.mp4`);
+ }),
+ generateThumbnail: vi.fn(async (_path, id) => {
+ const { PATHS } = await import('../../lib/fileUtils.js');
+ await writeFile(join(PATHS.videoThumbnails, `${id}.jpg`), `poster:${id}`);
+ if (state.thumbnailFailure === 'throw') throw new Error('poster failed');
+ return state.thumbnailFailure === 'null' ? null : `${id}.jpg`;
+ }),
+ extractEvaluationFrames: vi.fn(async () => []),
+}));
+vi.mock('../../lib/childProcess.js', async importOriginal => ({
+ ...(await importOriginal()), spawn: () => {
+ const child = Object.assign(new EventEmitter(), {
+ stdout: new EventEmitter(), stderr: new EventEmitter(), stdin: new EventEmitter(),
+ kill: vi.fn(() => queueMicrotask(() => child.emit('close', null, 'SIGTERM'))),
+ });
+ child.stdin.end = body => { state.input = JSON.parse(body); };
+ state.child = child;
+ return child;
+ },
+}));
+vi.mock('./reactorRuntime.js', () => ({ ensureReactorRuntime: async () => 'synthetic-python' }));
+vi.mock('../settings.js', () => ({ getSettings: async () => ({ videoGen: { reactor: { apiKey: 'example-key' } } }) }));
+vi.mock('../../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: async () => ({ ok: true, release: async () => {}, handoffTo: async () => {} }) }));
+vi.mock('../../lib/detachedSpawn.js', () => ({ spawnDetached: async () => state.localChild }));
+vi.mock('../localMemory.js', () => ({ prepareLocalMemory: async () => ({ blockers: [], unloaded: [] }), gpuBlockersMessage: () => '' }));
+vi.mock('../hfToken.js', () => ({ hfChildEnv: async () => ({}) }));
+vi.mock('./runtimes.js', () => ({
+ BYOV_RUNTIME_INFO: {}, runtimeIsCacheOnly: () => false, runtimeNeedsProcessGroupKill: () => false,
+ runtimeUsesMlx: () => false, invalidateByovReadyCache: () => {}, pickDeathFingerprint: async () => null,
+}));
+vi.mock('./displayPower.js', () => ({ isDisplaySleepEnabled: () => false, sleepDisplayForVideo: () => {}, wakeDisplayForVideo: () => {} }));
+vi.mock('fs', async importOriginal => ({ ...(await importOriginal()), watch: () => ({ close: () => {} }) }));
+
+console.log('🧪 Finalizer fixture collection: filesystem');
+const { PATHS } = await import('../../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+console.log('🧪 Finalizer fixture collection: history and finalizer');
+const { loadHistory, saveHistory, mutateVideoHistory } = await import('./history.js');
+const { finalizeGeneratedVideo } = await import('./generateVideoHelpers.js');
+const { videoGenEvents } = await import('./events.js');
+console.log('🧪 Finalizer fixture collection: Reactor');
+const reactor = await import('./reactor.js');
+console.log('🧪 Finalizer fixture collection: local caller');
+const { spawnAndWatchVideo } = await import('./spawnWatch.js');
+const { videoJobState } = await import('./jobState.js');
+console.log('🧪 Finalizer fixture collection: ready');
+const { it, drain } = ownTestBodies(vitestIt);
+const operations = new Set();
+function own(fn) {
+ const run = Promise.resolve().then(fn);
+ const settled = run.then(() => {}, () => {});
+ operations.add(settled);
+ settled.then(() => operations.delete(settled));
+ return run;
+}
+const gates = [];
+const gate = () => {
+ const value = { entered: Promise.withResolvers(), finish: Promise.withResolvers() };
+ gates.push(value);
+ return value;
+};
+const settleTurn = () => new Promise(resolve => setImmediate(resolve));
+const pathOf = id => join(PATHS.videos, `${id}.mp4`);
+const ctx = (id, extras = {}) => ({
+ job: { status: 'running', clients: [] }, jobId: id, outputPath: pathOf(id), filename: `${id}.mp4`,
+ meta: { id, filename: `${id}.mp4`, prompt: 'Synthetic clip', modelId: 'fixture' },
+ actualSeed: 1, mutateHistory: mutateVideoHistory, ...extras,
+});
+async function produce(id) { await writeFile(pathOf(id), `video:${id}`); }
+async function copyAssets() {
+ const root = join(PATHS.data, 'copied');
+ await rm(root, { recursive: true, force: true });
+ await mkdir(root);
+ await cp(PATHS.videos, join(root, 'videos'), { recursive: true });
+ await cp(PATHS.videoThumbnails, join(root, 'posters'), { recursive: true });
+ return root;
+}
+async function copyHistory(root) {
+ await cp(join(PATHS.data, 'video-history.json'), join(root, 'history.json'));
+ return JSON.parse(await readFile(join(root, 'history.json'), 'utf8'));
+}
+function missing(root, history) {
+ return history.flatMap(row => [
+ row.filename && join(root, 'videos', row.filename),
+ row.thumbnail && join(root, 'posters', row.thumbnail),
+ ].filter(path => path && !existsSync(path)));
+}
+beforeEach(async () => {
+ Object.assign(state, { bypass: false, admission: null, historyGate: null, unlinkGate: null,
+ faststartGate: null, failHistory: false, failFaststart: false, thumbnailFailure: null, child: null, input: null, localChild: null });
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.videoThumbnails, { recursive: true });
+ await saveHistory([]);
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ jwt: 'example-jwt' }) })));
+ vi.stubEnv('REACTOR_API_KEY', '');
+});
+afterEach(async () => {
+ for (const value of gates.splice(0)) value.finish.resolve();
+ reactor.cancelAll();
+ await vi.waitFor(() => expect(reactor.getActiveJob()).toBeNull());
+ if (state.localChild && state.localChild.exitCode == null) {
+ state.localChild.exitCode = 1;
+ state.localChild.emit('close', 1, null);
+ }
+ while (operations.size) await Promise.all(operations);
+ await drain();
+ videoGenEvents.removeAllListeners();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ videoJobState.jobs.clear();
+ videoJobState.activeProcess = null;
+ state.failHistory = false;
+ await rm(PATHS.videos, { recursive: true, force: true });
+ await rm(PATHS.videoThumbnails, { recursive: true, force: true });
+});
+afterAll(async () => { await drain(); await cleanupTempDataRoots(); });
+
+describe('generated-video backup publication', () => {
+ it('holds a finalizer out of a cut; bypass publishes between asset and history copies', async () => {
+ const cut = await acquireBackupSnapshotCut();
+ let run;
+ try {
+ const copied = await copyAssets();
+ await produce('held');
+ const context = ctx('held');
+ state.admission = Promise.withResolvers();
+ run = own(() => finalizeGeneratedVideo(context));
+ await state.admission.promise;
+ await settleTurn();
+ expect(context.job.status).toBe('running');
+ expect(await copyHistory(copied)).toEqual([]);
+ } finally { cut(); await run; }
+ await saveHistory([]);
+ await rm(PATHS.videos, { recursive: true, force: true });
+ await mkdir(PATHS.videos);
+ state.bypass = true;
+ const copied = await copyAssets();
+ await produce('bypassed');
+ await finalizeGeneratedVideo(ctx('bypassed'));
+ expect(missing(copied, await copyHistory(copied))).toHaveLength(2);
+ });
+
+ for (const phase of ['faststart', 'history']) it(`drains an active ${phase} through the copied history pair`, async () => {
+ await produce('drain');
+ const blocked = gate();
+ if (phase === 'faststart') state.faststartGate = blocked;
+ else state.historyGate = blocked;
+ const publication = {};
+ const context = ctx('drain', { publication });
+ const run = own(() => finalizeGeneratedVideo(context));
+ await blocked.entered.promise;
+ let acquired = false;
+ const cutting = acquireBackupSnapshotCut().then(cut => { acquired = true; return cut; });
+ let cut;
+ try {
+ await settleTurn();
+ expect(acquired).toBe(false);
+ expect(context.job.status).toBe('running');
+ blocked.finish.resolve();
+ await run;
+ cut = await cutting;
+ const root = await copyAssets();
+ const history = await copyHistory(root);
+ expect(history).toHaveLength(1);
+ expect(missing(root, history)).toEqual([]);
+ expect(publication.committed).toBe(true);
+ } finally {
+ blocked.finish.resolve();
+ await run.catch(() => {});
+ (cut || await cutting)();
+ }
+ });
+
+ it('drains failed-history rollback before a cut can copy partial outputs', async () => {
+ await produce('rollback');
+ state.failHistory = true;
+ const blocked = gate();
+ blocked.matches = path => path === pathOf('rollback');
+ state.unlinkGate = blocked;
+ const context = ctx('rollback');
+ const run = own(() => finalizeGeneratedVideo(context)).then(() => null, error => error);
+ await blocked.entered.promise;
+ let acquired = false;
+ const cutting = acquireBackupSnapshotCut().then(cut => { acquired = true; return cut; });
+ let cut;
+ try {
+ await settleTurn();
+ expect(acquired).toBe(false);
+ blocked.finish.resolve();
+ expect((await run).message).toBe('history commit failed');
+ cut = await cutting;
+ const root = await copyAssets();
+ expect(await copyHistory(root)).toEqual([]);
+ expect(await readdir(PATHS.videos)).toEqual([]);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ expect(context.job.status).toBe('running');
+ } finally {
+ blocked.finish.resolve();
+ await run;
+ (cut || await cutting)();
+ }
+ });
+
+ for (const phase of ['faststart', 'poster']) it(`removes a failed ${phase}'s pre-tracked partial bytes`, async () => {
+ await produce('partial');
+ if (phase === 'faststart') state.failFaststart = true;
+ else state.thumbnailFailure = 'throw';
+ await expect(finalizeGeneratedVideo(ctx('partial'))).rejects.toThrow(/failed/);
+ expect(await loadHistory()).toEqual([]);
+ expect(await readdir(PATHS.videos)).toEqual([]);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ });
+
+ it('keeps thumbnail-less compatibility and removes the partial poster', async () => {
+ await produce('no-poster');
+ state.thumbnailFailure = 'null';
+ expect(await finalizeGeneratedVideo(ctx('no-poster'))).toBeNull();
+ expect(await loadHistory()).toEqual([expect.objectContaining({ thumbnail: null })]);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ expect(existsSync(pathOf('no-poster'))).toBe(true);
+ });
+
+ it('preserves the committed pair when completion dispatch throws', async () => {
+ await produce('dispatch');
+ const publication = {};
+ vi.spyOn(videoGenEvents, 'emit').mockImplementation(() => { throw new Error('dispatch failed'); });
+ await expect(finalizeGeneratedVideo(ctx('dispatch', { publication }))).rejects.toThrow('dispatch failed');
+ expect(publication.committed).toBe(true);
+ const root = await copyAssets();
+ expect(missing(root, await copyHistory(root))).toEqual([]);
+ expect(await loadHistory()).toHaveLength(1);
+ });
+
+ it('preserves an already committed nonterminal member when the next member fails', async () => {
+ const job = { status: 'running', clients: [] };
+ await produce('member-one');
+ await finalizeGeneratedVideo(ctx('member-one', { job, terminal: false }));
+ expect(job.status).toBe('running');
+ await produce('member-two');
+ state.failHistory = true;
+ await expect(finalizeGeneratedVideo(ctx('member-two', { job, terminal: false }))).rejects.toThrow('history commit failed');
+ expect((await loadHistory()).map(row => row.id)).toEqual(['member-one']);
+ expect(await readdir(PATHS.videos)).toEqual(['member-one.mp4']);
+ const root = await copyAssets();
+ expect(missing(root, await copyHistory(root))).toEqual([]);
+ });
+
+ it('local batch failure cleans only unpublished members through the real caller', async () => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 101, stdout: new EventEmitter(), stderr: new EventEmitter(),
+ exitCode: null, signalCode: null, killed: false,
+ kill: vi.fn(() => { child.killed = true; }),
+ });
+ state.localChild = child;
+ const job = { status: 'running', clients: [] };
+ const batch = [0, 1].map(index => ({ id: `batch-${index}`, filename: `batch-${index}.mp4`, index, seed: index + 1 }));
+ const failed = Promise.withResolvers();
+ videoGenEvents.on('failed', failed.resolve);
+ await spawnAndWatchVideo({
+ ...ctx('batch-job', { job }), batch, cleanupTempFiles: async () => {},
+ stepwiseDir: join(PATHS.data, 'preview'), bin: 'synthetic-python', args: ['synthetic-render'],
+ model: { runtime: 'fixture' }, modelId: 'fixture', width: 512, height: 512,
+ numFrames: 25, steps: 8, videoGenSettings: {},
+ });
+ await produce(batch[0].id);
+ child.stdout.emit('data', `${JSON.stringify({ video_path: pathOf(batch[0].id), batch_index: 0, seed: 1 })}\n`);
+ await vi.waitFor(async () => expect((await loadHistory()).map(row => row.id)).toEqual([batch[0].id]));
+ state.failHistory = true;
+ await produce(batch[1].id);
+ child.stdout.emit('data', `${JSON.stringify({ video_path: pathOf(batch[1].id), batch_index: 1, seed: 2 })}\n`);
+ await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGTERM'));
+ child.exitCode = 1;
+ child.emit('close', 1, null);
+ await failed.promise;
+ const root = await copyAssets();
+ const history = await copyHistory(root);
+ expect(history.map(row => row.id)).toEqual([batch[0].id]);
+ expect(await readdir(PATHS.videos)).toEqual([batch[0].filename]);
+ expect(missing(root, history)).toEqual([]);
+ });
+
+ for (const failure of ['cleanup rejection', 'child error']) it(`local close drains an accepted member before ${failure} can discard it`, async () => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 101, stdout: new EventEmitter(), stderr: new EventEmitter(),
+ exitCode: null, signalCode: null, killed: false, kill: vi.fn(),
+ });
+ state.localChild = child;
+ const batch = [0, 1].map(index => ({ id: `close-${index}`, filename: `close-${index}.mp4`, index, seed: index + 1 }));
+ const failed = Promise.withResolvers();
+ videoGenEvents.on('failed', failed.resolve);
+ await spawnAndWatchVideo({
+ ...ctx('close-job'), batch,
+ cleanupTempFiles: async () => { if (failure === 'cleanup rejection') throw new Error('cleanup failed'); },
+ stepwiseDir: join(PATHS.data, 'preview'), bin: 'synthetic-python', args: ['synthetic-render'],
+ model: { runtime: 'fixture' }, modelId: 'fixture', width: 512, height: 512,
+ numFrames: 25, steps: 8, videoGenSettings: {},
+ });
+ await produce(batch[0].id);
+ state.historyGate = gate();
+ child.stdout.emit('data', `${JSON.stringify({ video_path: pathOf(batch[0].id), batch_index: 0, seed: 1 })}\n`);
+ await state.historyGate.entered.promise;
+ if (failure === 'child error') child.emit('error', new Error('child failed'));
+ child.exitCode = 0;
+ child.emit('close', 0, null);
+ try {
+ await settleTurn();
+ expect(existsSync(pathOf(batch[0].id))).toBe(true);
+ expect(existsSync(join(PATHS.videoThumbnails, `${batch[0].id}.jpg`))).toBe(true);
+ expect(await loadHistory()).toEqual([]);
+ } finally { state.historyGate.finish.resolve(); }
+ await failed.promise;
+ const root = await copyAssets();
+ const history = await copyHistory(root);
+ expect(history.map(row => row.id)).toEqual([batch[0].id]);
+ expect(missing(root, history)).toEqual([]);
+ });
+
+ it('Reactor refuses cancellation during publication and preserves output after a dispatch error', async () => {
+ const original = videoGenEvents.emit.bind(videoGenEvents);
+ const failed = Promise.withResolvers();
+ videoGenEvents.on('failed', failed.resolve);
+ vi.spyOn(videoGenEvents, 'emit').mockImplementation((type, ...args) => {
+ if (type === 'completed') throw new Error('dispatch failed');
+ return original(type, ...args);
+ });
+ const job = await reactor.generateVideo({ prompt: 'Synthetic clip', seconds: 6 });
+ await vi.waitFor(() => expect(state.input).not.toBeNull());
+ await writeFile(state.input.outputPath, 'captured video');
+ state.historyGate = gate();
+ state.child.stdout.emit('data', `${JSON.stringify({ type: 'complete', frames: 144, seconds: 6, clipId: 'example-clip' })}\n`);
+ state.child.emit('close', 0);
+ await state.historyGate.entered.promise;
+ expect(reactor.cancel(job.jobId)).toBe(false);
+ state.historyGate.finish.resolve();
+ await failed.promise;
+ await vi.waitFor(() => expect(reactor.getActiveJob()).toBeNull());
+ const root = await copyAssets();
+ const history = await copyHistory(root);
+ expect(history).toHaveLength(1);
+ expect(missing(root, history)).toEqual([]);
+ });
+});
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index 5df5715d59..733f11c04c 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -9,11 +9,13 @@
*/
import { existsSync, statSync } from 'fs';
+import { join } from 'path';
import { broadcastSse } from '../../lib/sseUtils.js';
import {
generateThumbnail, optimizeForStreaming, probeFrameCount, probeVideoDuration,
} from '../../lib/ffmpeg.js';
-import { formatBytes } from '../../lib/fileUtils.js';
+import { formatBytes, PATHS, unlinkGuarded } from '../../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { videoGenEvents } from './events.js';
@@ -740,6 +742,18 @@ export function bufferChildExit(proc, { bufferOutput = false } = {}) {
};
}
+// Only fresh, unreferenced outputs belong here. Callers retain the publication
+// latch so a later notification failure never sends committed bytes to cleanup.
+export async function discardUnpublishedVideo({ jobId, outputPath }) {
+ return withBackupAssetPublication(async () => {
+ const results = await Promise.allSettled([
+ outputPath, `${outputPath}.fs.mp4`, join(PATHS.videoThumbnails, `${jobId}.jpg`),
+ ].map(path => unlinkGuarded(path)));
+ const failed = results.find(result => result.status === 'rejected' && result.reason?.code !== 'ENOENT');
+ if (failed) throw failed.reason;
+ });
+}
+
/**
* Success path of generateVideo's `close` handler: faststart-optimize the
* output, generate a thumbnail, prepend the history entry, and emit the
@@ -755,59 +769,73 @@ export function bufferChildExit(proc, { bufferOutput = false } = {}) {
* @param {number} ctx.actualSeed
* @param {(mutator: (h: Array) => Array) => Promise<Array>} ctx.mutateHistory - serialized read-modify-write on the shared history file (mutateVideoHistory)
* @param {boolean} [ctx.terminal=true] - False persists a batch member without completing its queue job.
+ * @param {object} [ctx.publication] - Caller latch; committed is set before notifications.
* @param {number} [ctx.startedAtMs] - Date.now() captured just before the child
* spawned. Defaults to `job.renderStartedAtMs`, which generateVideo stamps.
*/
-export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory, startedAtMs = job?.renderStartedAtMs, terminal = true }) {
- if (terminal) job.status = 'complete';
- await optimizeForStreaming(outputPath);
- const thumbnail = await generateThumbnail(outputPath, jobId);
- // Serialized append through the shared history tail so a concurrent write
- // path (a full-video download completing, another render finalizing) can't
- // read the same stale array and clobber this record on save.
- //
- // Persist the runtime fingerprint captured from the child's startup RUNTIME:
- // line (set on `job` by makeVideoGenLineHandler) so each history record
- // self-documents the exact ltx/mlx/torch + chip + OS stack it rendered on.
- // Absent (sentinel) when the runtime didn't emit one — e.g. the bare
- // `mlx_video.generate_av` path we don't control.
- //
- // Wall-clock render timing (#3801) is what makes a future render estimable:
- // videoGen/eta.js calibrates its cost model purely from these measurements.
- // Stamped ONLY when we actually observed the spawn instant — an entry with
- // no `renderMs` is an explicit absent sentinel that the estimator skips,
- // which is why the timing spread is conditional rather than defaulted to 0
- // (a zero-duration sample would drag every estimate toward "instant").
- // The window measured is spawn → output finalized, i.e. what the user waits
- // through, including the thumbnail/faststart tail above.
- const timing = renderTimingFields(startedAtMs);
- await mutateHistory((history) => {
- history.unshift({
- ...meta,
- thumbnail,
- ...timing,
- ...(job.runtime ? { runtime: job.runtime } : {}),
- // What the speed profile actually resolved to at render time (#4875).
- // `meta.speedProfileId` above is the REQUEST; this is the outcome, so a
- // render whose TeaCache or distilled adapter was unavailable reads back
- // as degraded instead of as a full speed claim. Absent on every quality
- // render and on runners that don't report one.
- ...(job.speedProfile ? { speedProfileApplied: job.speedProfile } : {}),
- // Whether the draft decoder actually decoded this clip (#5423).
- // `meta.draftDecode` above is the REQUEST that survived every server-side
- // gate; this is the outcome, so a render whose decoder failed to load
- // reads back as a full decode instead of claiming a draft one. Absent on
- // every full-decode render and on runners that don't report one.
- ...(job.draftDecode ? { draftDecodeApplied: job.draftDecode } : {}),
- // What block streaming actually resolved to at render time (#6499).
- // `meta.streamingMode` above is the REQUEST; this is the outcome —
- // whether the pinned pipeline had the parameter, the RAM-based 'auto'
- // decision, and (when active) the render's peak MLX memory. Absent on
- // a resident-by-default render and on runners that don't report one.
- ...(job.streamingPolicy ? { streamingPolicyApplied: job.streamingPolicy } : {}),
- });
- return history;
+export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory, startedAtMs = job?.renderStartedAtMs, terminal = true, publication = {} }) {
+ const thumbnail = await withBackupAssetPublication(async () => {
+ try {
+ await optimizeForStreaming(outputPath);
+ const thumbnail = await generateThumbnail(outputPath, jobId);
+ // ffmpeg may leave a partial poster even when it returns no thumbnail.
+ if (!thumbnail) await unlinkGuarded(join(PATHS.videoThumbnails, `${jobId}.jpg`)).catch(error => {
+ if (error.code !== 'ENOENT') throw error;
+ });
+ // Serialized append through the shared history tail so a concurrent write
+ // path (a full-video download completing, another render finalizing) can't
+ // read the same stale array and clobber this record on save.
+ //
+ // Persist the runtime fingerprint captured from the child's startup RUNTIME:
+ // line (set on `job` by makeVideoGenLineHandler) so each history record
+ // self-documents the exact ltx/mlx/torch + chip + OS stack it rendered on.
+ // Absent (sentinel) when the runtime didn't emit one — e.g. the bare
+ // `mlx_video.generate_av` path we don't control.
+ //
+ // Wall-clock render timing (#3801) is what makes a future render estimable:
+ // videoGen/eta.js calibrates its cost model purely from these measurements.
+ // Stamped ONLY when we actually observed the spawn instant — an entry with
+ // no `renderMs` is an explicit absent sentinel that the estimator skips,
+ // which is why the timing spread is conditional rather than defaulted to 0
+ // (a zero-duration sample would drag every estimate toward "instant").
+ // The window measured is spawn → output finalized, i.e. what the user waits
+ // through, including the thumbnail/faststart tail above.
+ const timing = renderTimingFields(startedAtMs);
+ await mutateHistory((history) => {
+ history.unshift({
+ ...meta,
+ thumbnail,
+ ...timing,
+ ...(job.runtime ? { runtime: job.runtime } : {}),
+ // What the speed profile actually resolved to at render time (#4875).
+ // `meta.speedProfileId` above is the REQUEST; this is the outcome, so a
+ // render whose TeaCache or distilled adapter was unavailable reads back
+ // as degraded instead of as a full speed claim. Absent on every quality
+ // render and on runners that don't report one.
+ ...(job.speedProfile ? { speedProfileApplied: job.speedProfile } : {}),
+ // Whether the draft decoder actually decoded this clip (#5423).
+ // `meta.draftDecode` above is the REQUEST that survived every server-side
+ // gate; this is the outcome, so a render whose decoder failed to load
+ // reads back as a full decode instead of claiming a draft one. Absent on
+ // every full-decode render and on runners that don't report one.
+ ...(job.draftDecode ? { draftDecodeApplied: job.draftDecode } : {}),
+ // What block streaming actually resolved to at render time (#6499).
+ // `meta.streamingMode` above is the REQUEST; this is the outcome —
+ // whether the pinned pipeline had the parameter, the RAM-based 'auto'
+ // decision, and (when active) the render's peak MLX memory. Absent on
+ // a resident-by-default render and on runners that don't report one.
+ ...(job.streamingPolicy ? { streamingPolicyApplied: job.streamingPolicy } : {}),
+ });
+ return history;
+ });
+ publication.committed = true;
+ return thumbnail;
+ } catch (error) {
+ await discardUnpublishedVideo({ jobId, outputPath });
+ throw error;
+ }
});
+ if (terminal) job.status = 'complete';
console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);
if (terminal) {
broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index 87d5d8f58b..beac85357c 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -3,6 +3,7 @@ import { writeFileSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { EventEmitter } from 'events';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, bufferChildExit, isNativeTeardownAbort, verifyPostCompletionOutputs, POST_COMPLETION_ABORT_RUNTIME, RENDER_INPUTS_VERSION, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
describe('parseByteProgress', () => {
@@ -110,6 +111,10 @@ vi.mock('../../lib/ffmpeg.js', () => ({
probeFrameCount: probeMock.frames,
probeVideoDuration: probeMock.duration,
}));
+vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-video-finalizer-metadata-'),
+}));
+afterAll(() => cleanupTempDataRoots());
const PYTHON_NOISE_RE = /^(Loading|Fetching|tokenizer|Some weights)/;
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index da04a23c74..4128b66049 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -33,7 +33,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
import { videoGenEvents } from './events.js';
-import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
+import { discardUnpublishedVideo, finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { noImageReason, deriveAspectRatio, GROK_ASPECT_RATIOS } from '../imageGen/grok.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
@@ -248,6 +248,7 @@ async function runGrokVideo(job, jobId, bin, args, {
}, GROK_VIDEO_TIMEOUT_MS);
let terminalStarted = false;
+ const publication = {};
let processError;
proc.on('error', (err) => {
if (terminalStarted) return;
@@ -305,15 +306,14 @@ async function runGrokVideo(job, jobId, bin, args, {
// SSE complete + videoGenEvents 'completed' — identical to local
// renders so every downstream consumer (history grid, media index,
// completion hooks) sees the same contract.
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory, publication });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
await cleanup();
+ if (!publication.committed) await discardUnpublishedVideo({ jobId, outputPath }).catch(retainOwnership);
retainOwnership(err);
- // finalizeGeneratedVideo marks job.status='complete' BEFORE its async
- // post-processing (faststart/thumbnail/history) — a throw there must
- // still surface as a terminal failure or the queue's job stays
- // 'running' until the watchdog. Force past the idempotence guard.
+ // A dispatch failure can follow a durable commit; preserve its bytes and
+ // still surface a terminal failure past the completion idempotence guard.
finalizeJobFailure(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`, { force: true });
}
});
diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.js
index f9f4a486c3..1f4d5593fb 100644
--- a/server/services/videoGen/grok.test.js
+++ b/server/services/videoGen/grok.test.js
@@ -65,6 +65,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
actual.PATHS.videos = FAKE_VIDEOS_DIR;
actual.PATHS.data = FAKE_DATA_DIR;
+ actual.PATHS.videoThumbnails = join(TEST_ROOT, 'thumbnails');
return {
...actual,
ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index 2ac89f0619..d7e039aa26 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -315,10 +315,10 @@ async function runReactorVideo(job, jobId, {
// Durable publication owns the output from this point until it settles.
// No await may separate the last cancellation check from this boundary.
entry.finalizing = true;
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, aspect: frame.aspect, width: frame.canvas.width, height: frame.canvas.height, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory });
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, aspect: frame.aspect, width: frame.canvas.width, height: frame.canvas.height, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory, publication: entry });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
- await rm(outputPath, { force: true }).catch((cleanupError) => { console.log(`⚠️ Reactor cleanup: could not remove failed output ${outputPath} (${cleanupError.code})`); });
+ if (!entry.committed) await rm(outputPath, { force: true }).catch((cleanupError) => { console.log(`⚠️ Reactor cleanup: could not remove failed output ${outputPath} (${cleanupError.code})`); });
// A continuation names a clip reactor rendered in an EARLIER session, and
// reactor decides whether it still holds it. Say so on the failure rather
// than leaving the user re-reading a prompt that was never the problem.
@@ -329,7 +329,7 @@ async function runReactorVideo(job, jobId, {
} finally {
await rm(`${outputPath}.capture`, { recursive: true, force: true }).catch((err) => { console.log(`⚠️ Reactor cleanup: could not remove capture dir ${outputPath}.capture (${err.code})`); });
if (frame.fittedPath) await rm(frame.fittedPath, { force: true }).catch((err) => { console.log(`⚠️ Reactor cleanup: could not remove fitted frame ${frame.fittedPath} (${err.code})`); });
- if (entry.aborted) await rm(outputPath, { force: true }).catch((err) => { console.log(`⚠️ Reactor cleanup: could not remove aborted output ${outputPath} (${err.code})`); });
+ if (entry.aborted && !entry.committed) await rm(outputPath, { force: true }).catch((err) => { console.log(`⚠️ Reactor cleanup: could not remove aborted output ${outputPath} (${err.code})`); });
activeRequests.delete(jobId);
activeJobs.delete(jobId);
}
diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.js
index f8f22fa1d3..bb8f475d7a 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -21,6 +21,7 @@ import { safeChildProcessEnv } from '../../lib/processEnv.js';
import {
makeVideoGenLineHandler,
finalizeGeneratedVideo,
+ discardUnpublishedVideo,
isWatchdogSuccess,
isNativeTeardownAbort,
verifyPostCompletionOutputs,
@@ -168,6 +169,13 @@ export async function spawnAndWatchVideo({
const expectedOutputPaths = batch
? batch.map((item) => join(PATHS.videos, item.filename))
: [outputPath];
+ const publications = new Map(expectedOutputPaths.map(path => [path, {}]));
+ const discardFailedOutputs = async () => {
+ for (const [index, path] of expectedOutputPaths.entries()) {
+ if (publications.get(path).committed) continue;
+ await discardUnpublishedVideo({ jobId: batch ? batch[index].id : jobId, outputPath: path }).catch(retainOwnership);
+ }
+ };
// ── one render child, fully wired ──────────────────────────────────────────
// Everything per-CHILD lives in here — the process handle, the completion watchdog, the
@@ -321,6 +329,7 @@ export async function spawnAndWatchVideo({
}
receivedOutputs += 1;
completedOutputs.add(itemPath);
+ publications.get(itemPath).started = true;
outputTail = outputTail.then(async () => {
const thumbnail = await finalizeGeneratedVideo({
job, jobId: item.id, outputPath: itemPath, filename: itemFilename,
@@ -328,6 +337,7 @@ export async function spawnAndWatchVideo({
actualSeed: item.seed, mutateHistory: mutateVideoHistory,
// Batch timings include shared startup and cannot train single-render ETAs.
startedAtMs: null, terminal: false,
+ publication: publications.get(itemPath),
});
batchResults.push({ filename: itemFilename, seed: item.seed, thumbnail, path: `/data/videos/${itemFilename}` });
const message = `Saved ${batchResults.length}/${batch.length} videos`;
@@ -425,6 +435,10 @@ export async function spawnAndWatchVideo({
// no terminal SSE. The catch routes any failure through the job's error
// finalizer so the client still gets a terminal 'failed' event.
try {
+ // Accepted batch members may still be at their history commit when the
+ // child closes. Drain every finalizer before cleanup or a recorded child
+ // error can enter the discard path; admission itself is not a mutex.
+ await outputTail;
// Cleanup the resized temp images if we made them. Track via flags rather
// than a path-prefix check — tmpdir() can return a symlinked path
// (macOS /var → /private/var) so startsWith() can silently miss.
@@ -437,7 +451,6 @@ export async function spawnAndWatchVideo({
// output file is already on disk and non-empty: the render wrote its
// result, but the child hung during teardown. A kill with no output on
// disk still fails loudly below.
- await outputTail;
if (batchError) throw batchError;
const allOutputsFinalized = !batch || batchResults.length === batch.length;
const watchdogSuccess = allOutputsFinalized
@@ -470,6 +483,7 @@ export async function spawnAndWatchVideo({
}
if (unforgivenExit && !teardownRecovered) {
+ await discardFailedOutputs();
job.status = 'error';
let reason;
const failure = diagnostics.failure({ prompts: [meta?.prompt, meta?.negativePrompt] });
@@ -520,10 +534,11 @@ export async function spawnAndWatchVideo({
broadcastSse(job, { type: 'complete', result });
videoGenEvents.emit('completed', { generationId: jobId, ...result });
} else {
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory });
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory, publication: publications.get(outputPath) });
}
}
} catch (err) {
+ await discardFailedOutputs();
if (err !== childError) retainOwnership();
// Finalize/teardown threw — fail the job loudly instead of crashing the
// process. The job may already be partway through finalize, so force the
@@ -626,6 +641,9 @@ export async function spawnAndWatchVideo({
// excluded by construction rather than by a list that could drift.
const maybeRelaunchForPromptEncoding = async ({ code, signal, childKilled, cancelEpochAtClose, stderr }) => {
if (code === 0) return false;
+ // A batch member already in history must never be rendered again over its
+ // committed filename by a whole-batch prompt-encode retry.
+ if ([...publications.values()].some(publication => publication.started || publication.committed)) return false;
// A child PortOS killed on purpose — a user cancel, or either watchdog — is
// never a spontaneous Metal abort to recover from, whatever signal it
// finally landed on. Without this a cancel that raced an in-flight abort
diff --git a/server/services/videoGen/spawnWatch.test.js b/server/services/videoGen/spawnWatch.test.js
index 8fb5e5e20c..d0379370a9 100644
--- a/server/services/videoGen/spawnWatch.test.js
+++ b/server/services/videoGen/spawnWatch.test.js
@@ -21,8 +21,9 @@ vi.mock('../../lib/detachedSpawn.js', () => ({ spawnDetached: mocks.spawn }));
vi.mock('../../lib/childProcess.js', () => ({ spawn: () => new EventEmitter() }));
vi.mock('fs', async (importOriginal) => ({ ...(await importOriginal()), watch: mocks.watch }));
vi.mock('../../lib/fileUtils.js', () => ({
- PATHS: { videos: '/mock/videos' },
+ PATHS: { videos: '/mock/videos', videoThumbnails: '/mock/thumbnails' },
rmGuarded: mocks.rm,
+ unlinkGuarded: vi.fn(async () => {}),
formatBytes: vi.fn(),
}));
vi.mock('../../lib/ffmpeg.js', () => ({